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.

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

commented: Elegant way of getting the org. poster to think! +2

I think I get it now, actually. I was getting confused because I forgot to run through the entire 2nd for loop before incrementing b.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.