0

can anybody clear my doubt .. why this program is giving 10 as output. can you please explain the mechanism .. for loop is also having ; before the statements also

#include <iostream>
using namespace std;

int main() {
    int i ;
    for ( i =0 ; i<10 ; i++);
    {
      cout<<i ;
    }

    return 0;
}
Arunmu
  • 6,837
  • 1
  • 24
  • 46

2 Answers2

6
for ( i =0 ; i<10 ; i++);

This is a complete loop, the semicolon at the end indicates an empty body. Hence it simply increments i eventually to 10. The reason it's 10 (rather than 9) is because that is when the continuation condition i < 10 becomes false.

Which means that this little snippet:

{
    cout<<i ;
}

is a once-executed statement outputting the contents of i (left at 10 by the loop).

The braces in this case simply put the statement into an enclosed scope, they are not related to the loop at all.

So, if you want to output i each time through the loop, simply get rid of the semicolon so that the braces and their contents become the body of that loop.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
3
for ( i =0 ; i<10 ; i++); // This means loop till i = 10 at which point loop breaks. This is because of ending the for loop with ';'
{ // start of scope
    cout<<i ; // Print the value of i which is 10 now
} // end of scope

Consider that the loop has reached a point where i = 9, so, 'i < 10' condition is true.
Therefore, for the next iteration 'i++' will increment it to 10.
Now again the test 'i < 10' is checked. At this point '10 < 10' test returns false and the for loop breaks and the value of i is 10.

Arunmu
  • 6,837
  • 1
  • 24
  • 46
  • but i max is 9 here..how it is printing 10 – bhabajit kashyap May 30 '16 at 13:57
  • @bhabajitkashyap You need to understand how for loop works :). Consider i = 9, so, i < 10 condition is true. Therefore, for the next iteration 'i++' will increment it to 10. Now again the test 'i < 10' is checked. At this point '10 < 10' test returns false and the for loop breaks and the value of i is 10. – Arunmu May 30 '16 at 13:59
  • got the point ..thanks :-) – bhabajit kashyap May 30 '16 at 14:08