@Torex
During the addition of the columns, you check if its a 0 or more. If less than 0, end the for loops, and inform the user that the program has terminated.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
#include <iostream>
#include <iomanip>
using std::cin;
using std::cout;
using std::endl;
using std::setw;
int main()
{
int n, m, x[10][10] = { { 0 }, { 0 } }, sum = 0, i, j;
int v[10] = { 0 };
// Zero outsum, x array and v array.
// Initialized i and j so we don't need show int in the for loops.
bool ok = true;
cout << "Input the size of 2d array\n";
cin >> n;
m = n;
cout << "Input the elements of array\n";
for (i = 0; i<n; i++)
{
for (j = 0; j<m; j++)
{
cin >> x[i][j];
}
}
m--;
n--;
cout << "Your 2d array: \n";
for (i = 0; i<n; i++)
{
for (j = 0; j < m; j++)
{
if (x[i][j] >= 0)
{
v[j] += x[i][j];
cout << setw(5) << x[i][j];
sum += x[i][j];
}
else
{
cout << endl << endl << "Sorry, a negative number has been inputted. Program cannot continue." << endl;
i = n; // Ends the for loops
ok = false; // Negative number found. Set to false
}
}
cout << endl;
m--;
}
if (ok) // Print only IF ok is still true
{
cout << endl << "Sum = " << sum << endl;
for (i = 0; i < n; i++)
cout << "Column " << i << " sum = " << v[i] << endl;
}
return 0;
}
|
You asked..
And maybe you can explain how do m-- and n-- works in this program? |
Well, you're trying to figure a triangle of numbers in an array. If the user says the array is sized as 4, the inputted numbers are array[0][0], array[0][1], array[0][2] and array[0][3] for the top, which is kept track of, by variable m. N is for the array rows. 1 is subtracted from the rows count by the n--. Anyway, by subtracting 1, from m and n, the for loop counts only array[0][0] to array[0][2]. Then the second time thru the loop, because m is subtracted by 1 again, it only counts array[1][0] and array[1][1], and the last loop only counts array[2][0], because , again, 1 is subtracted from m. When finished, you have the numbers added from the triangle of numbers in the array.
Hope this clarifies everything. If not, ask the next question.