For Loop problems

What did I do wrong on the coding to "not" get the output of 01234?
why am I getting just 5?

1
2
3
4
5
6
7
8
9
  #include <iostream>
    using namespace std;
    int main()
    {
            int i = 0;
            for(; i < 5; i++);
            cout << i;
            return 0;
    }
1
2
3
4
5
6
7
8
9
 #include <iostream>
    using namespace std;
    int main()
    {
           
            for(int i = 0; i < 5; i++) // You have put a ; here which mean you have finish what in your for
            cout << i;
            return 0;
    }

Last edited on
one more question: assuming I still have the ;
why is the value for i equal to 5, instead of four?
although the for loop ended, the for loop says that i < 5.
the for add 1 to i each time it execute which mean it get to 5 and then compare if 5<5


0<5 // enter the loop
1<5 // enter the loop
2<5 // enter the loop
3<5 // enter the loop
4<5 // enter the loop
5<5 // do not enter the loop

for(;i<5;i++)
{
cout << i; // 0-1-2-3-4
}

// here i = 5

Sorry i usually speak french
Last edited on
The for loop ends when the condition becomes false.
In this case, the first value of i which makes the condition i<5 false is i=5, so that's the value i ends up becoming afterwards.

In other words, for loops can't "anticipate" when they're going to end.
Topic archived. No new replies allowed.