cpp

examples

examples.cpp⚙️
/**
 * Module 01: Foundations
 * Topic: Syntax and Structure
 * File: examples.cpp
 * 
 * This file demonstrates C++ syntax elements and program structure.
 * Study these examples after reading README.md.
 * 
 * Compile: g++ -std=c++17 -Wall -Wextra examples.cpp -o examples
 * Run:     ./examples
 */

#include <iostream>
#include <string>
#include <iomanip>  // For setw, setfill

using namespace std;

// ============================================================
// GLOBAL DECLARATIONS
// ============================================================

// Global constant
const double PI = 3.14159265359;

// Global variable (use sparingly!)
int globalCounter = 0;

// Forward declarations (prototypes)
void demonstrateScope();
int factorial(int n);

// ============================================================
// EXAMPLE 1: Token Types
// ============================================================
void example1_tokens() {
    cout << "\n=== EXAMPLE 1: Token Types ===" << endl;
    
    // Keywords: int, double, bool, return, if, etc.
    int number = 42;           // 'int' is a keyword
    
    // Identifiers: names we create
    int myVariable = 10;       // 'myVariable' is an identifier
    
    // Literals: fixed values
    int intLiteral = 100;      // Integer literal
    double doubleLit = 3.14;   // Floating-point literal
    char charLiteral = 'A';    // Character literal
    bool boolLiteral = true;   // Boolean literal
    
    // String literal
    string strLiteral = "Hello, World!";
    
    // Operators: +, -, *, /, ==, etc.
    int sum = 5 + 3;           // '+' is an operator
    
    // Separators: ;, {}, (), []
    // The semicolons, braces, parentheses are separators
    
    cout << "Integer: " << intLiteral << endl;
    cout << "Double: " << doubleLit << endl;
    cout << "Char: " << charLiteral << endl;
    cout << "Bool: " << boolLiteral << endl;
    cout << "String: " << strLiteral << endl;
    cout << "Sum: " << sum << endl;
}

// ============================================================
// EXAMPLE 2: Number Literals
// ============================================================
void example2_number_literals() {
    cout << "\n=== EXAMPLE 2: Number Literals ===" << endl;
    
    // Different bases for integers
    int decimal = 255;          // Base 10 (decimal)
    int octal = 0377;           // Base 8 (octal) - starts with 0
    int hex = 0xFF;             // Base 16 (hex) - starts with 0x
    int binary = 0b11111111;    // Base 2 (binary) - starts with 0b
    
    cout << "Decimal 255:    " << decimal << endl;
    cout << "Octal 0377:     " << octal << endl;
    cout << "Hex 0xFF:       " << hex << endl;
    cout << "Binary 0b11111111: " << binary << endl;
    cout << "(All represent the same value: 255)" << endl;
    
    // Digit separators (C++14) for readability
    long long bigNumber = 1'000'000'000;  // One billion
    double scientific = 6.022'140'76e23;  // Avogadro's number
    
    cout << "\nBig number: " << bigNumber << endl;
    cout << "Avogadro: " << scientific << endl;
    
    // Floating-point forms
    double d1 = 3.14;           // Standard
    double d2 = 314e-2;         // Scientific: 3.14
    double d3 = .5;             // 0.5
    double d4 = 5.;             // 5.0
    
    cout << "\nFloat forms: " << d1 << ", " << d2 << ", " << d3 << ", " << d4 << endl;
}

// ============================================================
// EXAMPLE 3: Identifiers and Naming
// ============================================================
void example3_identifiers() {
    cout << "\n=== EXAMPLE 3: Identifiers and Naming ===" << endl;
    
    // camelCase (common for variables/functions)
    int studentCount = 42;
    string firstName = "John";
    bool isActive = true;
    
    // snake_case (also common)
    int total_amount = 100;
    string last_name = "Doe";
    bool has_permission = true;
    
    // UPPER_CASE (for constants - we use const here)
    const int MAX_STUDENTS = 100;
    const double TAX_RATE = 0.08;
    
    // PascalCase is typically for class names
    // class StudentRecord { };  // Just showing convention
    
    // Prefixes for special cases
    int m_memberVariable = 0;   // m_ for member variables
    int g_globalVar = 0;        // g_ for globals (if you must)
    
    cout << "studentCount: " << studentCount << endl;
    cout << "firstName: " << firstName << endl;
    cout << "total_amount: " << total_amount << endl;
    cout << "MAX_STUDENTS: " << MAX_STUDENTS << endl;
    
    // Good naming practices
    int numberOfItems = 5;              // Descriptive
    bool hasPermission = true;          // Boolean as question
    double calculateInterestRate = 0.05; // Could be function name
    
    cout << "Good names are self-documenting!" << endl;
}

// ============================================================
// EXAMPLE 4: Statements vs Expressions
// ============================================================
void example4_statements_expressions() {
    cout << "\n=== EXAMPLE 4: Statements vs Expressions ===" << endl;
    
    // EXPRESSIONS - produce values
    // (These are used within statements)
    
    int a = 5, b = 3;
    
    // Expression examples (we print their values):
    cout << "Expression '5 + 3' evaluates to: " << (5 + 3) << endl;
    cout << "Expression 'a * b' evaluates to: " << (a * b) << endl;
    cout << "Expression 'a > b' evaluates to: " << (a > b) << endl;
    cout << "Expression 'a == 5' evaluates to: " << (a == 5) << endl;
    
    // Ternary expression
    cout << "Expression 'a > b ? a : b' evaluates to: " << (a > b ? a : b) << endl;
    
    // STATEMENTS - complete instructions
    
    // Declaration statement
    int x = 10;
    
    // Expression statement (expression + semicolon)
    x = x + 5;  // Assignment statement
    
    // Compound statement (block)
    {
        int temp = x;
        x = x * 2;
        cout << "Inside block: x = " << x << endl;
    }
    
    // Null statement
    ;  // Does nothing, but is valid
    
    // Control statements are covered in Control Flow lesson
    cout << "Final x value: " << x << endl;
}

// ============================================================
// EXAMPLE 5: Blocks and Scope
// ============================================================
void example5_scope() {
    cout << "\n=== EXAMPLE 5: Blocks and Scope ===" << endl;
    
    // Outer scope
    int outer = 100;
    cout << "Outer scope - outer: " << outer << endl;
    
    {
        // Inner block 1
        int inner = 200;
        cout << "Inner block - outer: " << outer << ", inner: " << inner << endl;
        
        {
            // Nested block
            int nested = 300;
            cout << "Nested block - outer: " << outer 
                 << ", inner: " << inner 
                 << ", nested: " << nested << endl;
        }
        // 'nested' is no longer accessible here
    }
    // 'inner' is no longer accessible here
    
    cout << "Back to outer scope - outer: " << outer << endl;
    
    // Variable shadowing
    int value = 1;
    cout << "\nShadowing demo:" << endl;
    cout << "Outer value: " << value << endl;
    
    {
        int value = 2;  // Shadows outer 'value'
        cout << "Inner value: " << value << endl;
        
        {
            int value = 3;  // Shadows both
            cout << "Nested value: " << value << endl;
        }
        cout << "Back to inner: " << value << endl;
    }
    cout << "Back to outer: " << value << endl;
    
    // Accessing global with scope resolution operator
    cout << "\nGlobal counter (using ::): " << ::globalCounter << endl;
}

// ============================================================
// EXAMPLE 6: Code Formatting Styles
// ============================================================
void example6_formatting() {
    cout << "\n=== EXAMPLE 6: Code Formatting Styles ===" << endl;
    
    int x = 10;
    
    // K&R / One True Brace Style
    if (x > 5) {
        cout << "K&R style: x is greater than 5" << endl;
    } else {
        cout << "K&R style: x is not greater than 5" << endl;
    }
    
    // Note: We'll use K&R style throughout this course
    // because it's compact and widely used
    
    // Proper spacing around operators
    int a = 5 + 3;          // Good: spaces around +
    int b = 10 * 2;         // Good: spaces around *
    bool c = (a == b);      // Good: spaces around ==
    
    // Consistent indentation (4 spaces)
    for (int i = 0; i < 3; i++) {
        cout << "    Indentation matters for readability!" << endl;
        if (i == 1) {
            cout << "        Nested indentation" << endl;
        }
    }
    
    cout << "See source code for formatting examples!" << endl;
}

// ============================================================
// EXAMPLE 7: Main Function Variations
// ============================================================
// Note: We can't have multiple main() functions, so we'll
// demonstrate the concepts through comments and explanation

void example7_main_function() {
    cout << "\n=== EXAMPLE 7: Main Function Variations ===" << endl;
    
    cout << "Valid main() signatures:" << endl;
    cout << "  int main() { return 0; }" << endl;
    cout << "  int main(int argc, char* argv[]) { return 0; }" << endl;
    cout << "  int main(int argc, char** argv) { return 0; }" << endl;
    
    cout << "\nReturn values:" << endl;
    cout << "  return 0;            // Success" << endl;
    cout << "  return EXIT_SUCCESS; // Success (from <cstdlib>)" << endl;
    cout << "  return 1;            // Error" << endl;
    cout << "  return EXIT_FAILURE; // Error (from <cstdlib>)" << endl;
    
    cout << "\nCommand-line example:" << endl;
    cout << "  ./program arg1 arg2 arg3" << endl;
    cout << "  argc = 4 (program name + 3 args)" << endl;
    cout << "  argv[0] = \"./program\"" << endl;
    cout << "  argv[1] = \"arg1\"" << endl;
    cout << "  argv[2] = \"arg2\"" << endl;
    cout << "  argv[3] = \"arg3\"" << endl;
}

// ============================================================
// EXAMPLE 8: Forward Declarations and Definitions
// ============================================================

// Forward declaration (prototype) - already at top of file
// int factorial(int n);

void example8_declarations() {
    cout << "\n=== EXAMPLE 8: Declarations vs Definitions ===" << endl;
    
    // We can use factorial() here because it was declared above
    cout << "5! = " << factorial(5) << endl;
    cout << "7! = " << factorial(7) << endl;
    
    cout << "\nDeclaration: Tells compiler something exists" << endl;
    cout << "  int factorial(int n);  // Declaration" << endl;
    cout << "\nDefinition: Actually creates/implements it" << endl;
    cout << "  int factorial(int n) { ... }  // Definition" << endl;
}

// Definition of factorial (implementation)
int factorial(int n) {
    if (n <= 1) return 1;
    return n * factorial(n - 1);
}

// ============================================================
// EXAMPLE 9: Common Syntax Errors (Corrected)
// ============================================================
void example9_common_errors() {
    cout << "\n=== EXAMPLE 9: Common Syntax Errors ===" << endl;
    
    cout << "Common mistakes to avoid:\n" << endl;
    
    // 1. Missing semicolon
    cout << "1. Missing semicolon:" << endl;
    cout << "   Wrong: int x = 5" << endl;
    cout << "   Right: int x = 5;" << endl;
    
    // 2. Assignment vs Comparison
    cout << "\n2. Assignment (=) vs Comparison (==):" << endl;
    cout << "   Wrong: if (x = 5)   // Assigns 5 to x" << endl;
    cout << "   Right: if (x == 5)  // Compares x to 5" << endl;
    
    // 3. Case sensitivity
    cout << "\n3. Case sensitivity:" << endl;
    cout << "   Wrong: Int x = 5;   // 'Int' is not 'int'" << endl;
    cout << "   Right: int x = 5;" << endl;
    
    // 4. Mismatched braces
    cout << "\n4. Mismatched braces:" << endl;
    cout << "   Always match { with }" << endl;
    cout << "   Use editor features to help!" << endl;
    
    // 5. Using undeclared variables
    cout << "\n5. Using undeclared variables:" << endl;
    cout << "   Wrong: cout << value;  // Not declared" << endl;
    cout << "   Right: int value = 5; cout << value;" << endl;
    
    // 6. Wrong include
    cout << "\n6. Missing includes:" << endl;
    cout << "   Wrong: using cout without <iostream>" << endl;
    cout << "   Right: #include <iostream>" << endl;
}

// ============================================================
// EXAMPLE 10: Complete Program Structure Demo
// ============================================================
void example10_complete_structure() {
    cout << "\n=== EXAMPLE 10: Complete Program Structure ===" << endl;
    
    cout << "A complete C++ program structure:" << endl;
    cout << R"(
    // ===== PREPROCESSOR DIRECTIVES =====
    #include <iostream>
    #include <string>
    #define MAX_SIZE 100
    
    // ===== USING DECLARATIONS =====
    using namespace std;
    
    // ===== GLOBAL CONSTANTS =====
    const double PI = 3.14159;
    
    // ===== FORWARD DECLARATIONS =====
    void helperFunction();
    int calculate(int x, int y);
    
    // ===== CLASS DEFINITIONS =====
    class MyClass {
    public:
        void method();
    private:
        int data;
    };
    
    // ===== MAIN FUNCTION =====
    int main() {
        // Local variables
        int x = 10;
        
        // Function calls
        helperFunction();
        int result = calculate(5, 3);
        
        // Return success
        return 0;
    }
    
    // ===== FUNCTION DEFINITIONS =====
    void helperFunction() {
        cout << "Helper!" << endl;
    }
    
    int calculate(int x, int y) {
        return x + y;
    }
)" << endl;
}

// ============================================================
// MAIN FUNCTION
// ============================================================
int main() {
    cout << "╔══════════════════════════════════════════════════════╗" << endl;
    cout << "║     C++ Syntax and Structure - Examples              ║" << endl;
    cout << "║     Study these after reading README.md              ║" << endl;
    cout << "╚══════════════════════════════════════════════════════╝" << endl;
    
    example1_tokens();
    example2_number_literals();
    example3_identifiers();
    example4_statements_expressions();
    example5_scope();
    example6_formatting();
    example7_main_function();
    example8_declarations();
    example9_common_errors();
    example10_complete_structure();
    
    cout << "\n╔══════════════════════════════════════════════════════╗" << endl;
    cout << "║     All examples completed!                          ║" << endl;
    cout << "║     Now try the exercises in exercises.cpp           ║" << endl;
    cout << "╚══════════════════════════════════════════════════════╝" << endl;
    
    return 0;
}
Examples - C++ Tutorial | DeepML