For Loop

Loop executes the same block of code again and again until the given condition is true.

  1. Statement-1 – assign value to a variable.
  2. Statement-2 – check the condition.
  3. Statement-3 – change the value of variable.

This will print name 5 times.

Dry Run

  1. Statement-1 shows i=0. Statement-2 checks condition, i is less than 5(true), move inside loop and print name.
  2. Statement-3 will increment i, now i=1. Statement-2 checks condition, i is less than 5(true), move inside loop and print name.
  3. Statement-3 will increment i, now i=2. Statement-2 checks condition i is less than 5(true), move inside loop and print name.
  4. Statement-3 will increment i, now i=3. Statement-2 checks condition i is less than 5(true), move inside loop and print name.
  5. Statement-3 will increment i, now i=4. Statement-2 checks condition i is less than 5(true), move inside loop and print name.
  6. Statement-3 will increment i, now i=5. Statement-2 checks condition i is less than 5(false), loop will terminate and control moves to next line.

Nested Loops

Nested loops are loops within loops. When we have a nested loops then, when outer loop runs one-time, inner loops complete its all iterations. After that control moves to the outer loop. Again, the outer loop runs a second time and inner loop completes its all iterations. This process will continue until the outer loop completes its all iterations.

Infinite for loop

If you put the double semicolon inside parenthesis, it will become infinite for loop.

Practice Exercises

Complete these exercises to reinforce your learning and earn XP

Sign in to track your progress and earn XP!
Exercise 1 of 2Easy

What will be the output?

15 XP~4 min
for(int i = 0; i < 3; i++) {
    printf("%d ", i);
}
Exercise 2 of 2Easy

To exit a loop immediately, we use the ___ statement.

10 XP~2 min