Loops in C++ allow repeated execution of code as long as a condition remains true. This makes programs efficient, readable, and free from repetitive manual coding.
Why Use Loops?
Instead of writing similar lines of code multiple times, loops automate repetition. They reduce errors and enhance clarity when performing repetitive tasks, such as counting values or cycling through lists.
The While Loop
The while
loop keeps running as long as the specified condition remains true. It continuously checks the condition before executing the loop body.
Syntax
while (condition) { // Code runs while condition remains true }
Example: Displaying Gear Numbers
#include <iostream> using namespace std; int main() { int gear = 1; while (gear <= 5) { // Loop runs while gear is 5 or less cout << "Current gear: " << gear << "\n"; gear++; // Increases gear level each loop cycle } return 0; }
How the Example Works
- The variable
gear
starts at 1. - The loop executes while
gear
is less than or equal to 5. gear++
increases the value with each iteration.- Once
gear
reaches 6, the condition is false, and the loop stops.