cpp

exercises

exercises.cpp⚙️
/**
 * Module 01: Foundations
 * Topic: Syntax and Structure
 * File: exercises.cpp
 * 
 * Complete the exercises below to practice syntax and structure concepts.
 * Each exercise has a TODO section for you to complete.
 * 
 * Compile: g++ -std=c++17 -Wall -Wextra exercises.cpp -o exercises
 * Run:     ./exercises
 */

#include <iostream>
#include <string>

using namespace std;

// ============================================================
// EXERCISE 1: Token Identification
// Difficulty: ⭐ (Beginner)
// 
// Task: For each line, add a comment identifying the token types.
//       Identify: keywords, identifiers, literals, operators, separators
// ============================================================
void exercise1() {
    cout << "\n=== EXERCISE 1: Token Identification ===" << endl;
    
    // TODO: Add comments identifying tokens in each line
    // Example: int age = 25;  // keyword:int, identifier:age, operator:=, literal:25, separator:;
    
    int count = 100;          // TODO: Identify tokens
    double price = 19.99;     // TODO: Identify tokens
    bool isValid = true;      // TODO: Identify tokens
    string name = "Alice";    // TODO: Identify tokens
    int sum = 5 + 3;          // TODO: Identify tokens
    
    cout << "Check your comments in the source code!" << endl;
    cout << "Each line should identify: keywords, identifiers, literals, operators, separators" << endl;
}

// ============================================================
// EXERCISE 2: Number Literal Conversions
// Difficulty: ⭐⭐ (Intermediate)
// 
// Task: Write the same value in different number formats
// ============================================================
void exercise2() {
    cout << "\n=== EXERCISE 2: Number Literal Conversions ===" << endl;
    
    // TODO: Write the number 42 in four different formats
    int decimal_42 = 0;       // TODO: Decimal form
    int hex_42 = 0;           // TODO: Hexadecimal form (0x...)
    int octal_42 = 0;         // TODO: Octal form (0...)
    int binary_42 = 0;        // TODO: Binary form (0b...)
    
    cout << "Decimal: " << decimal_42 << endl;
    cout << "Hex: " << hex_42 << endl;
    cout << "Octal: " << octal_42 << endl;
    cout << "Binary: " << binary_42 << endl;
    
    // TODO: Write one million using digit separators
    long long oneMillion = 0;  // TODO: Use digit separators (1'000'000)
    cout << "One million: " << oneMillion << endl;
    
    // All should print: 42, 42, 42, 42, 1000000
}

// ============================================================
// EXERCISE 3: Naming Convention Practice
// Difficulty: ⭐ (Beginner)
// 
// Task: Rename poorly named variables to follow conventions
// ============================================================
void exercise3() {
    cout << "\n=== EXERCISE 3: Naming Convention Practice ===" << endl;
    
    // TODO: Rename these variables following proper conventions
    // Use camelCase for regular variables
    // Use UPPER_CASE for constants
    
    int x = 25;                    // TODO: Should describe student's age
    double y = 3.14159;            // TODO: Should be a descriptive constant for PI
    bool z = true;                 // TODO: Should describe if user is logged in
    string s = "Introduction";     // TODO: Should describe a chapter title
    int n = 10;                    // TODO: Should describe maximum retry attempts
    
    // After renaming, print them with better variable names
    cout << "Original names were: x, y, z, s, n" << endl;
    cout << "Rename them to be descriptive!" << endl;
    
    // Uncomment and fix:
    // cout << "Student Age: " << studentAge << endl;
    // cout << "PI constant: " << PI << endl;
    // etc.
}

// ============================================================
// EXERCISE 4: Expression vs Statement
// Difficulty: ⭐⭐ (Intermediate)
// 
// Task: Identify whether each is an expression or statement
// ============================================================
void exercise4() {
    cout << "\n=== EXERCISE 4: Expression vs Statement ===" << endl;
    
    int a = 5, b = 10;
    
    // TODO: For each item below, print whether it's an EXPRESSION or STATEMENT
    // Then explain why
    
    // Items to classify:
    // 1. a + b
    // 2. a + b;
    // 3. int c = a + b;
    // 4. a > b
    // 5. a > b ? a : b
    // 6. { int temp = a; a = b; b = temp; }
    
    cout << "Classify each item in the source code!" << endl;
    cout << "1. a + b         = ?" << endl;
    cout << "2. a + b;        = ?" << endl;
    cout << "3. int c = a + b; = ?" << endl;
    cout << "4. a > b         = ?" << endl;
    cout << "5. a > b ? a : b = ?" << endl;
    cout << "6. { ... }       = ?" << endl;
    
    // Write your answers as comments:
    // 1. 
    // 2. 
    // 3. 
    // 4. 
    // 5. 
    // 6. 
}

// ============================================================
// EXERCISE 5: Scope Challenge
// Difficulty: ⭐⭐ (Intermediate)
// 
// Task: Predict the output, then run to verify
// ============================================================
void exercise5() {
    cout << "\n=== EXERCISE 5: Scope Challenge ===" << endl;
    
    int x = 1;
    cout << "A: x = " << x << endl;  // TODO: Predict value
    
    {
        int x = 2;
        cout << "B: x = " << x << endl;  // TODO: Predict value
        
        {
            int x = 3;
            cout << "C: x = " << x << endl;  // TODO: Predict value
            x = 30;
            cout << "D: x = " << x << endl;  // TODO: Predict value
        }
        
        cout << "E: x = " << x << endl;  // TODO: Predict value
        x = 20;
    }
    
    cout << "F: x = " << x << endl;  // TODO: Predict value
    
    // TODO: Write your predictions here BEFORE running:
    // A: ?
    // B: ?
    // C: ?
    // D: ?
    // E: ?
    // F: ?
}

// ============================================================
// EXERCISE 6: Fix the Syntax Errors
// Difficulty: ⭐⭐ (Intermediate)
// 
// Task: The code below has syntax errors. Identify and describe fixes.
// ============================================================
void exercise6() {
    cout << "\n=== EXERCISE 6: Fix the Syntax Errors ===" << endl;
    
    // TODO: Each commented block has errors. Describe the fixes needed.
    
    // Error 1:
    // Int number = 10
    // cout << number << endl;
    // Fix: 
    
    // Error 2:
    // int x = 5
    // if (x = 10) {
    //     cout << "x is 10" << endl;
    // }
    // Fix: 
    
    // Error 3:
    // string greeting = "Hello;
    // cout << greeting << endl;
    // Fix: 
    
    // Error 4:
    // int a = 5;
    // int b = 10;
    // int c = a ++ b;
    // Fix: 
    
    // Error 5:
    // if (true) {
    //     cout << "True" << endl;
    // else {
    //     cout << "False" << endl;
    // }
    // Fix: 
    
    cout << "Write fixes for each error as comments in the code!" << endl;
}

// ============================================================
// EXERCISE 7: Create a Proper Program Structure
// Difficulty: ⭐⭐⭐ (Advanced)
// 
// Task: Create a mini-program with proper structure
// ============================================================

// TODO: Add a global constant for MAX_ITEMS (value: 100)


// TODO: Forward declare a function called 'displayMenu'


void exercise7() {
    cout << "\n=== EXERCISE 7: Program Structure ===" << endl;
    
    // TODO: Call your displayMenu function
    
    // TODO: Use your MAX_ITEMS constant
    // cout << "Maximum items: " << MAX_ITEMS << endl;
    
    cout << "(Define the constant and function, then uncomment the code)" << endl;
}

// TODO: Define the displayMenu function
// It should print a simple menu like:
// ========== MENU ==========
// 1. Add Item
// 2. Remove Item
// 3. View Items
// 4. Exit
// ==========================


// ============================================================
// EXERCISE 8: Block Scoping Practice
// Difficulty: ⭐⭐ (Intermediate)
// 
// Task: Use block scoping to swap two variables
// ============================================================
void exercise8() {
    cout << "\n=== EXERCISE 8: Block Scoping Practice ===" << endl;
    
    int a = 100;
    int b = 200;
    
    cout << "Before swap: a = " << a << ", b = " << b << endl;
    
    // TODO: Use a block with a temporary variable to swap a and b
    // The temporary variable should only exist within the block
    // {
    //     // Your swap code here
    // }
    
    cout << "After swap: a = " << a << ", b = " << b << endl;
    // Should print: After swap: a = 200, b = 100
}

// ============================================================
// EXERCISE 9: Multi-Base Calculator
// Difficulty: ⭐⭐⭐ (Advanced)
// 
// Task: Create a calculator that works with different number bases
// ============================================================
void exercise9() {
    cout << "\n=== EXERCISE 9: Multi-Base Calculator ===" << endl;
    
    // TODO: Define numbers in different bases that add up to the same total
    
    // Set 1: Define three numbers that sum to 100
    int dec_40 = 0;     // TODO: 40 in decimal
    int hex_30 = 0;     // TODO: 30 in hexadecimal
    int bin_30 = 0;     // TODO: 30 in binary
    
    int sum1 = dec_40 + hex_30 + bin_30;
    cout << "Sum 1 (40 + 0x1E + 0b11110): " << sum1 << endl;
    cout << "Expected: 100" << endl;
    
    // Set 2: Multiply a hex number by an octal number
    int hex_16 = 0;     // TODO: 16 in hexadecimal (0x10)
    int oct_8 = 0;      // TODO: 8 in octal (010)
    
    int product = hex_16 * oct_8;
    cout << "Product (0x10 * 010): " << product << endl;
    cout << "Expected: 128" << endl;
}

// ============================================================
// EXERCISE 10: Complete Program Outline
// Difficulty: ⭐⭐⭐ (Advanced)
// 
// Task: Design a complete program structure for a student grade system
// ============================================================
void exercise10() {
    cout << "\n=== EXERCISE 10: Complete Program Outline ===" << endl;
    
    // TODO: Design (as comments) a complete program structure for:
    // A student grade management system
    
    // Your design should include:
    // 1. What #includes would you need?
    // 2. What global constants would you define?
    // 3. What functions would you declare (prototypes)?
    // 4. What would main() contain?
    // 5. What would each function do?
    
    cout << "Write your program design as comments in this function!" << endl;
    cout << "Consider:" << endl;
    cout << "- Adding a new student" << endl;
    cout << "- Recording grades" << endl;
    cout << "- Calculating averages" << endl;
    cout << "- Displaying reports" << endl;
    
    // DESIGN YOUR PROGRAM STRUCTURE HERE:
    /*
     * #include statements:
     * 
     * 
     * Global constants:
     * 
     * 
     * Function prototypes:
     * 
     * 
     * main() outline:
     * 
     * 
     * Function descriptions:
     * 
     * 
     */
}

// ============================================================
// BONUS: Command-Line Arguments Simulation
// Difficulty: ⭐⭐⭐ (Advanced)
// ============================================================
void bonusExercise() {
    cout << "\n=== BONUS: Command-Line Simulation ===" << endl;
    
    // Simulating command-line arguments
    // In real main(int argc, char* argv[]), these would come from command line
    
    const char* simulatedArgs[] = {
        "./program",
        "--verbose",
        "-n",
        "5",
        "input.txt"
    };
    int simulatedArgc = 5;
    
    cout << "Simulated command: ./program --verbose -n 5 input.txt" << endl;
    cout << "\nParsing arguments:" << endl;
    
    // TODO: Loop through and print each argument with its index
    // Expected output:
    // Arg 0: ./program
    // Arg 1: --verbose
    // Arg 2: -n
    // Arg 3: 5
    // Arg 4: input.txt
    
    for (int i = 0; i < simulatedArgc; i++) {
        // TODO: Print "Arg i: simulatedArgs[i]"
    }
    
    // TODO: Identify which argument is:
    // - The program name
    // - A flag (starts with -)
    // - A value
    // - A filename
}

// ============================================================
// MAIN FUNCTION
// ============================================================
int main() {
    cout << "╔══════════════════════════════════════════════════════╗" << endl;
    cout << "║     C++ Syntax and Structure - Exercises             ║" << endl;
    cout << "║     Complete the TODO sections in each exercise      ║" << endl;
    cout << "╚══════════════════════════════════════════════════════╝" << endl;
    
    exercise1();
    exercise2();
    exercise3();
    exercise4();
    exercise5();
    exercise6();
    exercise7();
    exercise8();
    exercise9();
    exercise10();
    bonusExercise();
    
    cout << "\n╔══════════════════════════════════════════════════════╗" << endl;
    cout << "║     Exercises Complete!                              ║" << endl;
    cout << "║                                                      ║" << endl;
    cout << "║     Tips:                                            ║" << endl;
    cout << "║     - Compile with -Wall -Wextra to catch issues     ║" << endl;
    cout << "║     - Read error messages carefully                  ║" << endl;
    cout << "║     - Move on to: 03_Input_Output                    ║" << endl;
    cout << "╚══════════════════════════════════════════════════════╝" << endl;
    
    return 0;
}

/* ============================================================
 * ANSWER KEY (Selected Answers)
 * ============================================================
 * 
 * Exercise 2 - Number Literals:
 * int decimal_42 = 42;
 * int hex_42 = 0x2A;
 * int octal_42 = 052;
 * int binary_42 = 0b101010;
 * long long oneMillion = 1'000'000;
 * 
 * Exercise 5 - Scope Output:
 * A: x = 1
 * B: x = 2
 * C: x = 3
 * D: x = 30
 * E: x = 2
 * F: x = 1
 * 
 * Exercise 8 - Swap:
 * {
 *     int temp = a;
 *     a = b;
 *     b = temp;
 * }
 * 
 * Exercise 9 - Multi-Base:
 * int dec_40 = 40;
 * int hex_30 = 0x1E;
 * int bin_30 = 0b11110;
 * int hex_16 = 0x10;
 * int oct_8 = 010;
 */
Exercises - C++ Tutorial | DeepML