In this tutorial you will learn about the C Program to add two Matrices and its application with practical example.
C Program to Add Two Matrices
In this tutorial, we will learn to create a C program that will add Two Matrices using C programming.
Prerequisites
Before starting with the tutorial, we assume that you are the best aware of the following C programming topics:
- Operators in C Programming.
- Basic Input and Output function in C Programming.
- Basic C programming.
- For loop in C programming.
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 |
1. Declaring the variables for the program. 2. Taking the input size of matrix. 3. Taking the input elements of matrix. 4. Adding the matrices<strong>.</strong> 5. Printing the result<strong> Added Matrix</strong>. 6. End Program. |
Program to add Two Matrices:-
In today’s tutorial, we will add two matrices. First, we will take the size of the matrix from the user, and then we will take the input elements of the two matrices. Now we will add the two elements of the matrices. At last, we will print the result matrix after adding.
Program:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
/* C Program to Add Two Matrices */ #include<stdio.h> int main() { //Declaring the required vairables for the program. int i, j, rw, cl, a[10][10], b[10][10]; int Add[10][10]; //Taking the input size of the matrix. printf("\n Please Enter Number of rows and columns : "); scanf("%d %d", &i, &j); //Taking the elements of the First Matrix printf("\n Please Enter the First Matrix Elements\n"); for(rw = 0; rw < i; rw++) { for(cl = 0;cl < j;cl++) { scanf("%d", &a[rw][cl]); } } //Taking the elements of the second Matrix printf("\n Please Enter the Second Matrix Elements\n"); for(rw = 0; rw < i; rw++) { for(cl = 0;cl < j;cl++) { scanf("%d", &b[rw][cl]); } } //Adding the one matrix from another for(rw = 0; rw < i; rw++) { for(cl = 0;cl < j;cl++) { Add[rw][cl] = a[rw][cl] + b[rw][cl]; } } //Printing the Add matrix. printf("\n After Adding Matrix a from Matrix b = a + b \n"); for(rw = 0; rw < i; rw++) { for(cl = 0; cl < j; cl++) { printf("%d \t ", Add[rw][cl]); } printf("\n"); } return 0; } |
Output:-
In the above program, we have first initialized the required variable.
- a[10][10]= it will hold the integer value.
- rw = it will hold the integer value for the loop.
- cl = it will hold the integer value for the loop.
- i= it will hold the input integer value for rows.
- j= it will hold the input integer value for columns.
Taking the size and the elements of the two matrices from the user.
Adding the matrices one from another.
Printing the matrix after adding.