- 1
If i=1; i<=5++i
Please show a detailed explanation of this program I am new to c++ how is the value be coming 2 and so on
5 Answers
+ 2
You can increment different values. Letâs modify your code a bit and have it stop at 10, start at 2.
for (int i = 2; i<=10; i += 2){
cout << i << endl;
Now the third part of the loop is:
i += 2
This increments the loop by 2.
Output should now be
2
4
6
8
10
To answer your last sentence, lets change it back to the original one from my previous post, but letâs start at 2
for (int i = 2; i<=5; i++){
cout << i << endl;
The output will now be:
2
3
4
5
+ 1
This is how a for loop syntax usually looks like. Let me use your numbers.
for (int i= 1; i <= 5; i++)
cout << i << endl;
So let us break down the paranthesis
- int i = 1
This part of the for loop is where the for loop begins, so the loop starts at 1
- i <= 5
This part of the loop is where it stops, so the greatest number of the loop is 5
- i++
This part of the loop is how much the loop increments by, so from 1 it will increment by 1 which gets you 2,3,4 and stops at 5 because of the i<= 5
So your output should be
1
2
3
4
5
0
Is it a general rule the number assigned to the variable should always be incremented by 1 or can it be more than 1? For ex if i=2 then i++ should be 2+1 or 2+2?
0
please expain
0
for (int i = 2; i<=10; i += 2){
i += 2
Output should now be
2
4
6
8
10
The output will now be:
2
3
4
5