cpp

exercises

exercises.cpp⚙️
/**
 * Module 01: Foundations
 * Topic: Input and Output
 * File: exercises.cpp
 * 
 * Complete the exercises below to practice I/O operations.
 * 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 <iomanip>
#include <string>
#include <limits>

using namespace std;

// ============================================================
// EXERCISE 1: Basic Output Practice
// Difficulty: ⭐ (Beginner)
// 
// Task: Print a personal information card using cout
// ============================================================
void exercise1() {
    cout << "\n=== EXERCISE 1: Personal Information Card ===" << endl;
    
    // TODO: Create and print a personal information card
    // It should look like this:
    //
    // ╔════════════════════════════════╗
    // ║     PERSONAL INFORMATION       ║
    // ╠════════════════════════════════╣
    // ║  Name:    [Your Name]          ║
    // ║  Age:     [Your Age]           ║
    // ║  City:    [Your City]          ║
    // ║  Country: [Your Country]       ║
    // ╚════════════════════════════════╝
    //
    // Hint: Use special characters like ╔ ╗ ╚ ╝ ║ ═ ╠ ╣
    // Or use simpler characters: + - | =
    
    // Write your code here:
    
    
}

// ============================================================
// EXERCISE 2: Escape Sequences
// Difficulty: ⭐ (Beginner)
// 
// Task: Create output using various escape sequences
// ============================================================
void exercise2() {
    cout << "\n=== EXERCISE 2: Escape Sequences ===" << endl;
    
    // TODO: Print the following (exactly as shown):
    //
    // 1. A file path: C:\Users\Name\Documents\file.txt
    // 2. A quote: He said, "Hello, World!"
    // 3. A tabbed list:
    //    Item1    100
    //    Item2    200
    //    Item3    300
    // 4. A multi-line address:
    //    John Doe
    //    123 Main St
    //    New York, NY 10001
    
    // Write your code here:
    
    
}

// ============================================================
// EXERCISE 3: Number Formatting Table
// Difficulty: ⭐⭐ (Intermediate)
// 
// Task: Create a formatted table showing numbers in different bases
// ============================================================
void exercise3() {
    cout << "\n=== EXERCISE 3: Number Base Table ===" << endl;
    
    // TODO: Create a table that shows numbers 1-16 in decimal, hex, and octal
    // 
    // Expected output:
    // +----------+----------+----------+
    // | Decimal  | Hex      | Octal    |
    // +----------+----------+----------+
    // |        1 |      0x1 |       01 |
    // |        2 |      0x2 |       02 |
    // ...
    // |       16 |     0x10 |      020 |
    // +----------+----------+----------+
    //
    // Hints:
    // - Use setw() for column widths
    // - Use showbase for 0x and 0 prefixes
    // - Remember to switch between dec, hex, oct
    
    // Write your code here:
    
    
}

// ============================================================
// EXERCISE 4: Price Formatting
// Difficulty: ⭐⭐ (Intermediate)
// 
// Task: Format monetary values correctly
// ============================================================
void exercise4() {
    cout << "\n=== EXERCISE 4: Price Formatting ===" << endl;
    
    // Given prices:
    double price1 = 9.5;
    double price2 = 100;
    double price3 = 49.999;
    double price4 = 1234.5;
    
    // TODO: Print each price in proper currency format:
    // - Always show 2 decimal places
    // - Right-align in a field of 12 characters
    // - Add $ prefix
    //
    // Expected output:
    // Price 1: $       9.50
    // Price 2: $     100.00
    // Price 3: $      50.00  (rounded)
    // Price 4: $   1,234.50  (optional: add comma)
    
    // Write your code here:
    
    
}

// ============================================================
// EXERCISE 5: Scientific Notation
// Difficulty: ⭐⭐ (Intermediate)
// 
// Task: Display scientific values in different formats
// ============================================================
void exercise5() {
    cout << "\n=== EXERCISE 5: Scientific Notation ===" << endl;
    
    double speedOfLight = 299792458;        // m/s
    double planckConstant = 6.62607015e-34; // J·s
    double avogadro = 6.02214076e23;        // /mol
    double electronMass = 9.1093837015e-31; // kg
    
    // TODO: Display each constant in:
    // 1. Default format
    // 2. Fixed notation with 2 decimal places
    // 3. Scientific notation with 4 decimal places
    //
    // Format like:
    // Speed of Light:
    //   Default:    2.99792e+08
    //   Fixed:      299792458.00
    //   Scientific: 2.9979e+08
    
    // Write your code here:
    
    
}

// ============================================================
// EXERCISE 6: Input and Calculate
// Difficulty: ⭐⭐ (Intermediate)
// 
// Task: Get user input and perform calculations
// ============================================================
void exercise6() {
    cout << "\n=== EXERCISE 6: Rectangle Calculator ===" << endl;
    
    // TODO: Create a rectangle calculator that:
    // 1. Asks for length and width
    // 2. Calculates and displays:
    //    - Area
    //    - Perimeter
    //    - Diagonal (use sqrt from <cmath>)
    //
    // Format the output nicely with labels
    //
    // Example:
    // Enter length: 5
    // Enter width: 3
    //
    // Rectangle Properties:
    // -------------------
    // Length:    5.00
    // Width:     3.00
    // Area:      15.00
    // Perimeter: 16.00
    // Diagonal:  5.83
    
    // For testing without input, use these values:
    double length = 5.0;
    double width = 3.0;
    
    // Write your code here:
    // (Replace hardcoded values with cin input when ready to test interactively)
    
    
}

// ============================================================
// EXERCISE 7: Input Validation
// Difficulty: ⭐⭐⭐ (Advanced)
// 
// Task: Implement robust input validation
// ============================================================
void exercise7() {
    cout << "\n=== EXERCISE 7: Input Validation ===" << endl;
    
    // TODO: Create a function that gets a valid integer in a range
    // 
    // Requirements:
    // 1. Keep asking until valid input is received
    // 2. Handle non-numeric input (letters, symbols)
    // 3. Handle out-of-range numbers
    // 4. Show appropriate error messages
    //
    // Test by getting:
    // - An age (0-150)
    // - A month (1-12)
    // - A percentage (0-100)
    
    cout << "Input validation demonstration:" << endl;
    cout << "(Implement the validation functions and test them)" << endl;
    
    // Write your validation function and test code here:
    
    
}

// ============================================================
// EXERCISE 8: Mixed Input Types
// Difficulty: ⭐⭐⭐ (Advanced)
// 
// Task: Handle mixing cin >> with getline
// ============================================================
void exercise8() {
    cout << "\n=== EXERCISE 8: Mixed Input Types ===" << endl;
    
    // TODO: Get the following information from the user:
    // 1. Student ID (integer)
    // 2. Full Name (string with spaces)
    // 3. GPA (double)
    // 4. Address (string with spaces)
    // 5. Age (integer)
    // 6. Bio (multi-word string)
    //
    // Remember: After cin >>, use cin.ignore() before getline!
    //
    // Display all information in a formatted card
    
    // For testing, use these simulated values:
    int studentId = 12345;
    string fullName = "John Doe";
    double gpa = 3.75;
    string address = "123 University Ave, College Town";
    int age = 20;
    string bio = "Computer Science major interested in AI";
    
    // Display the student card:
    // Write your code here:
    
    
}

// ============================================================
// EXERCISE 9: Formatted Report
// Difficulty: ⭐⭐⭐ (Advanced)
// 
// Task: Create a formatted sales report
// ============================================================
void exercise9() {
    cout << "\n=== EXERCISE 9: Sales Report ===" << endl;
    
    // Sales data
    string products[] = {"Laptop", "Mouse", "Keyboard", "Monitor", "Headphones"};
    int quantities[] = {5, 25, 15, 8, 12};
    double prices[] = {999.99, 29.99, 79.99, 299.99, 149.99};
    int numProducts = 5;
    
    // TODO: Create a professional sales report:
    //
    // ╔══════════════════════════════════════════════════════════╗
    // ║                    MONTHLY SALES REPORT                  ║
    // ║                      November 2024                       ║
    // ╠══════════════════════════════════════════════════════════╣
    // ║ Product      │ Qty  │ Unit Price │ Total      ║
    // ╠══════════════════════════════════════════════════════════╣
    // ║ Laptop       │    5 │    $999.99 │  $4,999.95 ║
    // ║ Mouse        │   25 │     $29.99 │    $749.75 ║
    // ║ ...          │  ... │        ... │        ... ║
    // ╠══════════════════════════════════════════════════════════╣
    // ║                              SUBTOTAL: $XX,XXX.XX        ║
    // ║                              TAX (8%): $X,XXX.XX         ║
    // ║                              TOTAL:    $XX,XXX.XX        ║
    // ╚══════════════════════════════════════════════════════════╝
    //
    // Use simpler characters if needed: + - | =
    
    // Write your code here:
    
    
}

// ============================================================
// EXERCISE 10: Interactive Menu System
// Difficulty: ⭐⭐⭐ (Advanced)
// 
// Task: Create a complete interactive menu
// ============================================================
void exercise10() {
    cout << "\n=== EXERCISE 10: Interactive Menu ===" << endl;
    
    // TODO: Create a calculator menu that:
    // 1. Displays a menu with options:
    //    1. Add
    //    2. Subtract
    //    3. Multiply
    //    4. Divide
    //    5. Exit
    // 2. Gets user choice
    // 3. Gets two numbers if operation selected
    // 4. Displays result with proper formatting
    // 5. Loops until Exit is selected
    //
    // Handle:
    // - Invalid menu choices
    // - Invalid number input
    // - Division by zero
    
    cout << "Menu system demonstration:" << endl;
    cout << "(Implement the full menu system)" << endl;
    
    // For demonstration, show what the menu should look like:
    cout << R"(
    ╔════════════════════════════╗
    ║      CALCULATOR MENU       ║
    ╠════════════════════════════╣
    ║  1. Add                    ║
    ║  2. Subtract               ║
    ║  3. Multiply               ║
    ║  4. Divide                 ║
    ║  5. Exit                   ║
    ╚════════════════════════════╝
    
    Enter choice: _
    )" << endl;
    
    // Write your code here:
    
    
}

// ============================================================
// BONUS: Custom Manipulator
// Difficulty: ⭐⭐⭐⭐ (Expert)
// ============================================================
void bonusExercise() {
    cout << "\n=== BONUS: Custom Output Formatting ===" << endl;
    
    // TODO: Create helper functions for common formatting tasks:
    //
    // 1. printCurrency(double amount) - prints "$1,234.56"
    // 2. printPercent(double value) - prints "75.5%"
    // 3. printBar(int width, char c) - prints a bar of characters
    // 4. printCentered(string text, int width) - prints centered text
    
    // Test your functions:
    // printCurrency(1234.56);   // $1,234.56
    // printPercent(0.755);      // 75.5%
    // printBar(30, '=');        // ==============================
    // printCentered("Hello", 20); //        Hello        
    
    cout << "(Implement the helper functions above)" << endl;
    
    // Write your code here:
    
    
}

// ============================================================
// MAIN FUNCTION
// ============================================================
int main() {
    cout << "╔══════════════════════════════════════════════════════╗" << endl;
    cout << "║     C++ Input/Output - 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 << "║     Key Skills Practiced:                            ║" << endl;
    cout << "║     - Basic cout and cin operations                  ║" << endl;
    cout << "║     - Formatting with iomanip                        ║" << endl;
    cout << "║     - Input validation                               ║" << endl;
    cout << "║     - Creating formatted reports                     ║" << endl;
    cout << "║                                                      ║" << endl;
    cout << "║     Next: 04_Variables_And_Data_Types                ║" << endl;
    cout << "╚══════════════════════════════════════════════════════╝" << endl;
    
    return 0;
}

/* ============================================================
 * ANSWER KEY (Selected Solutions)
 * ============================================================
 *
 * Exercise 3 - Number Base Table:
 * 
 * cout << showbase;
 * cout << setfill('-') << setw(32) << "" << setfill(' ') << endl;
 * cout << "| " << setw(8) << "Decimal" << " | " 
 *      << setw(8) << "Hex" << " | " 
 *      << setw(8) << "Octal" << " |" << endl;
 * cout << setfill('-') << setw(32) << "" << setfill(' ') << endl;
 * 
 * for (int i = 1; i <= 16; i++) {
 *     cout << "| " << dec << setw(8) << i << " | "
 *          << hex << setw(8) << i << " | "
 *          << oct << setw(8) << i << " |" << endl;
 * }
 * cout << dec << noshowbase;  // Reset
 *
 * Exercise 4 - Price Formatting:
 *
 * cout << fixed << setprecision(2);
 * cout << "Price 1: $" << setw(11) << price1 << endl;
 * cout << "Price 2: $" << setw(11) << price2 << endl;
 * cout << "Price 3: $" << setw(11) << price3 << endl;
 * cout << "Price 4: $" << setw(11) << price4 << endl;
 *
 * Exercise 7 - Input Validation:
 *
 * int getValidInt(int min, int max, const string& prompt) {
 *     int value;
 *     while (true) {
 *         cout << prompt;
 *         if (cin >> value && value >= min && value <= max) {
 *             cin.ignore(numeric_limits<streamsize>::max(), '\n');
 *             return value;
 *         }
 *         cout << "Invalid! Enter a number between " 
 *              << min << " and " << max << endl;
 *         cin.clear();
 *         cin.ignore(numeric_limits<streamsize>::max(), '\n');
 *     }
 * }
 */
Exercises - C++ Tutorial | DeepML