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<<" ";
|