How to calculate the sum of two matrices of order N x N with c plus plus
In this example, written in c++, the code shows how to perform the sum of two matrices of order N x N.
/**
Given two matrices of size n x n,
Calculate the matrix sum
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
// Initialize random number generator
srand(time(NULL));
// Define the length of the array
const int N = 5;
// Define two matrices of dimension N x N
int m1 [N][N];
int m2 [N][N];
// Define the matrix sum
int sum [N][N];
// Fill the matrices m1 and m2 with random integers
for(int i=0; i<N; i++)
{
for(int j=0; j<N; j++)
{
m1[i][j] = (rand()%10)+1;
m2[i][j] = (rand()%10)+1;
}
}
// Showing the matrix m1
printf("MATRIX M1\n");
for(int i=0; i<N; i++)
{
for(int j=0; j<N; j++)
{
printf( "%d \t", m1[i][j]);
}
printf( "\n");
}
printf("\n");
// Showing the matrix m2
printf("MATRIX M2\n");
for(int i=0; i<N; i++)
{
for(int j=0; j<N; j++)
{
printf( "%d \t", m2[i][j]);
}
printf( "\n");
}
// Calculating the matrix sum
for(int i=0; i<N; i++)
{
for(int j=0; j<N; j++)
{
sum[i][j] = m1[i][j] + m2[i][j];
}
}
printf("\n");
// Showing the matrix sum
printf("MATRIX SUM\n");
for(int i=0; i<N; i++)
{
for(int j=0; j<N; j++)
{
printf( "%d \t", sum[i][j]);
}
printf( "\n");
}
return 0;
}
This is the result:
MATRIX M1
8 2 4 1 4
8 2 1 7 2
10 3 7 3 4
2 5 2 3 3
7 10 1 10 2
MATRIX M2
9 10 4 2 8
5 8 8 5 5
5 5 1 1 8
5 1 5 8 1
3 10 5 7 2
MATRIX SUM
17 12 8 3 12
13 10 9 12 7
15 8 8 4 12
7 6 7 11 4
10 20 6 17 4