C++ while loop


The while loop in C++ is a control flow statement that allows a block of code to be executed repeatedly as long as a specified condition remains true. It is often used when the number of iterations is not known beforehand, and you want the loop to continue running until a particular condition is met.

Syntax of while Loop

while (condition) { // Code to be executed }
  • condition: The loop will keep executing the code block as long as this condition is true.
  • The condition is checked before each iteration, which means that if the condition is initially false, the loop body will not execute at all.

Example: Basic while Loop

Let's look at a simple example that uses a while loop to print numbers from 1 to 5:

#include <iostream> int main() { int count = 1; // Initialization while (count <= 5) { // Condition std::cout << "Count is: " << count << std::endl; count++; // Update } return 0; }

Output:

Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5

Explanation

  1. Initialization (int count = 1): A variable is declared and initialized to control the number of loop iterations.
  2. Condition (count <= 5): Before each iteration, the while loop checks this condition. If the condition is true, the loop executes; if it is false, the loop terminates.
  3. Update (count++): After each iteration, the value of count is incremented to eventually make the condition false.

Infinite while Loop

If the condition never becomes false, the while loop will run indefinitely, creating an infinite loop. This can be intentional in cases like waiting for user input or server listening, but it's generally advisable to include a way to exit the loop.

Example:

while (true) { std::cout << "This loop will run forever unless you break it!" << std::endl; }

To exit an infinite loop, you can use a control statement like break.

Example:

int count = 0; while (true) { std::cout << "Count is: " << count << std::endl; count++; if (count == 3) { break; // Exit the loop when count reaches 3 } } // Output: // Count is: 0 // Count is: 1 // Count is: 2

Use Case: User Input Example

while loops are often used for user input validation until the correct input is provided.

Example:

#include <iostream> int main() { int number; std::cout << "Enter a number between 1 and 10: "; std::cin >> number; while (number < 1 || number > 10) { std::cout << "Invalid number. Try again: "; std::cin >> number; } std::cout << "You entered: " << number << std::endl; return 0; }
  • In this example, the while loop ensures that the user enters a valid number between 1 and 10.
  • If the input is invalid, the user is repeatedly prompted to enter the correct value until the condition (number < 1 || number > 10) becomes false.

Key Points

  1. Condition Check Before Execution: The while loop checks the condition before executing the loop body, so if the condition is false initially, the loop body won't run even once.
  2. No Fixed Iteration Count: Unlike a for loop, the while loop is better suited for situations where the number of iterations is not predetermined.
  3. Use Cases: Common use cases include:
    • Repeatedly prompting for user input until a valid value is entered.
    • Running a block of code while waiting for a condition to change (e.g., waiting for data from a sensor).

Comparison with do-while Loop

A while loop checks the condition before executing the loop body. This means the loop may not execute at all if the condition is false initially. In contrast, a do-while loop will execute the loop body at least once because the condition is checked after the loop body.

Example of do-while Loop:

#include <iostream> int main() { int count = 6; do { std::cout << "Count is: " << count << std::endl; count++; } while (count <= 5); return 0; } // Output: // Count is: 6

In this example, the loop runs once because the condition is checked after the loop body.

Summary

  • A while loop repeats a block of code as long as the condition remains true.
  • It is used when you do not know beforehand how many times the loop will run.
  • If the condition is initially false, the loop will not execute at all.
  • You can use break to exit the loop early or use infinite loops for specific scenarios.

The while loop is a versatile tool for repetitive tasks that depend on certain dynamic conditions being met during runtime.