5 Computer -- Programming II

Write a C program to read two 3x3 matrices and perform matrix addition/multiplication.

Write a C program to read two 3x3 matrices and perform matrix addition/multiplication.

#include <stdio.h>

int main()

{

    int a[3][3], b[3][3], c[3][3];

    int i, j, k, choice;


    printf("Enter the elements of first matrix:\n");

    for (i = 0; i < 3; i++) {

        for (j = 0; j < 3; j++) {

            scanf("%d", &a[i][j]);

        }

    }


    printf("Enter the elements of second matrix:\n");

    for (i = 0; i < 3; i++) {

        for (j = 0; j < 3; j++) {

            scanf("%d", &b[i][j]);

        }

    }


    printf("Enter your choice:\n");

    printf("1. Addition\n");

    printf("2. Multiplication\n");

    scanf("%d", &choice);


    switch (choice) {

        case 1:

            // Addition

            for (i = 0; i < 3; i++) {

                for (j = 0; j < 3; j++) {

                    c[i][j] = a[i][j] + b[i][j];

                }

            }

            printf("The sum of the two matrices is:\n");

            for (i = 0; i < 3; i++) {

                for (j = 0; j < 3; j++) {

                    printf("%d\t", c[i][j]);

                }

                printf("\n");

            }

            break;


        case 2:

            // Multiplication

            for (i = 0; i < 3; i++) {

                for (j = 0; j < 3; j++) {

                    c[i][j] = 0;

                    for (k = 0; k < 3; k++) {

                        c[i][j] += a[i][k] * b[k][j];

                    }

                }

            }

            printf("The product of the two matrices is:\n");

            for (i = 0; i < 3; i++) {

                for (j = 0; j < 3; j++) {

                    printf("%d\t", c[i][j]);

                }

                printf("\n");

            }

            break;


        default:

            printf("Invalid choice!\n");

            break;

    }


    return 0;

}


More questions on Programming II

Differentiate between structure and union.

Structures in Cis a user-defined data type available in C that allows to combining of data items of different kinds. Structures are used to represent a record.

Defining a structure:To define astructure, you must use thestructstatement. The struct statement defines a newdata type, with more than or equal to one member. The format of the struct statement is as follows:

struct [structure name] { member definition; member definition; ... member definition; }; (OR) struct [structure name] { member...
Close Open App