Loops
Loops allow you to execute a block of code repeatedly, which is essential for tasks like processing data, iterating through collections, and implementing algorithms. Understanding loops is crucial for writing efficient and concise programs.
For Loop
The for loop is ideal when you know exactly how many times you want to repeat something:
// Basic for loop syntax
for (initialization; condition; increment) {
// code to repeat
}
// Example: Print numbers 1 to 10
for (int i = 1; i <= 10; i++) {
cout << i << " ";
}
cout << endl;
// Example: Calculate factorial
int n = 5;
int factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
}
cout << "Factorial of " << n << " is " << factorial << endl;
// Example: Sum of numbers
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
cout << "Sum of 1 to 100 is " << sum << endl;
For Loop Components:
- Initialization: Executed once at the beginning
- Condition: Checked before each iteration
- Increment: Executed after each iteration
- Any component can be empty, but semicolons are required
While Loop
The while loop continues as long as a condition is true. It's useful when you don't know the exact number of iterations:
// Basic while loop
int count = 0;
while (count < 5) {
cout << "Count: " << count << endl;
count++;
}
// Example: Input validation
int number;
cout << "Enter a positive number: ";
cin >> number;
while (number <= 0) {
cout << "Please enter a positive number: ";
cin >> number;
}
// Example: Finding digits in a number
int num = 12345;
int digitCount = 0;
while (num > 0) {
num /= 10;
digitCount++;
}
cout << "Number of digits: " << digitCount << endl;
Do-While Loop
The do-while loop executes the code block at least once, then continues while the condition is true:
// Menu example
int choice;
do {
cout << "\n=== Menu ===" << endl;
cout << "1. Option 1" << endl;
cout << "2. Option 2" << endl;
cout << "3. Exit" << endl;
cout << "Enter choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "You selected Option 1" << endl;
break;
case 2:
cout << "You selected Option 2" << endl;
break;
case 3:
cout << "Goodbye!" << endl;
break;
default:
cout << "Invalid choice!" << endl;
}
} while (choice != 3);
// Example: Reverse a number
int original = 12345;
int reversed = 0;
do {
reversed = reversed * 10 + original % 10;
original /= 10;
} while (original > 0);
cout << "Reversed number: " << reversed << endl;
When to Use Each Loop:
- For loop: When you know the number of iterations
- While loop: When the number of iterations depends on a condition
- Do-while loop: When you need to execute the code at least once
Nested Loops
You can place loops inside other loops to handle multi-dimensional data or complex patterns:
// Print a multiplication table
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
cout << i * j << "\t";
}
cout << endl;
}
// Print a pattern
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
cout << "*";
}
cout << endl;
}
// Output:
// *
// **
// ***
// ****
// *****
// Find all prime numbers up to n
int n = 30;
for (int i = 2; i <= n; i++) {
bool isPrime = true;
for (int j = 2; j * j <= i; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
cout << i << " ";
}
}
Nested Loop Performance:
Nested loops can significantly impact performance. A loop inside another loop creates O(n²) time complexity. Be mindful of this when working with large datasets.
Loop Control Statements
Special statements that change the normal flow of loop execution:
Break Statement
Exits the loop immediately
// Find first even number
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
cout << "First even: " << i << endl;
break;
}
}
// Search in array
int arr[] = {5, 2, 8, 1, 9};
int target = 8;
bool found = false;
for (int i = 0; i < 5; i++) {
if (arr[i] == target) {
cout << "Found at index " << i << endl;
found = true;
break;
}
}
Continue Statement
Skips the rest of the current iteration
// Print only odd numbers
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
cout << i << " ";
}
// Output: 1 3 5 7 9
// Skip negative numbers
int numbers[] = {-2, 5, -1, 8, 3, -4};
for (int i = 0; i < 6; i++) {
if (numbers[i] < 0) {
continue;
}
cout << numbers[i] << " ";
}
// Output: 5 8 3
Range-Based For Loop (C++11)
A modern C++ feature that simplifies iterating through containers:
#include
#include
// Traditional array
int arr[] = {1, 2, 3, 4, 5};
cout << "Array elements: ";
for (int x : arr) {
cout << x << " ";
}
cout << endl;
// Vector
vector vec = {10, 20, 30, 40, 50};
cout << "Vector elements: ";
for (int x : vec) {
cout << x << " ";
}
cout << endl;
// String
string text = "Hello";
cout << "Characters: ";
for (char c : text) {
cout << c << " ";
}
cout << endl;
// Modifying elements (use reference)
for (int& x : vec) {
x *= 2; // Double each element
}
Common Loop Patterns
Accumulation
// Sum elements
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
// Find maximum
int max_val = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max_val) {
max_val = arr[i];
}
}
Counting
// Count positive numbers
int count = 0;
for (int i = 0; i < n; i++) {
if (arr[i] > 0) {
count++;
}
}
// Count occurrences
int target = 5;
int occurrences = 0;
for (int x : arr) {
if (x == target) {
occurrences++;
}
}