🔄 Mastering C++ Iteration Constructs: Automating Repetitive Tasks
Loops are control structures used to execute a block of code repeatedly until a specific termination condition is met. They eliminate code redundancy and are essential for iterating through data structures, processing user requests, and managing simulations.
🔁 Iteration Constructs
- for loop: Ideal when the exact number of iterations is known in advance.
- while loop: Evaluates condition *before* executing the loop body (entry-controlled).
- do-while loop: Executes the body *at least once* before checking the condition (exit-controlled).
🛑 Loop Control Statements
- break: Instantly terminates the loop, jumping control outside.
- continue: Skips the current iteration and jumps directly to the next loop cycle.
📊 End-to-End Loop Execution & Control Flow Workflow Diagram
1. Initialization
Initialize loop counter variable (`int i = 0`).
2. Condition Evaluation
Check boolean termination condition (`i < 10`).
3. Loop Body Execution
Execute statements inside braces (or single iteration block).
6. Loop Exit
Condition becomes false; program resumes execution below loop.
5. Repeat Cycle
Return to condition check for the next iteration cycle.
4. Update / Increment
Increment or decrement loop counter (`i++`).
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double itemPrices[] = {450.50, 1200.00, 325.25, 850.00};
int numItems = 4;
double cartSubtotal = 0.0;
for (int i = 0; i < numItems; i++) {
cartSubtotal += itemPrices[i];
}
cout << "--- E-Commerce Cart Summary ---" << endl;
cout << "Total Items in Cart : " << numItems << endl;
cout << "Calculated Subtotal : ₹" << fixed << setprecision(2) << cartSubtotal << endl;
return 0;
}
#include <iostream>
using namespace std;
int main() {
int countdownSeconds = 5;
cout << "--- Aerospace Launch Control ---" << endl;
while (countdownSeconds > 0) {
cout << "T-Minus " << countdownSeconds << " seconds..." << endl;
countdownSeconds--;
}
cout << "BLAST OFF! Rocket successfully launched into orbit." << endl;
return 0;
}
#include <iostream>
using namespace std;
int main() {
int correctPin = 4321;
int enteredPin = 1234; // Simulated incorrect attempt followed by correct
int attempts = 0;
cout << "--- ATM Security Terminal ---" << endl;
do {
attempts++;
// Simulating user input update for demo
if (attempts == 2) enteredPin = 4321;
cout << "Attempt " << attempts << " - PIN entered: " << enteredPin << endl;
if (enteredPin != correctPin) {
cout << "Incorrect PIN. Try again." << endl;
}
} while (enteredPin != correctPin && attempts < 3);
if (enteredPin == correctPin) {
cout << "Access Granted! Welcome to your account." << endl;
} else {
cout << "Card Blocked due to too many failed attempts." << endl;
}
return 0;
}
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double principal = 100000.00;
double annualRate = 0.08; // 8% return
int totalYears = 5;
cout << "--- 5-Year Investment Growth Projection ---" << endl;
for (int year = 1; year <= totalYears; year++) {
principal += (principal * annualRate);
cout << "Year " << year << " Value: ₹" << fixed << setprecision(2) << principal << endl;
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
int pollCycle = 0;
int sensorReadings[] = {45, 52, 60, 88, 70}; // 88 triggers overheat
cout << "--- Industrial Sensor Polling ---" << endl;
while (pollCycle < 5) {
int currentTemp = sensorReadings[pollCycle];
cout << "Cycle " << pollCycle + 1 << " - Temperature: " << currentTemp << "°C" << endl;
if (currentTemp >= 80) {
cout << "[CRITICAL ALERT]: Overheat threshold breached! Shutting down system." << endl;
break; // Exit loop immediately
}
pollCycle++;
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
cout << "--- Batch Processing Even IDs ---" << endl;
for (int id = 1; id <= 10; id++) {
// If ID is odd, skip this iteration
if (id % 2 != 0) {
continue;
}
cout << "Processing batch ID: " << id << endl;
}
return 0;
}
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
cout << "--- Pricing Tier Matrix (1 to 3) ---" << endl;
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 5; j++) {
cout << setw(4) << (i * j) << " ";
}
cout << endl;
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
int targetNumber = 29;
bool isPrime = true;
if (targetNumber <= 1) isPrime = false;
for (int i = 2; i <= targetNumber / 2; i++) {
if (targetNumber % i == 0) {
isPrime = false;
break;
}
}
cout << "--- Cryptographic Primality Test ---" << endl;
cout << "Target Number : " << targetNumber << endl;
cout << "Is Prime? : " << (isPrime ? "YES (Secure)" : "NO (Composite)") << endl;
return 0;
}
#include <iostream>
using namespace std;
int main() {
int choice = 1;
int transactionCount = 0;
cout << "--- POS Terminal Session ---" << endl;
do {
transactionCount++;
// Simulated menu choice: process 2 transactions then exit
if (transactionCount == 3) {
choice = 3; // Exit code
}
cout << "[Menu] 1. New Sale | 2. Refund | 3. Exit" << endl;
cout << "Cashier selected option: " << choice << endl;
if (choice == 1) {
cout << "-> Processing sale transaction..." << endl;
} else if (choice == 2) {
cout << "-> Processing refund..." << endl;
} else if (choice == 3) {
cout << "-> Closing terminal session." << endl;
}
} while (choice != 3);
return 0;
}
#include <iostream>
using namespace std;
int main() {
int n = 6;
long long factorialResult = 1;
for (int i = 1; i <= n; i++) {
factorialResult *= i;
}
cout << "--- Statistical Permutation Calculator ---" << endl;
cout << "Number (n) : " << n << endl;
cout << "Factorial (n!) : " << factorialResult << endl;
return 0;
}