cpp

examples

examples.cpp⚙️
/**
 * C++ Function Basics - Comprehensive Examples
 * 
 * This file demonstrates fundamental concepts of functions in C++:
 * - Function declaration and definition
 * - Return types and void functions
 * - Parameters and arguments
 * - Function scope and lifetime
 * - Default arguments
 * - Function organization
 * 
 * Compile: g++ -std=c++17 -Wall -Wextra examples.cpp -o examples
 * Run: ./examples
 */

#include <iostream>
#include <string>
#include <vector>
#include <cmath>

using namespace std;

// ============================================================
// SECTION 1: FUNCTION DECLARATIONS (PROTOTYPES)
// ============================================================
// Forward declarations - functions defined later

// Basic function declarations
int add(int a, int b);
double multiply(double x, double y);
void printGreeting();
void printMessage(string message);

// Declarations with and without parameter names
int subtract(int, int);               // Without parameter names (valid but less clear)
int divide(int dividend, int divisor); // With parameter names (preferred)

// ============================================================
// SECTION 2: BASIC FUNCTION DEFINITIONS
// ============================================================

/**
 * Adds two integers together.
 * @param a First integer
 * @param b Second integer
 * @return Sum of a and b
 */
int add(int a, int b) {
    return a + b;
}

/**
 * Multiplies two floating-point numbers.
 */
double multiply(double x, double y) {
    return x * y;
}

/**
 * Subtracts second number from first.
 */
int subtract(int a, int b) {
    return a - b;
}

/**
 * Divides dividend by divisor.
 * Note: Returns 0 if divisor is zero (simplified error handling).
 */
int divide(int dividend, int divisor) {
    if (divisor == 0) {
        cerr << "Warning: Division by zero!" << endl;
        return 0;
    }
    return dividend / divisor;
}

// ============================================================
// SECTION 3: VOID FUNCTIONS
// ============================================================

/**
 * Prints a simple greeting - no parameters, no return value.
 */
void printGreeting() {
    cout << "Hello, World!" << endl;
    // No return statement needed for void functions
}

/**
 * Prints a custom message.
 */
void printMessage(string message) {
    cout << message << endl;
}

/**
 * Prints a horizontal separator line.
 */
void printSeparator(char c = '-', int length = 40) {
    for (int i = 0; i < length; i++) {
        cout << c;
    }
    cout << endl;
}

/**
 * Demonstrates early return in void function.
 */
void printPositiveOnly(int value) {
    if (value <= 0) {
        cout << "Value must be positive!" << endl;
        return;  // Early exit
    }
    cout << "Positive value: " << value << endl;
}

// ============================================================
// SECTION 4: RETURN TYPES
// ============================================================

// Integer return
int getMaxValue() {
    return 2147483647;  // INT_MAX
}

// Double return
double calculateCircleArea(double radius) {
    const double PI = 3.14159265359;
    return PI * radius * radius;
}

// Boolean return (predicate function)
bool isEven(int number) {
    return number % 2 == 0;
}

bool isPrime(int n) {
    if (n <= 1) return false;
    if (n <= 3) return true;
    if (n % 2 == 0 || n % 3 == 0) return false;
    for (int i = 5; i * i <= n; i += 6) {
        if (n % i == 0 || n % (i + 2) == 0) {
            return false;
        }
    }
    return true;
}

// String return
string getGreeting(string name) {
    return "Hello, " + name + "!";
}

// Returning objects
vector<int> getEvenNumbersUpTo(int max) {
    vector<int> evens;
    for (int i = 2; i <= max; i += 2) {
        evens.push_back(i);
    }
    return evens;  // Return by value (copy or move)
}

// ============================================================
// SECTION 5: auto RETURN TYPE (C++14)
// ============================================================

auto addAuto(int a, int b) {
    return a + b;  // Deduced as int
}

auto divideAuto(double a, double b) {
    return a / b;  // Deduced as double
}

auto getFullName(string first, string last) {
    return first + " " + last;  // Deduced as string
}

// Trailing return type (C++11)
auto computeProduct(int a, double b) -> double {
    return a * b;
}

// ============================================================
// SECTION 6: FUNCTION SCOPE
// ============================================================

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

void demonstrateScope() {
    // Local variable - only visible in this function
    int localVar = 100;
    cout << "Local variable: " << localVar << endl;
    cout << "Global counter: " << globalCounter << endl;
    
    // Block scope
    {
        int blockVar = 50;
        cout << "Block variable: " << blockVar << endl;
        // localVar still accessible here
        cout << "Local in block: " << localVar << endl;
    }
    // blockVar not accessible here
    
    globalCounter++;  // Modify global
}

// Static local variable - persists between calls
void functionWithStatic() {
    static int callCount = 0;  // Initialized only once
    callCount++;
    cout << "This function has been called " << callCount << " time(s)" << endl;
}

// ============================================================
// SECTION 7: DEFAULT ARGUMENTS
// ============================================================

/**
 * Creates a greeting message with optional customization.
 */
void greetPerson(string name = "Guest", string greeting = "Hello", int times = 1) {
    for (int i = 0; i < times; i++) {
        cout << greeting << ", " << name << "!" << endl;
    }
}

/**
 * Calculates power with default exponent of 2 (square).
 */
double power(double base, int exponent = 2) {
    return pow(base, exponent);
}

/**
 * Formats a price with optional currency symbol and decimal places.
 */
string formatPrice(double amount, string currency = "$", int decimals = 2) {
    string result = currency;
    
    // Simple formatting (for demonstration)
    int whole = static_cast<int>(amount);
    int fraction = static_cast<int>((amount - whole) * pow(10, decimals)) % 
                   static_cast<int>(pow(10, decimals));
    
    result += to_string(whole) + ".";
    
    // Pad with zeros
    string fracStr = to_string(fraction);
    while (fracStr.length() < static_cast<size_t>(decimals)) {
        fracStr = "0" + fracStr;
    }
    result += fracStr;
    
    return result;
}

// ============================================================
// SECTION 8: MULTIPLE RETURN VALUES (using pair/tuple/struct)
// ============================================================

#include <tuple>
#include <utility>

// Using pair
pair<int, int> getMinMax(const vector<int>& numbers) {
    if (numbers.empty()) {
        return {0, 0};
    }
    
    int minVal = numbers[0];
    int maxVal = numbers[0];
    
    for (int n : numbers) {
        if (n < minVal) minVal = n;
        if (n > maxVal) maxVal = n;
    }
    
    return {minVal, maxVal};
}

// Using tuple
tuple<double, double, double> getStatistics(const vector<int>& numbers) {
    if (numbers.empty()) {
        return {0.0, 0.0, 0.0};
    }
    
    double sum = 0;
    int minVal = numbers[0];
    int maxVal = numbers[0];
    
    for (int n : numbers) {
        sum += n;
        if (n < minVal) minVal = n;
        if (n > maxVal) maxVal = n;
    }
    
    double avg = sum / numbers.size();
    return {avg, static_cast<double>(minVal), static_cast<double>(maxVal)};
}

// Using struct (cleaner for complex returns)
struct DivisionResult {
    int quotient;
    int remainder;
    bool success;
};

DivisionResult safeDivide(int a, int b) {
    if (b == 0) {
        return {0, 0, false};
    }
    return {a / b, a % b, true};
}

// ============================================================
// SECTION 9: FUNCTION EXAMPLES - PRACTICAL USE CASES
// ============================================================

/**
 * Calculates factorial of n.
 */
long long factorial(int n) {
    if (n < 0) return -1;  // Error case
    if (n <= 1) return 1;
    
    long long result = 1;
    for (int i = 2; i <= n; i++) {
        result *= i;
    }
    return result;
}

/**
 * Calculates Fibonacci number at position n.
 */
long long fibonacci(int n) {
    if (n <= 0) return 0;
    if (n == 1) return 1;
    
    long long prev2 = 0, prev1 = 1;
    for (int i = 2; i <= n; i++) {
        long long current = prev1 + prev2;
        prev2 = prev1;
        prev1 = current;
    }
    return prev1;
}

/**
 * Checks if a string is a palindrome.
 */
bool isPalindrome(string str) {
    int left = 0;
    int right = str.length() - 1;
    
    while (left < right) {
        if (str[left] != str[right]) {
            return false;
        }
        left++;
        right--;
    }
    return true;
}

/**
 * Reverses a string.
 */
string reverseString(string str) {
    int left = 0;
    int right = str.length() - 1;
    
    while (left < right) {
        swap(str[left], str[right]);
        left++;
        right--;
    }
    return str;
}

/**
 * Counts occurrences of a character in a string.
 */
int countChar(const string& str, char target) {
    int count = 0;
    for (char c : str) {
        if (c == target) {
            count++;
        }
    }
    return count;
}

// ============================================================
// DEMONSTRATION FUNCTIONS
// ============================================================

void demonstrateBasicFunctions() {
    cout << "\n╔══════════════════════════════════════════════════════════════╗" << endl;
    cout << "║           SECTION 1: Basic Function Calls                    ║" << endl;
    cout << "╚══════════════════════════════════════════════════════════════╝" << endl;
    
    // Calling basic functions
    cout << "\nArithmetic Operations:" << endl;
    cout << "  add(5, 3) = " << add(5, 3) << endl;
    cout << "  subtract(10, 4) = " << subtract(10, 4) << endl;
    cout << "  multiply(3.5, 2.0) = " << multiply(3.5, 2.0) << endl;
    cout << "  divide(17, 5) = " << divide(17, 5) << endl;
    
    // Nested function calls
    cout << "\nNested calls:" << endl;
    cout << "  add(multiply(2, 3), 4) = " << add(multiply(2, 3), 4) << endl;
}

void demonstrateVoidFunctions() {
    cout << "\n╔══════════════════════════════════════════════════════════════╗" << endl;
    cout << "║           SECTION 2: Void Functions                          ║" << endl;
    cout << "╚══════════════════════════════════════════════════════════════╝" << endl;
    
    printGreeting();
    printMessage("This is a custom message.");
    
    cout << "\nDifferent separators:" << endl;
    printSeparator();           // Default: ----- (40)
    printSeparator('=', 30);    // Custom: ===== (30)
    printSeparator('*');        // Custom char, default length
    
    cout << "\nEarly return demonstration:" << endl;
    printPositiveOnly(10);
    printPositiveOnly(-5);
}

void demonstrateReturnTypes() {
    cout << "\n╔══════════════════════════════════════════════════════════════╗" << endl;
    cout << "║           SECTION 3: Return Types                            ║" << endl;
    cout << "╚══════════════════════════════════════════════════════════════╝" << endl;
    
    cout << "\nDifferent return types:" << endl;
    cout << "  getMaxValue() = " << getMaxValue() << endl;
    cout << "  calculateCircleArea(5.0) = " << calculateCircleArea(5.0) << endl;
    cout << "  isEven(7) = " << boolalpha << isEven(7) << endl;
    cout << "  isPrime(17) = " << isPrime(17) << endl;
    cout << "  getGreeting(\"Alice\") = " << getGreeting("Alice") << endl;
    
    cout << "\nReturning vectors:" << endl;
    vector<int> evens = getEvenNumbersUpTo(10);
    cout << "  Even numbers up to 10: ";
    for (int n : evens) {
        cout << n << " ";
    }
    cout << endl;
    
    cout << "\nauto return type (C++14):" << endl;
    cout << "  addAuto(10, 20) = " << addAuto(10, 20) << endl;
    cout << "  divideAuto(15.0, 4.0) = " << divideAuto(15.0, 4.0) << endl;
    cout << "  getFullName(\"John\", \"Doe\") = " << getFullName("John", "Doe") << endl;
}

// ⚠️ LEARNING NOTE: This function was originally named 'demonstrateScope()'
// but that name was already used at line 192!
// ERROR: You can't have two functions with the same name AND same parameters.
// This is a REDEFINITION ERROR.
// FIX: Rename one of them to be unique.
void runScopeDemo() {
    cout << "\n╔══════════════════════════════════════════════════════════════╗" << endl;
    cout << "║           SECTION 4: Function Scope                          ║" << endl;
    cout << "╚══════════════════════════════════════════════════════════════╝" << endl;
    
    cout << "\nDemonstrating local and global scope:" << endl;
    cout << "Global counter before: " << globalCounter << endl;
    demonstrateScope();
    demonstrateScope();
    cout << "Global counter after: " << globalCounter << endl;
    
    cout << "\nStatic variable demonstration:" << endl;
    for (int i = 0; i < 3; i++) {
        functionWithStatic();
    }
}

void demonstrateDefaultArguments() {
    cout << "\n╔══════════════════════════════════════════════════════════════╗" << endl;
    cout << "║           SECTION 5: Default Arguments                       ║" << endl;
    cout << "╚══════════════════════════════════════════════════════════════╝" << endl;
    
    cout << "\nUsing default arguments:" << endl;
    cout << "greetPerson():" << endl;
    greetPerson();  // Uses all defaults
    
    cout << "\ngreetPerson(\"Alice\"):" << endl;
    greetPerson("Alice");  // Uses default greeting and times
    
    cout << "\ngreetPerson(\"Bob\", \"Welcome\"):" << endl;
    greetPerson("Bob", "Welcome");  // Uses default times
    
    cout << "\ngreetPerson(\"Charlie\", \"Hi\", 2):" << endl;
    greetPerson("Charlie", "Hi", 2);  // No defaults
    
    cout << "\nPower function with default exponent:" << endl;
    cout << "  power(5) = " << power(5) << " (default exponent 2)" << endl;
    cout << "  power(2, 10) = " << power(2, 10) << endl;
    
    cout << "\nPrice formatting:" << endl;
    cout << "  formatPrice(99.95) = " << formatPrice(99.95) << endl;
    cout << "  formatPrice(50.5, \"€\") = " << formatPrice(50.5, "€") << endl;
    cout << "  formatPrice(123.456, \"£\", 3) = " << formatPrice(123.456, "£", 3) << endl;
}

void demonstrateMultipleReturns() {
    cout << "\n╔══════════════════════════════════════════════════════════════╗" << endl;
    cout << "║           SECTION 6: Multiple Return Values                  ║" << endl;
    cout << "╚══════════════════════════════════════════════════════════════╝" << endl;
    
    vector<int> numbers = {3, 7, 2, 9, 1, 8, 4, 6, 5};
    
    // Using pair
    cout << "\nUsing std::pair:" << endl;
    auto [minVal, maxVal] = getMinMax(numbers);  // Structured binding (C++17)
    cout << "  Min: " << minVal << ", Max: " << maxVal << endl;
    
    // Using tuple
    cout << "\nUsing std::tuple:" << endl;
    auto [avg, minV, maxV] = getStatistics(numbers);
    cout << "  Average: " << avg << ", Min: " << minV << ", Max: " << maxV << endl;
    
    // Using struct
    cout << "\nUsing struct:" << endl;
    DivisionResult result1 = safeDivide(17, 5);
    if (result1.success) {
        cout << "  17 / 5 = " << result1.quotient << " remainder " << result1.remainder << endl;
    }
    
    DivisionResult result2 = safeDivide(10, 0);
    if (!result2.success) {
        cout << "  10 / 0 = Division failed (division by zero)" << endl;
    }
}

void demonstratePracticalFunctions() {
    cout << "\n╔══════════════════════════════════════════════════════════════╗" << endl;
    cout << "║           SECTION 7: Practical Function Examples             ║" << endl;
    cout << "╚══════════════════════════════════════════════════════════════╝" << endl;
    
    cout << "\nFactorial:" << endl;
    for (int i = 0; i <= 10; i++) {
        cout << "  " << i << "! = " << factorial(i) << endl;
    }
    
    cout << "\nFibonacci sequence (first 15):" << endl;
    cout << "  ";
    for (int i = 0; i < 15; i++) {
        cout << fibonacci(i) << " ";
    }
    cout << endl;
    
    cout << "\nPrime numbers up to 50:" << endl;
    cout << "  ";
    for (int i = 2; i <= 50; i++) {
        if (isPrime(i)) {
            cout << i << " ";
        }
    }
    cout << endl;
    
    cout << "\nString operations:" << endl;
    cout << "  isPalindrome(\"radar\") = " << boolalpha << isPalindrome("radar") << endl;
    cout << "  isPalindrome(\"hello\") = " << isPalindrome("hello") << endl;
    cout << "  reverseString(\"hello\") = " << reverseString("hello") << endl;
    cout << "  countChar(\"mississippi\", 's') = " << countChar("mississippi", 's') << endl;
}

// ============================================================
// MAIN FUNCTION
// ============================================================

int main() {
    cout << "╔════════════════════════════════════════════════════════════════════╗" << endl;
    cout << "║                   C++ FUNCTION BASICS EXAMPLES                     ║" << endl;
    cout << "║               Comprehensive Demonstration of Functions             ║" << endl;
    cout << "╚════════════════════════════════════════════════════════════════════╝" << endl;
    
    demonstrateBasicFunctions();
    demonstrateVoidFunctions();
    demonstrateReturnTypes();
    demonstrateScope();
    demonstrateDefaultArguments();
    demonstrateMultipleReturns();
    demonstratePracticalFunctions();
    
    cout << "\n╔════════════════════════════════════════════════════════════════════╗" << endl;
    cout << "║                       Examples Complete!                           ║" << endl;
    cout << "║      Review the code to understand function concepts in C++        ║" << endl;
    cout << "╚════════════════════════════════════════════════════════════════════╝" << endl;
    
    return 0;
}
Examples - C++ Tutorial | DeepML