cpp
examples
examples.cpp⚙️cpp
/**
* C++ Control Flow - Examples
*
* This file demonstrates control flow structures in C++ with practical examples.
* Each example is contained in its own function for easy understanding.
*
* Topics covered:
* - if, if-else, if-else-if statements
* - switch statements
* - for, while, do-while loops
* - Range-based for loops
* - break, continue, return statements
* - Nested loops
* - Common algorithms
*
* Compile: g++ -std=c++17 -Wall -Wextra examples.cpp -o examples
* Run: ./examples
*/
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <array>
#include <cmath>
using namespace std;
// ============================================================
// Example 1: if Statements
// ============================================================
void example_if_statements() {
cout << "\n=== Example 1: if Statements ===" << endl;
int age = 20;
// Simple if
cout << "Age: " << age << endl;
if (age >= 18) {
cout << "You are an adult." << endl;
}
// if with logical operators
int score = 85;
if (score >= 80 && score <= 100) {
cout << "Score " << score << ": Excellent performance!" << endl;
}
// Multiple conditions
int temperature = 25;
if (temperature > 30) {
cout << "It's hot!" << endl;
}
if (temperature >= 20 && temperature <= 30) {
cout << "Temperature " << temperature << "°C: Nice weather!" << endl;
}
if (temperature < 20) {
cout << "It's cold!" << endl;
}
}
// ============================================================
// Example 2: if-else Statements
// ============================================================
void example_if_else() {
cout << "\n=== Example 2: if-else Statements ===" << endl;
// Even or odd
for (int num : {4, 7, 12, 15}) {
if (num % 2 == 0) {
cout << num << " is even." << endl;
} else {
cout << num << " is odd." << endl;
}
}
// Positive, negative, or zero
cout << "\n-- Sign Check --" << endl;
for (int num : {-5, 0, 10}) {
if (num > 0) {
cout << num << " is positive." << endl;
} else if (num < 0) {
cout << num << " is negative." << endl;
} else {
cout << num << " is zero." << endl;
}
}
}
// ============================================================
// Example 3: if-else-if Ladder
// ============================================================
void example_if_else_if() {
cout << "\n=== Example 3: if-else-if Ladder ===" << endl;
// Grade calculator
vector<int> scores = {95, 82, 75, 65, 45};
for (int score : scores) {
char grade;
string message;
if (score >= 90) {
grade = 'A';
message = "Excellent!";
} else if (score >= 80) {
grade = 'B';
message = "Good job!";
} else if (score >= 70) {
grade = 'C';
message = "Satisfactory";
} else if (score >= 60) {
grade = 'D';
message = "Needs improvement";
} else {
grade = 'F';
message = "Failed";
}
cout << "Score: " << score << " -> Grade: " << grade
<< " (" << message << ")" << endl;
}
}
// ============================================================
// Example 4: Nested if Statements
// ============================================================
void example_nested_if() {
cout << "\n=== Example 4: Nested if Statements ===" << endl;
struct Person {
string name;
int age;
bool hasLicense;
bool hasInsurance;
};
vector<Person> people = {
{"Alice", 25, true, true},
{"Bob", 17, false, false},
{"Charlie", 20, true, false},
{"Diana", 30, false, true}
};
for (const auto& person : people) {
cout << "\n" << person.name << " (Age: " << person.age << "): ";
if (person.age >= 18) {
if (person.hasLicense) {
if (person.hasInsurance) {
cout << "Can drive legally." << endl;
} else {
cout << "Has license but needs insurance." << endl;
}
} else {
cout << "Adult but needs a license." << endl;
}
} else {
cout << "Too young to drive." << endl;
}
}
}
// ============================================================
// Example 5: switch Statement
// ============================================================
void example_switch() {
cout << "\n=== Example 5: switch Statement ===" << endl;
// Day of week
cout << "-- Days of Week --" << endl;
for (int day = 1; day <= 7; day++) {
cout << "Day " << day << ": ";
switch (day) {
case 1:
cout << "Monday" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
case 4:
cout << "Thursday" << endl;
break;
case 5:
cout << "Friday" << endl;
break;
case 6:
case 7:
cout << "Weekend!" << endl;
break;
default:
cout << "Invalid day" << endl;
}
}
// Menu selection
cout << "\n-- Menu Selection --" << endl;
char choice = 'B';
cout << "User selected: " << choice << endl;
switch (choice) {
case 'A':
case 'a':
cout << "Option A: Create new file" << endl;
break;
case 'B':
case 'b':
cout << "Option B: Open existing file" << endl;
break;
case 'C':
case 'c':
cout << "Option C: Save file" << endl;
break;
case 'Q':
case 'q':
cout << "Quit program" << endl;
break;
default:
cout << "Unknown option" << endl;
}
}
// ============================================================
// Example 6: for Loop
// ============================================================
void example_for_loop() {
cout << "\n=== Example 6: for Loop ===" << endl;
// Basic counting
cout << "Count 1-5: ";
for (int i = 1; i <= 5; i++) {
cout << i << " ";
}
cout << endl;
// Counting backward
cout << "Count 5-1: ";
for (int i = 5; i >= 1; i--) {
cout << i << " ";
}
cout << endl;
// Step by 2
cout << "Even numbers 2-10: ";
for (int i = 2; i <= 10; i += 2) {
cout << i << " ";
}
cout << endl;
// Multiple variables
cout << "\n-- Two Variables --" << endl;
for (int i = 0, j = 10; i < j; i++, j--) {
cout << "i=" << i << ", j=" << j << endl;
}
// Sum calculation
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
cout << "\nSum of 1-100: " << sum << endl;
}
// ============================================================
// Example 7: while Loop
// ============================================================
void example_while_loop() {
cout << "\n=== Example 7: while Loop ===" << endl;
// Basic while
cout << "Count down: ";
int count = 5;
while (count > 0) {
cout << count << " ";
count--;
}
cout << "Blastoff!" << endl;
// Find digits in a number
cout << "\n-- Count Digits --" << endl;
int number = 123456;
int original = number;
int digitCount = 0;
while (number > 0) {
digitCount++;
number /= 10;
}
cout << original << " has " << digitCount << " digits" << endl;
// Reverse a number
cout << "\n-- Reverse Number --" << endl;
number = 12345;
int reversed = 0;
original = number;
while (number > 0) {
int digit = number % 10;
reversed = reversed * 10 + digit;
number /= 10;
}
cout << original << " reversed is " << reversed << endl;
// Collatz conjecture
cout << "\n-- Collatz Sequence (starting from 13) --" << endl;
int n = 13;
cout << n;
while (n != 1) {
if (n % 2 == 0) {
n = n / 2;
} else {
n = 3 * n + 1;
}
cout << " -> " << n;
}
cout << endl;
}
// ============================================================
// Example 8: do-while Loop
// ============================================================
void example_do_while() {
cout << "\n=== Example 8: do-while Loop ===" << endl;
// Guaranteed execution
cout << "-- Guaranteed Execution --" << endl;
int x = 100;
do {
cout << "do-while with x=" << x << " (condition x < 10 is false)" << endl;
} while (x < 10);
// Compare with while
while (x < 10) {
cout << "while loop never executes" << endl;
}
cout << "while loop skipped (condition false)" << endl;
// Digit sum
cout << "\n-- Digit Sum --" << endl;
int number = 9876;
int sum = 0;
int original = number;
do {
sum += number % 10;
number /= 10;
} while (number > 0);
cout << "Sum of digits in " << original << " is " << sum << endl;
// Menu simulation
cout << "\n-- Menu Simulation --" << endl;
int choice = 1;
int iteration = 0;
do {
iteration++;
cout << "Iteration " << iteration << ": Processing choice " << choice << endl;
choice++; // Simulate user input
} while (choice <= 3);
cout << "Menu exited after " << iteration << " iterations" << endl;
}
// ============================================================
// Example 9: Range-based for Loop
// ============================================================
void example_range_for() {
cout << "\n=== Example 9: Range-based for Loop ===" << endl;
// Array
cout << "-- Array --" << endl;
int arr[] = {10, 20, 30, 40, 50};
cout << "Elements: ";
for (int x : arr) {
cout << x << " ";
}
cout << endl;
// Vector
cout << "\n-- Vector --" << endl;
vector<string> fruits = {"Apple", "Banana", "Cherry", "Date"};
cout << "Fruits: ";
for (const string& fruit : fruits) {
cout << fruit << " ";
}
cout << endl;
// String
cout << "\n-- String Characters --" << endl;
string word = "Hello";
cout << "Characters in '" << word << "': ";
for (char c : word) {
cout << c << " ";
}
cout << endl;
// Modify elements
cout << "\n-- Modify Elements --" << endl;
vector<int> nums = {1, 2, 3, 4, 5};
cout << "Original: ";
for (int n : nums) cout << n << " ";
cout << endl;
for (int& n : nums) {
n *= 2;
}
cout << "Doubled: ";
for (int n : nums) cout << n << " ";
cout << endl;
// Initializer list
cout << "\n-- Initializer List --" << endl;
cout << "Powers of 2: ";
for (int x : {1, 2, 4, 8, 16, 32, 64}) {
cout << x << " ";
}
cout << endl;
// With auto
cout << "\n-- Using auto --" << endl;
vector<pair<string, int>> students = {{"Alice", 95}, {"Bob", 87}, {"Charlie", 92}};
for (const auto& [name, score] : students) { // C++17 structured binding
cout << name << ": " << score << endl;
}
}
// ============================================================
// Example 10: break and continue
// ============================================================
void example_break_continue() {
cout << "\n=== Example 10: break and continue ===" << endl;
// break example
cout << "-- break Example --" << endl;
cout << "Searching for 7 in {2, 4, 6, 7, 8, 10}: ";
int target = 7;
int arr[] = {2, 4, 6, 7, 8, 10};
bool found = false;
for (int i = 0; i < 6; i++) {
if (arr[i] == target) {
cout << "Found at index " << i << endl;
found = true;
break;
}
}
if (!found) cout << "Not found" << endl;
// continue example
cout << "\n-- continue Example --" << endl;
cout << "Odd numbers 1-10: ";
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue;
cout << i << " ";
}
cout << endl;
// Skip negative numbers
cout << "\n-- Skip Negatives --" << endl;
int mixed[] = {3, -1, 4, -1, 5, -9, 2, 6};
int sum = 0;
cout << "Processing: ";
for (int n : mixed) {
if (n < 0) {
cout << "[skip " << n << "] ";
continue;
}
sum += n;
cout << n << " ";
}
cout << "\nSum of positives: " << sum << endl;
// Find first vowel
cout << "\n-- Find First Vowel --" << endl;
string text = "Crystal";
char firstVowel = '\0';
for (char c : text) {
c = tolower(c);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
firstVowel = c;
break;
}
}
if (firstVowel != '\0') {
cout << "First vowel in '" << text << "': " << firstVowel << endl;
} else {
cout << "No vowel found in '" << text << "'" << endl;
}
}
// ============================================================
// Example 11: Nested Loops
// ============================================================
void example_nested_loops() {
cout << "\n=== Example 11: Nested Loops ===" << endl;
// Multiplication table
cout << "-- Multiplication Table (5x5) --" << endl;
cout << " ";
for (int j = 1; j <= 5; j++) {
cout << setw(4) << j;
}
cout << endl << " " << string(20, '-') << endl;
for (int i = 1; i <= 5; i++) {
cout << setw(2) << i << " |";
for (int j = 1; j <= 5; j++) {
cout << setw(4) << i * j;
}
cout << endl;
}
// Triangle pattern
cout << "\n-- Right Triangle --" << endl;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
cout << "* ";
}
cout << endl;
}
// Inverted triangle
cout << "\n-- Inverted Triangle --" << endl;
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
cout << "* ";
}
cout << endl;
}
// Number pyramid
cout << "\n-- Number Pyramid --" << endl;
for (int i = 1; i <= 5; i++) {
// Print spaces
for (int s = 5 - i; s > 0; s--) {
cout << " ";
}
// Print numbers
for (int j = 1; j <= i; j++) {
cout << j << " ";
}
cout << endl;
}
// Matrix search with break
cout << "\n-- Matrix Search --" << endl;
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
target = 7;
found = false;
for (int i = 0; i < 3 && !found; i++) {
for (int j = 0; j < 4 && !found; j++) {
if (matrix[i][j] == target) {
cout << "Found " << target << " at [" << i << "][" << j << "]" << endl;
found = true;
}
}
}
}
// ============================================================
// Example 12: Common Algorithms
// ============================================================
void example_algorithms() {
cout << "\n=== Example 12: Common Algorithms ===" << endl;
int arr[] = {64, 25, 12, 22, 11, 25, 64};
int size = sizeof(arr) / sizeof(arr[0]);
// Find minimum and maximum
cout << "-- Min/Max --" << endl;
int minVal = arr[0], maxVal = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] < minVal) minVal = arr[i];
if (arr[i] > maxVal) maxVal = arr[i];
}
cout << "Array: ";
for (int x : arr) cout << x << " ";
cout << "\nMin: " << minVal << ", Max: " << maxVal << endl;
// Calculate average
cout << "\n-- Average --" << endl;
int sum = 0;
for (int x : arr) sum += x;
double average = static_cast<double>(sum) / size;
cout << "Sum: " << sum << ", Average: " << fixed << setprecision(2) << average << endl;
// Count occurrences
cout << "\n-- Count Occurrences --" << endl;
int target = 25;
int count = 0;
for (int x : arr) {
if (x == target) count++;
}
cout << target << " appears " << count << " time(s)" << endl;
// Check if sorted
cout << "\n-- Check if Sorted --" << endl;
int sorted[] = {1, 2, 3, 4, 5};
int unsorted[] = {3, 1, 4, 1, 5};
auto isSorted = [](int a[], int n) {
for (int i = 1; i < n; i++) {
if (a[i] < a[i-1]) return false;
}
return true;
};
cout << "{1,2,3,4,5} is " << (isSorted(sorted, 5) ? "" : "not ") << "sorted" << endl;
cout << "{3,1,4,1,5} is " << (isSorted(unsorted, 5) ? "" : "not ") << "sorted" << endl;
// Prime numbers in range
cout << "\n-- Prime Numbers 2-30 --" << endl;
auto isPrime = [](int n) {
if (n < 2) return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return false;
}
return true;
};
cout << "Primes: ";
for (int i = 2; i <= 30; i++) {
if (isPrime(i)) cout << i << " ";
}
cout << endl;
// Fibonacci sequence
cout << "\n-- Fibonacci (first 10) --" << endl;
int a = 0, b = 1;
cout << a << " " << b << " ";
for (int i = 2; i < 10; i++) {
int next = a + b;
cout << next << " ";
a = b;
b = next;
}
cout << endl;
// Factorial
cout << "\n-- Factorials --" << endl;
for (int n = 0; n <= 10; n++) {
unsigned long long fact = 1;
for (int i = 2; i <= n; i++) {
fact *= i;
}
cout << n << "! = " << fact << endl;
}
}
// ============================================================
// Example 13: Loop Patterns
// ============================================================
void example_loop_patterns() {
cout << "\n=== Example 13: Loop Patterns ===" << endl;
// Counter-controlled loop
cout << "-- Counter-Controlled --" << endl;
cout << "Processing items 1-5: ";
for (int i = 1; i <= 5; i++) {
cout << i << " ";
}
cout << endl;
// Sentinel-controlled loop (simulated)
cout << "\n-- Sentinel-Controlled --" << endl;
int values[] = {5, 10, 15, 20, -1}; // -1 is sentinel
int i = 0;
int sum = 0;
cout << "Values until sentinel (-1): ";
while (values[i] != -1) {
cout << values[i] << " ";
sum += values[i];
i++;
}
cout << "\nSum: " << sum << endl;
// Flag-controlled loop
cout << "\n-- Flag-Controlled --" << endl;
int data[] = {2, 4, 6, 7, 8, 10};
bool foundOdd = false;
i = 0;
while (!foundOdd && i < 6) {
if (data[i] % 2 != 0) {
cout << "First odd number found: " << data[i] << " at index " << i << endl;
foundOdd = true;
}
i++;
}
// Early termination with validation
cout << "\n-- Early Termination --" << endl;
int numbers[] = {10, 20, 30, 40, 50};
target = 30;
int result = -1;
for (i = 0; i < 5; i++) {
if (numbers[i] == target) {
result = i;
break; // Early termination
}
cout << "Checked index " << i << endl;
}
cout << "Found " << target << " at index " << result << endl;
}
// ============================================================
// Example 14: Advanced Control Flow
// ============================================================
void example_advanced_control() {
cout << "\n=== Example 14: Advanced Control Flow ===" << endl;
// C++17: if with initializer
cout << "-- if with Initializer (C++17) --" << endl;
vector<int> vec = {1, 2, 3, 4, 5};
if (auto it = find(vec.begin(), vec.end(), 3); it != vec.end()) {
cout << "Found 3 at index " << distance(vec.begin(), it) << endl;
}
// C++17: switch with initializer
cout << "\n-- switch with Initializer (C++17) --" << endl;
auto getStatus = []() { return 2; };
switch (int status = getStatus(); status) {
case 1:
cout << "Status: Active" << endl;
break;
case 2:
cout << "Status: Pending" << endl;
break;
case 3:
cout << "Status: Completed" << endl;
break;
default:
cout << "Status: Unknown (" << status << ")" << endl;
}
// Multiple return points
cout << "\n-- Multiple Return Points --" << endl;
auto classify = [](int n) -> string {
if (n < 0) return "negative";
if (n == 0) return "zero";
if (n < 10) return "single digit";
if (n < 100) return "two digits";
return "large number";
};
for (int n : {-5, 0, 7, 42, 1000}) {
cout << n << " is a " << classify(n) << endl;
}
// Nested loop with labeled break (using flag)
cout << "\n-- Breaking Nested Loops --" << endl;
bool breakOuter = false;
for (int i = 1; i <= 3 && !breakOuter; i++) {
for (int j = 1; j <= 3; j++) {
cout << "(" << i << "," << j << ") ";
if (i == 2 && j == 2) {
cout << "[break] ";
breakOuter = true;
break;
}
}
if (!breakOuter) cout << endl;
}
cout << endl;
// Using lambda to break nested loops
cout << "\n-- Lambda for Nested Loop Control --" << endl;
auto findPair = [](int target) -> pair<int, int> {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
if (i * j == target) {
return {i, j};
}
}
}
return {-1, -1};
};
auto [x, y] = findPair(12);
cout << "First pair with product 12: (" << x << ", " << y << ")" << endl;
}
// ============================================================
// Main Function - Run All Examples
// ============================================================
int main() {
cout << "╔════════════════════════════════════════════════════════════╗" << endl;
cout << "║ C++ CONTROL FLOW - COMPREHENSIVE EXAMPLES ║" << endl;
cout << "╚════════════════════════════════════════════════════════════╝" << endl;
example_if_statements();
example_if_else();
example_if_else_if();
example_nested_if();
example_switch();
example_for_loop();
example_while_loop();
example_do_while();
example_range_for();
example_break_continue();
example_nested_loops();
example_algorithms();
example_loop_patterns();
example_advanced_control();
cout << "\n╔════════════════════════════════════════════════════════════╗" << endl;
cout << "║ ALL EXAMPLES COMPLETE ║" << endl;
cout << "╚════════════════════════════════════════════════════════════╝" << endl;
return 0;
}