VOOZH about

URL: https://www.geeksforgeeks.org/dsa/while-loop-in-programming/

⇱ While loop in Programming - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

While loop in Programming

Last Updated : 26 Mar, 2026

A while loop is a control structure that repeatedly executes a block of code as long as a specified condition remains true.

  • The condition is checked before each iteration, and the loop stops once the condition becomes false.
  • It is useful when the number of iterations is not known beforehand.
👁 while_loop

Explanation:
The code initializes count = 0 and runs a while loop while count < 5. In each iteration, the current value of count is printed using cout, and then count is incremented by 1.

Working:
The loop starts from 0, prints the value, and increases it by 1 in every iteration. When count becomes 5, the condition count < 5 becomes false, so the loop terminates.

Use Cases of While Loop:

  • Input Validation: Repeatedly ask for input until the user provides a valid value.
  • Processing Data: Traverse arrays, lists, or collections until a condition is met.
  • Event Handling: Continuously monitor events like sensor data or network requests.
  • Implementing Algorithms: Used in algorithms such as searching, sorting, and mathematical computations.
  • State Machines: Execute logic repeatedly until a state change occurs.
  • Games and Simulations: Run the main game loop to update state, process input, and render output.
  • Batch Processing: Process multiple tasks (files, records, etc.) until all items are handled.
Comment
Article Tags:
Article Tags: