Hi everyone. I'm having issues with this program. This program counts a sum of elements which are above the reverse diagonal and which are greater than 0.
For example:
-2 1 2
3 4 5
6 7 8
The answer should be like this:
The sum of the 1st column: 3
The sum of the 2nd column: 1
However some compilers give a right answer and some of them prints insanely large numbers. Where is the problem? Is it connected with a formats of variables or what?
#include <iostream>
#include <iomanip>
usingnamespace std;
int function(int n, ???);
int main()
{
int n, A[10][10];
int B[10];
cout << "Input the size of 2d array:" << endl;
cin >> n;
if(n<0)
{
cout << "\nYou can't create a 2d array with this number" << endl;
return 1;
}
cout << "Input the elements of a 2d array by lines" << endl;
for (int i = 0; i<n; i++) //
{
for (int j = 0; j<n; j++)
{
cin >> A[i][j]; // Input of the elements to the array
}
}
cout << "\nYour 2d array" << endl;
for (int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
cout << setw(5) << A[i][j]; // Control print
}
cout << endl;
}
function(int n, ????);
for(int j = 0; j <n-1; j++)
{
if(B[j] == 0)
cout << j+1 << "there are no elements which are greater than 0 in this column" << endl;
else
cout << j+1 << " the sum of the column is: " << B[j] << endl;
}
return 0;
}
int function(int n, ???)
{
for (int i = 0; i<n; i++)
{
for (int j = 0; j<n; j++)
{
if(i + j < n - 1)
{
if(A[i][j] > 0)
{
B[j] = B[j] + A[i][j];
}
}
}
}
return ???
}
If I want to give back the answer as a value with function, how should I declare variables inside?
Since the result is an array of several values, rather than a single number, the function will return the results via the array B[]. Thus it doesn't need to be declared as int function(... .
The function header could look line this:
void function(int n, int A[10][10], int B[10])
and you would call it like this:
function(n, A, B);
I'd suggest if you do that, it seems reasonable that the function might be called more than once, thus it should reset the contents of array B[] to all zeros each time.