# Complex for-statements

• 06-03-2008
Wicket
Complex for-statements
I have got this four for-statements in a program of mine:

Code:

```for (int i = a + 1, j = b + 1; i < 8 || j < 8; i++, j++) {         field[i][j] = -1;         filled++;         cout << i << ' ' << j << endl;                // Just to see what happens } for (int i = a + 1, j = b - 1; i < 8 || j >= 0; i++, j++) {         field[i][j] = -1;         filled++; } for (int i = a - 1, j = b + 1; i >= 0 || j < 8; i++, j++) {         field[i][j] = -1;         filled++; } for (int i = a - 1, j = b - 1; i >= 0 || j >= 0; i++, j++) {         field[i][j] = -1;         filled++; }```
I have got the random numbers between 0 and 8 and field has the size [8][8].

I wanted to set from the random numbers a and b the diagonals to -1. I handle the two diagonals in two ways: first diagonal down and then up.

The problem is that after compiling and running the program crashes. After putting a cout statement in the first for-loop I saw what went wrong. This is the output:
Code:

```2 5 3 6 4 7 5 8 6 9 7 10```
I wasn't expecting that i or j would be greater then eight. Can someone tell me what I am doing wrong.

I am using BCC5.5.
• 06-03-2008
tabstop
|| means or, not and. And is &&.
• 06-03-2008
Wicket
I now || means or. Else I will have the problem that the statement will be false if I get i = 6 and j = 10. It must stop before it gets there. So it needs an or.
• 06-03-2008
tabstop
Stop and think for a minute. Consider the i=6, j=9 case you had above. Is (i < 8 || j < 8) true? Of course it is -- since i = 6, i < 8. Do you want it to be true? Of course you don't, because your for-loop doesn't stop. Fortunately for you, (i < 8 && j < 8) will be false in this case, since j<8 will be false.
• 06-03-2008
Wicket
A yes. You're right. I always want to swap that to around. In a more normal for-statement I always see it directly that that's wrong. In this case I looked after the crash to that statement and thougt it was right.
• 06-03-2008
CornedBee
Also, it looks like you ought to be decrementing in some of those loops.
• 06-04-2008
dwks
You might want to consider using a function of sorts for this. The loops are all quite similar. You'd just have to pass in parameters describing whether you wanted i and j to increment or decrement. Then you'd probably return the filled value after the loop had finished.