C++ Loops
Repeating code execution efficiently in C++
🔄 What are C++ Loops?
C++ loops allow you to repeat code blocks multiple times efficiently. They help automate repetitive tasks and process collections of data without writing duplicate code.
#include <iostream>
using namespace std;
int main() {
// Print numbers 1 to 5
for (int i = 1; i <= 5; i++) {
cout << "Number: " << i << endl;
}
return 0;
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Key Loop Concepts
For Loop
A for loop repeats a block of code a specific number of times, making it ideal for iterating
over sequences. It consists of an initialization, a condition, and an increment/decrement expression.
In the multiplication example, the loop runs from 1 to 10, calculating and displaying each product with 3. This
structured iteration is efficient for tasks where the exact number of repetitions is known beforehand, such as
processing arrays or generating tables.
for (int i = 0; i < 5; i++) {
// code here
}
While Loop
A while loop executes repeatedly as long as a specified condition remains true, perfect for
uncertain iteration counts. It checks the condition before each iteration. In the provided example,
numbers are added sequentially until the cumulative sum exceeds 50, demonstrating its use in scenarios like reading
data until a sentinel value or achieving a target threshold where the total iterations aren't predetermined.
while (condition) {
// code here
}
Do-While Loop
The do-while loop guarantees at least one execution by evaluating the condition after the loop
body. This is crucial for menu-driven programs or input validation where an action must occur before
checking for exit criteria. The sample menu prompts the user for a choice (1-3) and continues to display options
until the user selects "Exit," ensuring the interface is presented initially regardless of the condition state.
do {
// code here
} while (condition);
Loop Control
Break and continue statements
break; // exit loop
continue; // skip iteration
🔹 For Loop
A for loop repeats a block of code a specific number of times, making it ideal for iterating
over sequences. It consists of an initialization, a condition, and an increment/decrement expression.
In the multiplication example, the loop runs from 1 to 10, calculating and displaying each product with 3. This
structured iteration is efficient for tasks where the exact number of repetitions is known beforehand, such as
processing arrays or generating tables.
#include <iostream>
using namespace std;
int main() {
// Print multiplication table of 3
cout << "Multiplication table of 3:" << endl;
for (int i = 1; i <= 10; i++) {
cout << "3 x " << i << " = " << (3 * i) << endl;
}
return 0;
}
Output:
Multiplication table of 3:
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
... (continues to 30)
🔹 While Loop
A while loop executes repeatedly as long as a specified condition remains true, perfect for
uncertain iteration counts. It checks the condition before each iteration. In the provided example,
numbers are added sequentially until the cumulative sum exceeds 50, demonstrating its use in scenarios like reading
data until a sentinel value or achieving a target threshold where the total iterations aren't predetermined.
#include <iostream>
using namespace std;
int main() {
int number = 1;
int sum = 0;
cout << "Adding numbers until sum exceeds 50:" << endl;
while (sum <= 50) {
sum += number;
cout << "Added " << number << ", sum = " << sum << endl;
number++;
}
cout << "Final sum: " << sum << endl;
return 0;
}
Output:
Adding numbers until sum exceeds 50:
Added 1, sum = 1
Added 2, sum = 3
Added 3, sum = 6
... (continues until sum > 50)
Final sum: 55
🔹 Do-While Loop
The do-while loop guarantees at least one execution by evaluating the condition after the loop
body. This is crucial for menu-driven programs or input validation where an action must occur before
checking for exit criteria. The sample menu prompts the user for a choice (1-3) and continues to display options
until the user selects "Exit," ensuring the interface is presented initially regardless of the condition state.
#include <iostream>
using namespace std;
int main() {
int choice;
do {
cout << "\n--- Simple Menu ---" << endl;
cout << "1. Say Hello" << endl;
cout << "2. Say Goodbye" << endl;
cout << "3. Exit" << endl;
cout << "Enter choice (1-3): ";
cin >> choice;
switch (choice) {
case 1:
cout << "Hello there!" << endl;
break;
case 2:
cout << "Goodbye!" << endl;
break;
case 3:
cout << "Exiting..." << endl;
break;
default:
cout << "Invalid choice!" << endl;
}
} while (choice != 3);
return 0;
}
Output:
--- Simple Menu ---
1. Say Hello
2. Say Goodbye
3. Exit
Enter choice (1-3): (user input)
🔹 Loop Control Statements
The break and continue statements provide precise control over loop execution
flow. break terminates the loop entirely, while skip (often implemented as
continue) skips the current iteration. In the example, the loop prints numbers 1-10 but skips 5 using
continue and stops entirely at 8 using break, showcasing how to conditionally bypass steps
or exit early based on specific logic.
#include <iostream>
using namespace std;
int main() {
cout << "Numbers 1-10, skipping 5, stopping at 8:" << endl;
for (int i = 1; i <= 10; i++) {
if (i == 5) {
cout << "Skipping " << i << endl;
continue; // Skip rest of this iteration
}
if (i == 8) {
cout << "Breaking at " << i << endl;
break; // Exit the loop completely
}
cout << "Number: " << i << endl;
}
cout << "Loop finished!" << endl;
return 0;
}
Output:
Numbers 1-10, skipping 5, stopping at 8:
Number: 1
Number: 2
Number: 3
Number: 4
Skipping 5
Number: 6
Number: 7
Breaking at 8
Loop finished!