If variables are the "memory" and conditionals are the "brain," then loops are the "muscles" of your program. Loops allow you to repeat a block of code multiple times without rewriting it. This is essential for processing lists, repeating game cycles, or validating user input.
In C++, we have three primary types of loops.
1. The for Loop
Best used when you know exactly how many times you want to repeat something (e.g., "count to 10").
Syntax:
for (initialization; condition; increment)
2. The while Loop
Best used when you want to repeat something until a condition changes, but you don't know exactly when that will happen (e.g., "keep asking for a password until it's correct").
Syntax:
while (condition) { // code }
3. The do-while Loop
Similar to the while loop, but it guarantees the code runs at least once before checking the condition.
Code Example: Counting and Validation
This program uses a for loop to print a multiplication table and a while loop to force a user to enter a positive number.
#include <iostream>
using namespace std;
int main() {
// 1. FOR LOOP: Multiplication Table for 5
cout << "--- Table of 5 ---" << endl;
for (int i = 1; i <= 5; i++) {
cout << "5 x " << i << " = " << (5 * i) << endl;
}
// 2. WHILE LOOP: Input Validation
int secretPin = 1234;
int enteredPin;
cout << "\n--- Security Check ---" << endl;
cout << "Enter your PIN: ";
cin >> enteredPin;
while (enteredPin != secretPin) {
cout << "Wrong PIN! Try again: ";
cin >> enteredPin;
}
cout << "Access Granted!" << endl;
// 3. DO-WHILE LOOP: Run at least once
int choice;
do {
cout << "\nPress 0 to exit: ";
cin >> choice;
} while (choice != 0);
return 0;
}Key Keywords: break and continue
break: Immediately exits the loop entirely.continue: Skips the rest of the current loop iteration and jumps straight to the next lap.