cpp

examples

examples.cpp⚙️
/**
 * Module 01: Foundations
 * Topic: Introduction to C++
 * File: examples.cpp
 * 
 * This file contains practical examples demonstrating concepts
 * from the README. Study these after reading the theory.
 * 
 * Compile: g++ -std=c++17 -Wall -Wextra examples.cpp -o examples
 * Run:     ./examples
 */

#include <iostream>
#include <string>

// Using the std namespace for cleaner code in examples
using namespace std;

// ============================================================
// EXAMPLE 1: The Classic Hello World
// ============================================================
void example1_hello_world() {
    cout << "\n=== EXAMPLE 1: Hello World ===" << endl;
    
    // The most basic C++ program output
    cout << "Hello, World!" << endl;
    
    // Multiple outputs can be chained
    cout << "Welcome " << "to " << "C++" << "!" << endl;
    
    // Using newline character instead of endl
    cout << "Line 1\nLine 2\nLine 3\n";
}

// ============================================================
// EXAMPLE 2: Different Ways to Output
// ============================================================
void example2_output_methods() {
    cout << "\n=== EXAMPLE 2: Output Methods ===" << endl;
    
    // Method 1: Using endl (flushes the buffer)
    cout << "Using endl" << endl;
    
    // Method 2: Using \n (doesn't flush - slightly faster)
    cout << "Using newline\n";
    
    // Method 3: Multiple items in one statement
    int age = 25;
    string name = "Alice";
    cout << "Name: " << name << ", Age: " << age << endl;
    
    // Method 4: Printing special characters
    cout << "Tab:\tafter tab" << endl;
    cout << "Quote: \"Hello\"" << endl;
    cout << "Backslash: \\" << endl;
}

// ============================================================
// EXAMPLE 3: Basic Input
// ============================================================
void example3_basic_input() {
    cout << "\n=== EXAMPLE 3: Basic Input ===" << endl;
    
    // Note: In this demo, we'll use hardcoded values
    // to make the examples runnable without interaction
    
    // How you would normally get input:
    /*
    int number;
    cout << "Enter a number: ";
    cin >> number;
    cout << "You entered: " << number << endl;
    */
    
    // Demo with preset value
    int number = 42;
    cout << "Demo number: " << number << endl;
    
    string name = "Bob";
    cout << "Demo name: " << name << endl;
}

// ============================================================
// EXAMPLE 4: Program Structure Elements
// ============================================================

// Global constant (visible everywhere)
const double PI = 3.14159265359;

// Function declaration (prototype)
double calculateCircleArea(double radius);

void example4_program_structure() {
    cout << "\n=== EXAMPLE 4: Program Structure ===" << endl;
    
    // Local variable (only visible in this function)
    double radius = 5.0;
    
    // Using the global constant and calling a function
    double area = calculateCircleArea(radius);
    
    cout << "Circle with radius " << radius << endl;
    cout << "Area = " << area << endl;
}

// Function definition (implementation)
double calculateCircleArea(double radius) {
    return PI * radius * radius;
}

// ============================================================
// EXAMPLE 5: Comments in Practice
// ============================================================
void example5_comments() {
    cout << "\n=== EXAMPLE 5: Comments in Practice ===" << endl;
    
    // Single-line comment: Good for brief explanations
    int count = 10;  // Initialize counter to 10
    
    /* 
     * Multi-line comment: Good for longer explanations
     * or temporarily disabling code blocks.
     * 
     * This style is common for documentation.
     */
    
    /**
     * Documentation comment style (Doxygen compatible)
     * @brief Describes what something does
     * @param parameter_name Description of parameter
     * @return Description of return value
     */
    
    // TODO: Comments can mark work to be done
    // FIXME: Comments can mark bugs to fix
    // NOTE: Comments can highlight important info
    
    cout << "Count value: " << count << endl;
    cout << "See source code for comment examples!" << endl;
}

// ============================================================
// EXAMPLE 6: Namespaces
// ============================================================

// Custom namespace example
namespace MyMath {
    const double E = 2.71828;
    
    double square(double x) {
        return x * x;
    }
}

namespace Physics {
    const double SPEED_OF_LIGHT = 299792458.0;  // m/s
    const double GRAVITY = 9.81;                 // m/s²
}

void example6_namespaces() {
    cout << "\n=== EXAMPLE 6: Namespaces ===" << endl;
    
    // Accessing namespace members with ::
    cout << "Euler's number: " << MyMath::E << endl;
    cout << "5 squared: " << MyMath::square(5) << endl;
    
    cout << "Speed of light: " << Physics::SPEED_OF_LIGHT << " m/s" << endl;
    cout << "Gravity: " << Physics::GRAVITY << " m/s²" << endl;
    
    // Using declaration - bring specific item into scope
    using MyMath::square;
    cout << "7 squared: " << square(7) << endl;
}

// ============================================================
// EXAMPLE 7: Return Values from Main
// ============================================================
void example7_return_values() {
    cout << "\n=== EXAMPLE 7: Return Values ===" << endl;
    
    cout << "In C++, main() returns an int:" << endl;
    cout << "  return 0;  -> Success" << endl;
    cout << "  return 1;  -> General error" << endl;
    cout << "  return N;  -> Specific error code" << endl;
    cout << endl;
    cout << "The shell can check this with: echo $?" << endl;
    cout << "This program will return 0 (success)" << endl;
}

// ============================================================
// EXAMPLE 8: Preprocessor Directives
// ============================================================

// Define a constant using preprocessor
#define MAX_STUDENTS 100

// Conditional compilation
#define DEBUG_MODE 1

void example8_preprocessor() {
    cout << "\n=== EXAMPLE 8: Preprocessor Directives ===" << endl;
    
    cout << "MAX_STUDENTS defined as: " << MAX_STUDENTS << endl;
    
    #if DEBUG_MODE
        cout << "Debug mode is ON" << endl;
        cout << "Extra debug info would appear here" << endl;
    #else
        cout << "Debug mode is OFF" << endl;
    #endif
    
    // Preprocessor stringification
    #define STRINGIFY(x) #x
    cout << "Stringified: " << STRINGIFY(Hello World) << endl;
}

// ============================================================
// EXAMPLE 9: Basic Types Preview
// ============================================================
void example9_types_preview() {
    cout << "\n=== EXAMPLE 9: Basic Types Preview ===" << endl;
    
    // Integer types
    int wholeNumber = 42;
    
    // Floating-point types
    double decimal = 3.14159;
    
    // Character type
    char letter = 'A';
    
    // Boolean type
    bool isTrue = true;
    
    // String type (from <string> header)
    string text = "Hello";
    
    cout << "int:    " << wholeNumber << endl;
    cout << "double: " << decimal << endl;
    cout << "char:   " << letter << endl;
    cout << "bool:   " << isTrue << " (1 = true)" << endl;
    cout << "string: " << text << endl;
    
    cout << "\n(Types are covered in detail in the Variables lesson)" << endl;
}

// ============================================================
// EXAMPLE 10: Compilation Stages Demo
// ============================================================
void example10_compilation_info() {
    cout << "\n=== EXAMPLE 10: Compilation Information ===" << endl;
    
    // Predefined macros give compilation info
    cout << "This file: " << __FILE__ << endl;
    cout << "Current line: " << __LINE__ << endl;
    cout << "Compiled on: " << __DATE__ << " at " << __TIME__ << endl;
    
    // C++ version check
    #if __cplusplus >= 202002L
        cout << "C++ Standard: C++20 or later" << endl;
    #elif __cplusplus >= 201703L
        cout << "C++ Standard: C++17" << endl;
    #elif __cplusplus >= 201402L
        cout << "C++ Standard: C++14" << endl;
    #elif __cplusplus >= 201103L
        cout << "C++ Standard: C++11" << endl;
    #else
        cout << "C++ Standard: Pre-C++11" << endl;
    #endif
    
    cout << "__cplusplus value: " << __cplusplus << endl;
}

// ============================================================
// MAIN FUNCTION - Entry Point
// ============================================================
int main() {
    cout << "╔══════════════════════════════════════════════════════╗" << endl;
    cout << "║     C++ Introduction - Code Examples                 ║" << endl;
    cout << "║     Study these after reading README.md              ║" << endl;
    cout << "╚══════════════════════════════════════════════════════╝" << endl;
    
    // Run all examples
    example1_hello_world();
    example2_output_methods();
    example3_basic_input();
    example4_program_structure();
    example5_comments();
    example6_namespaces();
    example7_return_values();
    example8_preprocessor();
    example9_types_preview();
    example10_compilation_info();
    
    cout << "\n╔══════════════════════════════════════════════════════╗" << endl;
    cout << "║     All examples completed successfully!             ║" << endl;
    cout << "║     Now try the exercises in exercises.cpp           ║" << endl;
    cout << "╚══════════════════════════════════════════════════════╝" << endl;
    
    return 0;  // Success
}
Examples - C++ Tutorial | DeepML