While Loop in C

The while loop in C is used to execute a block of code repeatedly as long as a specified condition is true. It is commonly used when the number of iterations is not known in advance.

Syntax

while (condition) { // Code to be executed repeatedly }

Example

int i = 1; while (i <= 5) { printf("%d\n", i); i++; } // Output: 1 2 3 4 5

How It Works

  • The condition is checked before each iteration.
  • If the condition is true, the loop executes the code inside its body.
  • After each iteration, the condition is evaluated again.
  • The loop continues until the condition becomes false.

Tips

  • Use while loops when the number of iterations is unknown.
  • Ensure the condition will eventually become false to avoid infinite loops.
  • Update variables affecting the condition inside the loop.
  • Keep loop body simple for readability and maintainability.

Common Mistakes

  • Not updating the variable used in the condition, causing an infinite loop.
  • Using incorrect conditions that never become false.
  • Placing semicolons immediately after while (condition); which creates an empty loop.
  • Overcomplicating the loop body, making logic hard to follow.