Curriculum
Course: C basic
Login

Curriculum

C basic

C Introduction

0/1

C Get Started

0/1

C Comments

0/1

C Constants

0/1

C Operators

0/1

C Break and Continue

0/1

C User Input

0/1

C Memory Address

0/1

C Structures

0/1
Text lesson

For Loop

For Loop

When you know the exact number of times you need to loop through a block of code, use a for loop instead of a while loop.

Syntax

for (expression 1; expression 2; expression 3) {
  // code block to be executed
}
  • Expression 1 is executed once before the code block starts.
  • Expression 2 sets the condition for running the code block.
  • Expression 3 is executed after each iteration of the code block.

The following example will print the numbers 0 through 4:

Example

int i;

for (i = 0; i < 5; i++) {
  printf(“%d\n”, i);
}

Example explained

  • Expression 1 initializes a variable before the loop begins (int i = 0).
  • Expression 2 sets the condition for the loop to continue (i must be less than 5). If the condition is true, the loop will repeat; if false, the loop will terminate.
  • Expression 3 increments the value (i++) after each iteration of the code block.