Latest Post

C++ | Sum of Matrices using 2d Array

 

Introduction


This program is of sum of matrices using 2d arrays. The program below is given. The program is extendable by using more numbers for matrix.

Program of sum of matrices


1:  #include<iostream.h>  
2:  #include<conio.h>  
3:  void main()  
4:  {  
5:  //clear the screen.  
6:  clrscr();  
7:  //declare variable type int  
8:  int a[3][3],b[3][3],i,j;  
9:  //Input <span class="IL_AD" id="IL_AD5">the numbers</span> <span class="IL_AD" id="IL_AD8">of first</span> matix  
10:  cout<<"First Matrix"<<endl;  
11:  for(i=0;i<3;i++)  
12:  {  
13:  for(j=0;j<3;j++)  
14:  {  
15:  cout<<"Enter number :";  
16:  cin>>a[i][j];  
17:  }  
18:  }  
19:  //Input the numbers of <span class="IL_AD" id="IL_AD6">second</span> matix  
20:  cout<<"Second Matrix"<<endl;  
21:  for(i=0;i<3;i++)  
22:  {  
23:  for(j=0;j<3;j++)  
24:  {  
25:  cout<<"Enter number :";  
26:  cin>>b[i][j];  
27:  }  
28:  }  
29:  //display the sum of matrices  
30:  cout<<"Sum is"<<endl;  
31:  for(i=0;i<3;i++)  
32:  {  
33:  cout<<"\n";  
34:  for(j=0;j<3;j++)  
35:  {  
36:  cout<<a[i][j]+b[i][j]<<"t";  
37:  }  
38:  cout<<endl;  
39:  }  
40:  //get character  
41:  getch();  
42:  }  

Output :

First Matrix
Enter the number
1
Enter the number
2
Enter the number
3
Enter the number
4
Enter the number
5
Enter the number
6
Enter the number
7
Enter the number
8
Enter the number
9

Second Matrix
Enter the number
1
Enter the number
2
Enter the number
3
Enter the number
4
Enter the number
5
Enter the number
6
Enter the number
7
Enter the number
8
Enter the number
9

Sum is
2 4 6
8 10 12
14 16 18

How does it work
  1. You enter the number.
  2. The number is saved in respective array for first matrix.
  3. The number is saved in respective array for second matrix.
  4. Then numbers are added and printed to form of matrix.
Extending it

The program can be extended by using more numbers and making the matrix more bigger. You can also do the same program to subtract the matrices. Go ahead. Extend it.

Explanation.
  1. Include ‘iostream.h’ and ‘conio.h’ files.
  2. Add void main.
  3. Start program by first clearing the screen.
  4. Declare the variables as int (name them as you want.)
  5. Add the cout and cin of array.
  6. Add for loop to print the sum of matrices.
At the end

You learnt creating the C++ program of Sum of matrices using 2d array. So now enjoy the program.

Please comment on the post and share it.
And like it if you liked.

SHARE THIS POST

Author: Robin Saxena
I m computer science student and i Interested in cs, c/c++ programming, java, html ,Photography , Music , and generally connecting with others.

1 comment :