In this example we will show you how to add two matrix
#include <iostream>
using namespace std;
#define N 4
void add(int A[][N], int B[][N], int C[][N]){
int i,j;
for(i = 0; i < N; i++){
for(j = 0; j < N; j++){
C[i][j] = A[i][j] + B[i][j];
}
}
}
int main(){
int arr1[N][N] = {{1,1,1,1},
{2,2,2,2},
{3,3,3,3}};
int arr2[N][N] = {{3,3,3,3},
{2,2,2,2},
{1,1,1,1}};
int arr3[N][N],i,j;
add(arr1,arr2,arr3);
cout<<"print add Array"<<endl;
for(i = 0; i < N; i++){
for(j = 0; j < N; j++)
{
cout<<arr3[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
Output:
4 4 4 4
4 4 4 4
4 4 4 4
0 0 0 0
Explanation:
Step 1: Define a Constant N
- The macro
#define N 4
is used to define the size of the matrix (i.e., 4×4). This means the matrix will have 4 rows and 4 columns.
#define N 4
Step 2: Matrix Addition Function
- The function
add
takes three 2D arrays (A
,B
, andC
) as input. It adds corresponding elements from matrixA
andB
, then stores the result in matrixC
.
void add(int A[][N], int B[][N], int C[][N]) {
int i, j;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
C[i][j] = A[i][j] + B[i][j]; // Adding corresponding elements
}
}
}
- Two
for
loops are used to iterate through all the elements in the 4×4 matrices. - The values at position
[i][j]
in both matricesA
andB
are added together and stored in matrixC
.
Step 3: Main Function
- The
main()
function initializes two 4×4 matricesarr1
andarr2
with hardcoded values. An empty matrixarr3
is also declared to store the result of the addition.
int main() {
int arr1[N][N] = {{1,1,1,1},
{2,2,2,2},
{3,3,3,3}}; // Matrix A
int arr2[N][N] = {{3,3,3,3},
{2,2,2,2},
{1,1,1,1}}; // Matrix B
int arr3[N][N], i, j; // Matrix C for storing the result
- Here, only three rows are initialized in
arr1
andarr2
, but the matrices are declared as 4×4 (N=4
). The uninitialized rows will contain garbage values or zeros depending on the compiler’s behavior.
Step 4: Calling the Addition Function
- The function
add(arr1, arr2, arr3)
is called to perform the matrix addition. This will populate matrixarr3
with the sum of corresponding elements fromarr1
andarr2
.
add(arr1, arr2, arr3); // Call the function to add matrices
Step 5. Print the Resulting Matrix
- The code then prints the result of the matrix addition stored in
arr3
using another set of nested loops.
cout << "print add Array" << endl;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
cout << arr3[i][j] << " "; // Print each element in matrix C
}
cout << endl; // Move to the next row after printing one row
}
return 0;
}