I have coded this program to get two matrices and in a different function, it calculates the addition of the two matrices, but when I want to get the two arrays as input arguments in my "sum" function it generates errors and it doesn't work.
My efforts include reviewing this question at Stackoverflow : Passing a 2D array to a C++ function It helps if only I set A and B arrays with numerical dimensions like : A[2][2] not A[ar][ac]. I want the function to work for n*n matrices not up to a limited number.
#include <iostream>
#include <iomanip>
using namespace std;
template <size_t row, size_t column, size_t row2, size_t column2 >
void sum(int(&array)[row][column], int(&array2)[row2][column2]);
int main()
{
int ar, ac, br, bc;
cout << "Welcome to my matrix calculator. \nPlease enter the values of you matrices.";
cout << "\n\n\tFor your FIRST matrix;";
cout << "\n\tNumber of \'ROWS\' : ";
cin >> ar;
cout << "\tNumber of \'COLUMNS\' : ";
cin >> ac;
int A[ar][ac];
cout << "\n\tPlease enter the values of your matrix." << endl << endl;
for (int i=0; i<ar; i++)
{
for (int j=0; j<ac; j++)
{
int m = i;
m++;
int n = j;
n++;
cout << "\tNumber[" << m << "][" << n << "] : ";
cin >> A[i][j];
}
cout << endl;
}
cout << "\n\tFor your SECOND matrix;";
cout << "\n\tNumber of \'ROWS\' : ";
cin >> br;
cout << "\tNumber of \'COLUMNS\' : ";
cin >> bc;
int B[br][bc];
cout << "\n\tPlease enter the values of your matrix." << endl << endl;
for (int i=0; i<br; i++)
{
for (int j=0; j<bc; j++)
{
int m = i;
m++;
int n = j;
n++;
cout << "\tNumber[" << m << "][" << n << "] : ";
cin >> B[i][j];
}
cout << endl;
}
cout << "\nYour FIRST matrix is : " << endl;
for (int i=0; i<ar; i++)
{
cout << endl << "\t" << "|";
for (int j=0; j<ac; j++)
{
cout << setw(4) << A[i][j];
}
cout << " |";
}
cout << "\n\nYour SECOND matrix is : " << endl;
for (int i=0; i<br; i++)
{
cout << endl << "\t" << "|";
for (int j=0; j<bc; j++)
{
cout << setw(4) << B[i][j];
}
cout << " |";
}
sum(A, B);
}
template <size_t row, size_t column, size_t row2, size_t column2 >
void sum(int(&array)[row][column], int(&array2)[row2][column2])
{
if(row==row2 && column==column2)
{
cout << "\n\n\tThe addition of your matrices is = ";
int add[row][column];
for(int i=0; i<row; i++)
{
for(int j; j<column; j++)
{
add[i][j] = array[i][j] + array2[i][j];
}
}
for(int i=0; i<row; i++)
{
cout << endl << "\t" << "|";
for(int j=0; j<column; j++)
{
cout << setw(4) << add[i][j];
}
cout << " |";
}
}
else
{
cout<< "Matrixes with different rows and columns can \'not\' be added together.";
}
}
I did try whatever was on the internet but none of work for n*n matrices, could you please help? Thanks in advance!