Time complexity of matrix addition

Implement the addition of 2x2 matrix in c++ and then give the asymptotic running time in O notation of it.(Note: Implementation should not be hardcoded and also give brief description of your solution)

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
 #include<iostream>
using namespace std;
int main()
{
	int mat1[3][3], mat2[3][3], i, j, mat3[3][3];
	cout<<"Enter matrix 1 elements :";
	for(i=0; i<3; i++)
	{
		for(j=0; j<3; j++)
		{
			cin>>mat1[i][j];
		}
	}
	cout<<"Enter matrix 2 elements :";
	for(i=0; i<3; i++)
	{
		for(j=0; j<3; j++)
		{
			cin>>mat2[i][j];
		}
	}
	cout<<"Adding the two matrix to form the third matrix .....\n";
	for(i=0; i<3; i++)
	{
		for(j=0; j<3; j++)
		{
			mat3[i][j]=mat1[i][j]+mat2[i][j];
		}
	}
	cout<<"The two matrix added successfully...!!";
	cout<<"The new matrix will be :\n";
	for(i=0; i<3; i++)
	{
		for(j=0; j<3; j++)
		{
			cout<<mat3[i][j]<<" ";
		}
		cout<<"\n";
	}

}


I am not getting how to calculate its time complexity!
I'm lost, too. Your question says 2x2 and your code refers to 3x3. Apparently, you weren't supposed to hard-code it either ...

Time complexity doesn't make much sense for a fixed-size matrix. Were you referring to adding two NxN matrices or adding N 2x2 matrices. (It makes rather a big difference.)
> Implement the addition of 2x2 matrix in c++
...
> Implementation should not be hardcoded
Having a constant would go a long way to helping you.
1
2
3
const int N = 3;
int mat1[N][N], mat2[N][N], i, j, mat3[N][N];
for(i=0; i<N; i++)



> and then give the asymptotic running time in O notation of it.
You don't work out the asymptotic behaviour just from a single chosen N written in one specific programming language.

Matrix addition is O(N2) regardless of your choice of language.
It's the nested loop nature of the algorithm which makes it so.
1
2
for(i=0; i<N; i++)
	for(j=0; j<N; j++)

matrix addition is O(N) where N = rows*cols or its N*N if you consider rows and cols distinctly. This is not contradictory, its just changing the how N is defined. Best case, worst case, average case and so on are ALL the EXACT same amount of work unless the matrix is sparse and the addition algorithm used is for sparse (you did not do that).
Last edited on
Topic archived. No new replies allowed.