cpp

loops

02_loops.cpp⚙️
/**
 * ============================================================
 * C++ CONTROL FLOW - LOOPS
 * ============================================================
 * 
 * This file covers:
 * - for loops
 * - while loops
 * - do-while loops
 * - Range-based for loops
 * - break, continue, goto
 * - Nested loops
 * 
 * Compile: g++ -std=c++17 -Wall 02_loops.cpp -o loops
 * Run: ./loops
 * 
 * ============================================================
 */

#include <iostream>
#include <vector>
#include <string>
#include <array>

using namespace std;

int main() {
    cout << "============================================" << endl;
    cout << "     C++ LOOPS" << endl;
    cout << "============================================" << endl << endl;

    // ========================================================
    // PART 1: for LOOP
    // ========================================================
    
    cout << "--- PART 1: for LOOP ---" << endl << endl;
    
    // Basic for loop
    // for (initialization; condition; update) { body }
    
    cout << "Counting 1 to 5: ";
    for (int i = 1; i <= 5; i++) {
        cout << i << " ";
    }
    cout << endl;
    
    // Counting down
    cout << "Counting down 5 to 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 << "Multiple variables: ";
    for (int i = 0, j = 10; i < j; i++, j--) {
        cout << "(" << i << "," << j << ") ";
    }
    cout << endl;
    
    // Iterating over array
    int numbers[] = {10, 20, 30, 40, 50};
    int size = sizeof(numbers) / sizeof(numbers[0]);
    
    cout << "Array elements: ";
    for (int i = 0; i < size; i++) {
        cout << numbers[i] << " ";
    }
    cout << endl;
    
    // Omitting parts of for loop
    cout << "\nOmitting loop parts:" << endl;
    int k = 0;
    for (; k < 3; k++) {  // No initialization
        cout << k << " ";
    }
    cout << endl;
    
    // Infinite loop (commented out)
    // for (;;) { /* runs forever */ }
    
    cout << endl;

    // ========================================================
    // PART 2: while LOOP
    // ========================================================
    
    cout << "--- PART 2: while LOOP ---" << endl << endl;
    
    // Basic while loop
    // while (condition) { body }
    
    int count = 1;
    cout << "While loop 1-5: ";
    while (count <= 5) {
        cout << count << " ";
        count++;
    }
    cout << endl;
    
    // Sum of numbers
    int sum = 0;
    int n = 1;
    while (n <= 10) {
        sum += n;
        n++;
    }
    cout << "Sum of 1-10: " << sum << endl;
    
    // Finding digits in a number
    int num = 12345;
    int digitCount = 0;
    int temp = num;
    while (temp > 0) {
        digitCount++;
        temp /= 10;
    }
    cout << "Digits in " << num << ": " << digitCount << endl;
    
    // Condition at start - may not execute at all
    int x = 10;
    while (x < 5) {  // False from start
        cout << "This won't print" << endl;
        x++;
    }
    cout << "While with false condition: didn't execute" << endl;
    
    cout << endl;

    // ========================================================
    // PART 3: do-while LOOP
    // ========================================================
    
    cout << "--- PART 3: do-while LOOP ---" << endl << endl;
    
    // do-while executes at least once
    // do { body } while (condition);
    
    int counter = 1;
    cout << "Do-while 1-5: ";
    do {
        cout << counter << " ";
        counter++;
    } while (counter <= 5);
    cout << endl;
    
    // Executes at least once, even with false condition
    int y = 10;
    cout << "Do-while with false condition: ";
    do {
        cout << y << " ";  // Prints once
        y++;
    } while (y < 5);
    cout << "(executed once)" << endl;
    
    // Menu example (common use case)
    cout << "\nMenu simulation:" << endl;
    int choice = 0;
    int menuRuns = 0;
    do {
        menuRuns++;
        // Simulate menu selection (in real code, would get user input)
        choice = (menuRuns < 3) ? 1 : 0;  // Exit after 3 iterations
        cout << "  Menu iteration " << menuRuns << ", choice: " << choice << endl;
    } while (choice != 0);
    
    cout << endl;

    // ========================================================
    // PART 4: RANGE-BASED for LOOP (C++11)
    // ========================================================
    
    cout << "--- PART 4: RANGE-BASED for LOOP ---" << endl << endl;
    
    // Modern way to iterate over collections
    // for (type element : collection) { body }
    
    // Array
    int arr[] = {1, 2, 3, 4, 5};
    cout << "Range-based over array: ";
    for (int elem : arr) {
        cout << elem << " ";
    }
    cout << endl;
    
    // Vector
    vector<string> fruits = {"apple", "banana", "cherry"};
    cout << "Range-based over vector: ";
    for (string fruit : fruits) {
        cout << fruit << " ";
    }
    cout << endl;
    
    // With auto (type inference)
    cout << "With auto: ";
    for (auto fruit : fruits) {
        cout << fruit << " ";
    }
    cout << endl;
    
    // By reference (to modify or avoid copying)
    cout << "Doubling values: ";
    vector<int> vals = {1, 2, 3, 4, 5};
    for (int& v : vals) {  // Reference to modify
        v *= 2;
    }
    for (auto v : vals) {
        cout << v << " ";
    }
    cout << endl;
    
    // Const reference (read-only, no copy)
    cout << "Const reference: ";
    for (const auto& v : vals) {
        cout << v << " ";
    }
    cout << endl;
    
    // Initializer list
    cout << "Initializer list: ";
    for (int i : {10, 20, 30, 40}) {
        cout << i << " ";
    }
    cout << endl;
    
    // String characters
    string text = "Hello";
    cout << "String characters: ";
    for (char c : text) {
        cout << c << "-";
    }
    cout << endl;
    
    cout << endl;

    // ========================================================
    // PART 5: break AND continue
    // ========================================================
    
    cout << "--- PART 5: break AND continue ---" << endl << endl;
    
    // break - exit loop immediately
    cout << "Break at 5: ";
    for (int i = 1; i <= 10; i++) {
        if (i == 5) break;
        cout << i << " ";
    }
    cout << "(stopped)" << endl;
    
    // continue - skip to next iteration
    cout << "Skip 5: ";
    for (int i = 1; i <= 10; i++) {
        if (i == 5) continue;
        cout << i << " ";
    }
    cout << endl;
    
    // Break in nested loops (exits inner only)
    cout << "\nBreak in nested loop:" << endl;
    for (int i = 1; i <= 3; i++) {
        cout << "Outer " << i << ": ";
        for (int j = 1; j <= 5; j++) {
            if (j == 3) break;
            cout << j << " ";
        }
        cout << endl;
    }
    
    // Finding first match
    int target = 7;
    int found = -1;
    int searchArr[] = {2, 5, 7, 9, 11};
    for (int i = 0; i < 5; i++) {
        if (searchArr[i] == target) {
            found = i;
            break;
        }
    }
    cout << "\nFound " << target << " at index: " << found << endl;
    
    cout << endl;

    // ========================================================
    // PART 6: NESTED LOOPS
    // ========================================================
    
    cout << "--- PART 6: NESTED LOOPS ---" << endl << endl;
    
    // Multiplication table
    cout << "Multiplication Table (1-5):" << endl;
    for (int i = 1; i <= 5; i++) {
        for (int j = 1; j <= 5; j++) {
            cout << i * j << "\t";
        }
        cout << endl;
    }
    
    // Pattern: Right triangle
    cout << "\nRight triangle:" << endl;
    for (int i = 1; i <= 5; i++) {
        for (int j = 1; j <= i; j++) {
            cout << "* ";
        }
        cout << endl;
    }
    
    // Pattern: Inverted triangle
    cout << "\nInverted triangle:" << endl;
    for (int i = 5; i >= 1; i--) {
        for (int j = 1; j <= i; j++) {
            cout << "* ";
        }
        cout << endl;
    }
    
    // Pattern: Number pyramid
    cout << "\nNumber pyramid:" << endl;
    for (int i = 1; i <= 5; i++) {
        // Spaces
        for (int s = 5; s > i; s--) {
            cout << " ";
        }
        // Numbers
        for (int j = 1; j <= i; j++) {
            cout << j << " ";
        }
        cout << endl;
    }
    
    // 2D array traversal
    cout << "\n2D Array traversal:" << endl;
    int matrix[3][4] = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12}
    };
    
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 4; j++) {
            cout << matrix[i][j] << "\t";
        }
        cout << endl;
    }
    
    cout << endl;

    // ========================================================
    // PART 7: LOOP EXAMPLES
    // ========================================================
    
    cout << "--- PART 7: PRACTICAL EXAMPLES ---" << endl << endl;
    
    // Prime number check
    int checkNum = 17;
    bool isPrime = true;
    if (checkNum <= 1) isPrime = false;
    for (int i = 2; i * i <= checkNum && isPrime; i++) {
        if (checkNum % i == 0) isPrime = false;
    }
    cout << checkNum << " is " << (isPrime ? "prime" : "not prime") << endl;
    
    // Fibonacci sequence
    cout << "Fibonacci (first 10): ";
    int fib1 = 0, fib2 = 1;
    cout << fib1 << " " << fib2 << " ";
    for (int i = 2; i < 10; i++) {
        int next = fib1 + fib2;
        cout << next << " ";
        fib1 = fib2;
        fib2 = next;
    }
    cout << endl;
    
    // Factorial
    int factNum = 5;
    long long factorial = 1;
    for (int i = 2; i <= factNum; i++) {
        factorial *= i;
    }
    cout << factNum << "! = " << factorial << endl;
    
    // Reverse a number
    int original = 12345;
    int reversed = 0;
    int tempNum = original;
    while (tempNum > 0) {
        reversed = reversed * 10 + tempNum % 10;
        tempNum /= 10;
    }
    cout << "Reverse of " << original << " is " << reversed << endl;
    
    cout << endl;

    cout << "============================================" << endl;
    cout << "LOOP SELECTION GUIDE:" << endl;
    cout << "============================================" << endl;
    cout << "for:       Known number of iterations" << endl;
    cout << "while:     Unknown iterations, check first" << endl;
    cout << "do-while:  At least one iteration needed" << endl;
    cout << "range-for: Iterating over collections" << endl;
    cout << "============================================" << endl;

    return 0;
}

// ============================================================
// EXERCISES:
// ============================================================
/*
 * 1. Print all prime numbers between 1 and 100
 * 
 * 2. Create these patterns:
 *    a) Square of stars
 *    b) Diamond shape
 *    c) Floyd's triangle
 * 
 * 3. Write a program to find GCD of two numbers using loops
 * 
 * 4. Create a number guessing game where user has limited attempts
 * 
 * 5. Print Pascal's triangle up to n rows
 */
Loops - C++ Tutorial | DeepML