Hello, I am having trouble understanding the output of the following program:

``````#include <iostream>
using namespace std;
int main ()
{
int  a[5][6];
int  b, d;
for (b=0; b<=5; b++) {
for (d = 4; d >= 0; d--) {
if ((b+d)% 4 == 0 ) {
a[d][b] = b;
}
else {
a[d][b] = -b;
}
}
}

for (d = 0; d < 4; d++) {
cout << a[d][d] << " ";
cout << endl;
}
return 0;
}``````

I know that the output is

0
-1
2
-3

But why? If b is counting up from 0, and d is counting down from 4, then isn't (b+d) % 4 always going to be zero? Thus meaning that the else condition will never apply, and thus never make the number negative?

Thanks to anyone who can shed some light on this.

2
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by ItecKid

Rather than me explaining it, i'll give you something to look at and think about. try adding the following line into your code, just inside the second foor loop

``cout << "D: " << d << " B: " << b << " (" << d+b << ")" << endl;``

The go through the output and see how many add up to 4

Chris