c
  1. c-for-loop

C For Loop

Syntax

for ( initialization; condition; increment ) {
   statement(s);
}

Example

#include <stdio.h>

int main() {
   int i;
   for (i = 1; i <= 5; ++i) {
      printf("%d ", i);
   }
   return 0;
}

Output

1 2 3 4 5

Explanation

A for loop is a control flow statement that allows code to be executed repeatedly. The for loop starts with an initialization statement that is executed once when the loop starts. Next, a condition is checked before each iteration, and if it is true, the statement(s) within the loop are executed. Finally, an increment or decrement statement is executed after each iteration, and the condition is checked again.

Use

The for loop is commonly used for iterating over arrays or executing a set of statements a specific number of times. It is useful when the number of iterations is known in advance.

Important Points

  • The for loop can be used to iterate over arrays and perform calculations on each element of the array.
  • The for loop can also be used to execute a set of statements a specific number of times.
  • The initialization statement is executed only once, at the beginning of the loop.
  • The condition is checked before each iteration, and if it evaluates to false, the loop exits.
  • The increment statement is executed after each iteration, before the condition is checked again.

Summary

The for loop is a powerful control flow statement in C that allows code to be executed repeatedly for a specified number of times. It is commonly used for iterating over arrays or performing a set of calculations a specific number of times. Understanding how to write a for loop with the correct syntax and important points will greatly improve your ability to write efficient and effective programs in C.

Published on: