Search⌘ K
AI Features

The for and while loops

Explore the use of for, while, and do-while loops in C++ to perform repeated actions efficiently. Learn loop control with break and continue, along with nested loops and managing infinite loops. Understand how these constructs help automate repetitive tasks and process complex data structures in programming.

Writing code often requires performing the same action repeatedly. Imagine calculating the final grade for every student in a class or prompting a user until they enter a valid password. Copying and pasting the same lines of code is tedious, error-prone, and impossible to scale if we don't know exactly how many times we need to repeat the action.

Instead, we use loops. In C++, loops enable us to define a block of logic once and repeatedly execute it as long as a specific condition is met, giving our programs the ability to handle tasks of any size with efficiency.

The while loop: Condition-controlled repetition

The while loop is the simplest form of iteration. It repeats a block of code as long as a specified boolean condition evaluates to true. This is ideal when we do not know in advance how many times the loop needs to run; we simply know it should continue while a state is valid.

The syntax relies on a condition checked at the start of every iteration:

while (condition) {
// Code to execute
}

If the condition is false initially, the body never executes. If it is true, the body executes, and then the program jumps back to the condition to check it again.

The while loop
The while loop

Here is a simple counter using a while loop.

C++ 23
#include <iostream>
int main() {
int fuel = 3;
// Loop runs as long as fuel is positive
while (fuel > 0) {
std::cout << "Rocket running... Fuel: " << fuel << "\n";
// Decrement fuel so the condition eventually becomes false
fuel = fuel - 1;
}
std::cout << "Liftoff complete.\n";
}

Let’s understand this step by step:

  • Line 4: We initialize a variable fuel to 3.

  • Line 7: The while statement checks if fuel > 0. Since 3 is greater than 0, we enter the block.

  • Line 8: We print the current fuel status.

  • Line 11: We decrease fuel by 1. This step is critical; without it, fuel would stay 3 forever, creating an infinite loop.

  • Line 12: The loop ends. Control jumps back to Line 7. This repeats until fuel becomes 0.

  • Line 14: When fuel > 0 is false, execution skips the loop body and proceeds here.

The for loop: Counted repetition

While while loops are flexible, we often need to run code a specific number of times—usually involving a counter variable. The for loop packages the initialization, condition, and update steps into a single, concise line. This reduces the risk of forgetting to update the counter.

The for loop
The for loop

The syntax has three parts separated by semicolons:

for (initialization; condition; update) {
// Code to execute
}
  1. Initialization: Runs once before the loop starts (e.g., int i = 0).

  2. Condition: Checked before every iteration. If true, the body runs. If false ...