In: Computer Science
*****In C++***** Exercise #3: Develop a program (name it AddMatrices) that adds two matrices. The matrices must of the same size. The program defines method Addition() that takes two two-dimensional arrays of integers and returns their addition as a two-dimensional array. The program main method defines two 3-by-3 arrays of type integer. The method prompts the user to initialize the arrays. Then it calls method Addition(). Finally, it prints out the array retuned by method Addition(). Document your code, and organize and space the outputs properly as shown below. Sample run 1: Matrix A: 2 1 2 7 1 8 3 20 3 Matrix B: 1 1 1 1 1 1 1 1 1 A + B: 3 2 3 8 2 9 4 21 4 Sample run 2: Matrix A: 2 2 2 2 2 2 2 2 2 Matrix B: 2 2 2 2 2 2 2 2 2 A + B: 4 4 4 4 4 4 4 4 4
If you have any queries write a comment if understood upvote Thank you.
Here to return a two dimensional array i have used double pointer
SOLUTION:
#include <bits/stdc++.h>
using namespace std;
#define N 3
int** addition(int A[][N], int B[][N]);
// This function adds A[][] and B[][], and stores its resukt into a
double pointer
//and return that
int** addition(int A[][N], int B[][N])
{
int i, j;
//create a double pointer
int** C=0;
C=new int*[3];
//create its array in one dimesional i.e rows
for (i = 0; i < N; i++) {
//create array into two dimensional based on the
columns
C[i]=new int[3];
for (j = 0; j < N; j++)
//add and store data into the C
C[i][j] = A[i][j] + B[i][j];
}
return C;//return the pointer
}
// main function
int main()
{
int i, j,A[3][3],B[3][3];
//create two arrays
cout<<"Matrix A: ";
//read data to A matrix
for (i = 0; i < N; i++)
for (j = 0; j < N; j++)
{
cin>>A[i][j];
}
cout<<"Matrix B :";
//read data to B matrix
for (i = 0; i < N; i++)
for (j = 0; j < N; j++)
{
cin>>B[i][j];
}
//call the addition function and store it into a
pointer
int** C=addition(A,B);
cout<<"A+B: ";
//print data
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++)
{
cout<<C[i][j]<<" ";
}
}
}
CODE IMAGE:
OUTPUT: