2D arrays question ??

Started by
10 comments, last by Zahlman 14 years, 12 months ago
Your for loop breaks down like so:
int j=0;beginning:if !(j < 4) goto end;{  // for loop body}j++goto beginning;end:

So the first time through the loop j is 0, which is less than 4, so it goes through the body and gets incremented to 1. 1 is less than 4, so it goes through the body and gets incremented to 2. 2 is less than 4, so it goes through the body and gets incremented to 3. 3 is less than 4, so it goes through the body and gets incremented to 4. 4 is not less than 4, so it skips the body and goes to the end.
Advertisement
That's why we normally write the loop with strict inequality (< rather than <=): because then the limit is the same number as the size of the array. Using a number directly is easier to remember than having to subtract one from it.

Arrays are zero-based in C++. This is a good thing. Learn to work with it. In the long run, it makes your life easier. (There are languages out there that use 1-based arrays by default, but they're definitely in the minority.)

This topic is closed to new replies.

Advertisement