red_wolf
red_wolf

Reputation: 87

increment and decrements in for loop

In a for loop should I use only i++ or i-- operators ? OR can I also use i+10, i+20,i-20 ? I used i+10 in the increment place in the For loop , it is not getting executed.but when I use i++ , it is getting executed.so please help me solve this ! I tried for(i=0;i<=100;i+20) is it wrong ?

Upvotes: 1

Views: 1208

Answers (5)

paxdiablo
paxdiablo

Reputation: 882356

In C and C++ at least, the statement:

i + 20

is an expression statement - the expression is evaluated (or may not be if the optimiser figures out the result does not affect the observable behaviour of the program, which is likely) but otherwise ignored. In fact, the statement:

42

is also valid but equally useless.


What you should be doing is one of:

i += 20
i = i + 20

That will work better in your loop because it actually modifies the loop control variable.

Upvotes: 3

Roman Izosimov
Roman Izosimov

Reputation: 210

When you use for(int i = 20; i <= 100; i + 20) it mean that start loop with i = 0, each iteration do i + 20 operation, and do this while i <= 100. Operation i + 20 dont have effect to i and i don't canged. You must change i in this section. Write for(int i = 20; i <= 100; i = i + 20) or for(int i = 20; i <= 100; i += 20) to change i in each loop iteration.

Upvotes: 1

Lukas Warsitz
Lukas Warsitz

Reputation: 1239

If you are using Java try this:

for(int i = 0; i<= 100; i+=20){
    System.out.println(i);
}

In Java i++ is equal to i = i + 1 .Thats why i + 20 doesnt work. so you must do something like i += 20 or i = i + 20 .

Upvotes: 1

aDoubleSo
aDoubleSo

Reputation: 1148

Maybe like this in C#!

        for (int i = 0; i < 100; i = i+10)
        {
            Console.WriteLine(i);
        }

Upvotes: 1

Scary Wombat
Scary Wombat

Reputation: 44854

If this is Java then the correct syntax is

for(i=0;i<=100;i=i+20) 

Upvotes: 1

Related Questions