Help with for loops

for
loop
looping
loops

#1

Can someone explain what these for loops are saying and mean?

for(i = 1; i < 5; i++)

for(i = 3; i >= 0; i–)

for(i = 2; i >=0 ; i–)

for(i = 0; i < 2 ; i++)

for(i = 2; i < 6 ; i += i + 1)


#2

Hey bro,

Can i explain it to you after some time currently i am busy.

Bye


#3

How for loop works?

for(initialization statement; test expression; update statement) {
       code/s to be executed; 
}

The initialization statement is executed only once at the beginning of the for loop. Then the test expression is checked by the program. If the test expression is false, for loop is terminated. But if test expression is true then the code/s inside body of for loop is executed and then update expression is updated. This process repeats until test expression is false.

Loop1 : for(i = 1; i < 5; i++)

This loop will run for values i = 1,2,3,4. Loop will quit when i=5 since the condition 5<5 will be false.

You can try doing a dry run:

  1. At first i = 1
  2. Evaluate condition 1<5 which is true
  3. Run the code inside for loop
  4. increment i, so that i=2
  5. Go to step 2 and continue

Loop2: for(i = 3; i >= 0; i–)

This loop starts with i=3 and the code inside for loop will run as long as i>=0. In this case, i is decremented (i–).

Loop3: for(i = 2; i >=0 ; i–)

This loop starts with i=2 and the code inside for loop will run as long as i>=0. In this case, i is decremented (i–).

Loop4: for(i = 0; i < 2 ; i++)

This loop starts with i=0 and will run for values i=0,1 and then quit when 2<2 condition evaluates to false.

Loop5: for(i = 2; i < 6 ; i += i + 1)

Steps:

  1. At first i=2
  2. Evaluate condition 2<6 which is true
  3. Run code inside for loop
  4. Set value of i += i+1 i.e 2 += 2+1 i.e i = 5
  5. Evaluate condition 5<6 which is true
  6. Run code inside for loop
  7. Set value of i += i+1 i.e 5 += 5+1 i.e i = 11
  8. Evaluate condition 11<6 which is false
  9. Quit loop