Oct 28, 2012 at 4:09am UTC
I have this code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include<iostream>
#include<iomanip>
using namespace std;
int main(){
for (int count=0; count<3; ++count){
int i=0;
while (i<10){
++i;
cout<<i;
}
cout<<endl;
}
return 0;
}
The output is:
12345678910
12345678910
12345678910
OK. I dont understand the code. I understand up to the point that it prints out 1 to 9. But why it print 10 since the condition is i<10 and also why it print 3 lines?
can someone explain this. Thanks
Last edited on Oct 28, 2012 at 4:10am UTC
Oct 28, 2012 at 4:13am UTC
It prints out 3 lines because the outer for loop goes from 0 to 2, which is 3 numbers.
Similarly, it prints out 10 number because it goes from 0 to 9, not from 1 to 9.
Oct 28, 2012 at 4:15am UTC
for loop from 0 to 2: 3 lines
while loop from 0 to 9: adds 1 inside the loop, before the output. so you get a loop from 1 to 10
Oct 28, 2012 at 4:19am UTC
ok, now i get it.
0 is to be counted as 1 so when the condition is <3, it will be
0......1.......2 ----- 3 lines (it still met the condition as its <3)
Cool thnx.