For loop

# include <iostream>
# include <cmath>

int main ()
{
using namespace std;
for (int i = 1; i <= 10; i++)
{
cout << i << " ";
i++;
}
system("pause");
return 0;
}

Why does the following code produce an output of 1 3 5 7 9 rather than 2 4 6 8 10? I am having trouble figuring out the logic of this code. For instance, my understanding of this code is the loop will run for when i = 1-10, and the i++ after the output will increase the number by 1? So instead of starting at 1 it will jump to 2, and instead of 3 it will jump to 4 etc etc.
1
2
3
4
5
for (int i = 1; i <= 10; i++)   // i = 1
{
     cout << i << " ";            //print i, which is still 1
     i++;                              //increment i; i = 2
 }                                       //Move on to next loop; i = 3; etc. 


The third portion inside the parentheses, or "i++," only occurs after the current iteration completes.
Banshee1 wrote:
my understanding of this code is the loop will run for when i = 1-10, and the i++ after the output will increase the number by 1? So instead of starting at 1 it will jump to 2, and instead of 3 it will jump to 4 etc.

Simply because you are incrementing i twice in your for...loop. Automatically, after the end of a loop, the looping variable is increased by the increment value, that is, i++ which means increment i by 1 after the end of the instructions inside the for...loop body. But in your case, you're also manually incrementing i, so it means yourself and the automatic-"incrementer"(I don't even know if that word exists) is manipulating the looping variable i.

Banshee1 wrote:
Why does the following code produce an output of 1 3 5 7 9 rather than 2 4 6 8 10? I am having trouble figuring out the logic of this code


You're displaying the value of i before any increment, if you want it to display 2 4 6 8 10, then increment it before display it i.e.
1
2
3
4
5
for (int i = 1; i <= 10; i++)
{
i++;
cout << i << " ";
} 


If you want it to output 2 4 6 8 10 then you start i from 2 i.e. i=2,
give i the terminal value(i.e. where you want it to stop counting) which is 10,
give it the increment value, which is the value you want it to increase by i.e. 2
so you have
1
2
for(int i=2; i<=10; i+=2)
cout<<i<<" ";
Last edited on
1
2
for (unsigned i = 1; i <= 10; i += 2)
 cout << i << " ";
Topic archived. No new replies allowed.