Real-Life Loop Examples
Menu System
Loops are often used to build interactive menus that repeat until the user selects an exit option:
Example
#include <iostream>
using namespace std;
int main() {
int choice;
do {
cout << "\nMenu:\n";
cout << "1. Option 1\n";
cout << "2. Option 2\n";
cout << "3. Exit\n";
cout << "Enter choice: ";
cin >> choice;
switch (choice) {
case 1: cout << "Option 1 selected\n"; break;
case 2: cout << "Option 2 selected\n"; break;
case 3: cout << "Exiting...\n"; break;
default: cout << "Invalid choice\n";
}
} while (choice != 3);
return 0;
}
Output
Menu: 1. Option 1 2. Option 2 3. Exit Enter choice: 1 Option 1 selected Menu: 1. Option 1 2. Option 2 3. Exit Enter choice: 3 Exiting...
Data Processing
Loops are widely used for processing collections of data, such as computing averages or filtering values:
Example
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<double> temperatures = {72.5, 68.3, 71.6, 75.2, 69.8};
// Calculate average temperature
double sum = 0;
for (double temp : temperatures) {
sum += temp;
}
double average = sum / temperatures.size();
// Find days above average
cout << "Days above average (" << average << "):\n";
for (size_t i = 0; i < temperatures.size(); i++) {
if (temperatures[i] > average) {
cout << "Day " << i + 1 << ": " << temperatures[i] << endl;
}
}
return 0;
}
Output
Days above average (71.48): Day 1: 72.5 Day 3: 71.6 Day 4: 75.2
Game Loop
Most games use a continuous loop to handle input, update game state, and render output:
Example
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
int main() {
bool gameRunning = true;
int score = 0;
while (gameRunning) {
// Process input
char input;
cout << "Enter command (q to quit, s to score): ";
cin >> input;
// Update state
if (input == 'q') {
gameRunning = false;
} else if (input == 's') {
score++;
cout << "Score: " << score << endl;
}
// Simulate frame delay
this_thread::sleep_for(chrono::milliseconds(100));
}
cout << "Game over! Final score: " << score << endl;
return 0;
}
Output
Enter command (q to quit, s to score): s Score: 1 Enter command (q to quit, s to score): s Score: 2 Enter command (q to quit, s to score): q Game over! Final score: 2
File Processing
Loops are essential when reading files of unknown length, such as processing lines in a text file:
Example
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream file("data.txt");
string line;
int lineCount = 0;
if (file.is_open()) {
while (getline(file, line)) {
lineCount++;
cout << "Line " << lineCount << ": " << line << endl;
}
file.close();
} else {
cout << "Unable to open file";
}
cout << "Total lines: " << lineCount << endl;
return 0;
}