need a help for code.

how to add two N*N matrix?is this is a valid code?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  # include<iostream>
# include<conio.h>
using namespace std;
void main(){
int a[5][5];
int b[5][5];
int c[5][5];
for(int i=0;i<5;i++)
{
	for(int j=0;j<5;j++)
	{
		a[i][j]=5;
		b[i][j]=6;
		c[i][j]=a[i][j]+b[i][j];
         cout<<"the sum is"<<c[i][j];
	}
	getch();

}}
Last edited on
closed account (Dy7SLyTq)
right off the bat i see void main. make it int. secondly your formatting is horrible. other than that, it looks fine

cout<<"the sum is"<<sum[i][j];
Where did you define sum ?

Overall, I don't like the idea of combining the initialisation of a and b with the other operations, (1) adding the two arrays and (2) outputting the results. It may be a fraction more efficient to do things this way, but the code would be much clearer and easier to either maintain or reuse if you kept such unrelated actions separate from each other.
closed account (Dy7SLyTq)
ah didnt notice that. in my mind it was c
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
53
54
55
56
# include<iostream>
# include<conio.h>
using namespace std;
void main()
{
	int a[3][3];
	int b[3][3];
	int sum[3][3];
	

	for(int i=0;i<3;i++)
	{
		
		for(int j=0;j<3;j++)
		{
			cout<<"Enter Value for loaction : ("<< i << "," << j << ") " ; //you can use "i+1" and "j+1" instead of "i" and "j" to understand better for locations.
			cin>>a[i][j];
			cout<<endl; 
		}
	
	}  // i am copying the same code as above for getiing input in b matrix but if you are aware of functions you can write it in a function and use twice.

		for(int i=0;i<3;i++)
	{
		
		for(int j=0;j<3;j++)
		{
			cout<<"Enter Value for loaction : ("<< i << "," << j << ") " ; //you can use "i+1" and "j+1" instead of "i" and "j" to understand better for locations.
			cin>>b[i][j];
			cout<<endl; 
		}
	
	}

	for (int i=0;i<3;i++)
	{
		for( int j=0;j<3;j++ )
		{
			sum[i][j]=a[i][j]+b[i][j];
		}

	}

	cout<<endl<<endl;

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

		for( int j=0;j<3;j++ )
		{
			cout<<sum[i][j]<< " " ;
		}
		cout<<endl;
	}
	getch();
}
Last edited on
Topic archived. No new replies allowed.