Nested for loops

#include<iostream>
#include<iomanip>
using namespace std;

int main() {
for (int i = 100; i <= 200; i++) {
for (int j = 0; j <= 4; j++) {
cout << setw(4) << i++;
}
cout << endl;
}
return 0;
}

Why when I compile and run, it skips a number each row?
Ex. 104-106 in the first to second row, then 110-112 in the second to third row, etc. What am I doing wrong?
i++ increments i by 1. So in the j loop i starts at 100 and ends at 105, even if the last value you print is 104. Just to be more clear:
j=0 print i=100, then increase i to 101
j=1 print i=101, then increase i to 102
j=2 print i=102, then increase i to 103
j=3 print i=103, then increase i to 104
j=4 print i=104, then increase i to 105
After that you return to the i loop, and increase i to 106, which you print for j=0
i++ = i += 1
Also remember to do code tags. [ code ] [/ code ] (no space padding)
Ohhh I see. Ok so I'm not sure if I'm going about it the right way now and would love clarity if I am going off track or if there is a simpler way of doing it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<iostream>
#include<iomanip>
using namespace std;

int main() {
   for (int i = 100; i <= 200; i++) {
      for (int j = 0; j <= 4; j++) {
         cout << setw(4) << i++;
      }
      cout << endl;
      i--;
   }
   return 0;
}


But now I noticed that when it runs, it runs all the way up to 104 instead of stopping at 200. My guess is that the j loop is fulfilling its purpose once i is decremented to 199 or something. What should I do? I feel like I'm causing a ripple effect of issues with everything now.

Oh and thanks poteto for the tip :)
Last edited on
just change 200 to be 195.
Last edited on
I tried that before but it only goes to 199. It should stop at exactly 200.
I GOT IT! ^_^

1
2
3
4
5
6
7
8
9
10
11
int main() {
   int i;
   for (i = 100; i < 200; i+=5) { 
      for (int j = 0; j < 5; j++) { 
         cout << setw(4) << i+j << " ";
      }
      cout << endl;
   } 
   cout << setw(4) << i << endl;
   return 0;
}
Topic archived. No new replies allowed.