cpp

Functions

03_Functions⚙️
/**
 * ============================================================
 * C++ FUNCTIONS - BASICS
 * ============================================================
 * 
 * This file covers:
 * - Function declaration and definition
 * - Function calling
 * - Return values
 * - Function parameters
 * - Scope and lifetime
 * 
 * Compile: g++ -std=c++17 -Wall 01_functions.cpp -o functions
 * Run: ./functions
 * 
 * ============================================================
 */

#include <iostream>
#include <string>

using namespace std;

// ============================================================
// FUNCTION DECLARATIONS (PROTOTYPES)
// ============================================================
// Declarations tell the compiler about the function's existence
// before its actual definition

void greet();                           // No parameters, no return
void greetPerson(string name);          // With parameter
int add(int a, int b);                  // Returns a value
double calculateArea(double radius);
void printLine(int length, char ch);
bool isEven(int number);
int factorial(int n);
void displayMenu();

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

int main() {
    cout << "============================================" << endl;
    cout << "     C++ FUNCTIONS - BASICS" << endl;
    cout << "============================================" << endl << endl;

    // ========================================================
    // PART 1: CALLING FUNCTIONS
    // ========================================================
    
    cout << "--- PART 1: CALLING FUNCTIONS ---" << endl << endl;
    
    // Call function with no parameters
    greet();
    
    // Call function with parameter
    greetPerson("Alice");
    greetPerson("Bob");
    
    // Call function that returns a value
    int sum = add(5, 3);
    cout << "add(5, 3) = " << sum << endl;
    
    // Use return value directly
    cout << "add(10, 20) = " << add(10, 20) << endl;
    
    // Chain function calls
    cout << "add(add(1,2), add(3,4)) = " << add(add(1,2), add(3,4)) << endl;
    
    cout << endl;

    // ========================================================
    // PART 2: RETURN VALUES
    // ========================================================
    
    cout << "--- PART 2: RETURN VALUES ---" << endl << endl;
    
    // Function returning double
    double area = calculateArea(5.0);
    cout << "Area of circle (r=5): " << area << endl;
    
    // Function returning bool
    cout << "Is 4 even? " << (isEven(4) ? "Yes" : "No") << endl;
    cout << "Is 7 even? " << (isEven(7) ? "Yes" : "No") << endl;
    
    // Using return value in conditions
    int num = 42;
    if (isEven(num)) {
        cout << num << " is even" << endl;
    }
    
    cout << endl;

    // ========================================================
    // PART 3: MULTIPLE PARAMETERS
    // ========================================================
    
    cout << "--- PART 3: MULTIPLE PARAMETERS ---" << endl << endl;
    
    // Function with multiple parameters
    printLine(20, '=');
    cout << "  Hello!  " << endl;
    printLine(20, '=');
    
    printLine(10, '-');
    
    cout << endl;

    // ========================================================
    // PART 4: VARIABLE SCOPE
    // ========================================================
    
    cout << "--- PART 4: VARIABLE SCOPE ---" << endl << endl;
    
    // Local variables are only visible within their function
    int x = 100;  // Local to main()
    
    cout << "x in main: " << x << endl;
    
    // Calling a function doesn't affect main's x
    // (unless passed by reference - covered later)
    
    // Block scope
    {
        int y = 50;  // Only visible in this block
        cout << "y in block: " << y << endl;
    }
    // cout << y;  // ERROR: y is not visible here
    
    cout << endl;

    // ========================================================
    // PART 5: FUNCTION EXAMPLES
    // ========================================================
    
    cout << "--- PART 5: PRACTICAL EXAMPLES ---" << endl << endl;
    
    // Calculate factorial
    cout << "Factorial of 5: " << factorial(5) << endl;
    cout << "Factorial of 0: " << factorial(0) << endl;
    cout << "Factorial of 10: " << factorial(10) << endl;
    
    // Menu display
    displayMenu();
    
    cout << endl;

    cout << "============================================" << endl;
    cout << "FUNCTION BASICS SUMMARY:" << endl;
    cout << "============================================" << endl;
    cout << "• Declaration: tells compiler about function" << endl;
    cout << "• Definition: provides the function body" << endl;
    cout << "• Return type: void, int, double, etc." << endl;
    cout << "• Parameters: inputs to the function" << endl;
    cout << "• Local scope: variables in function are local" << endl;
    cout << "============================================" << endl;

    return 0;
}

// ============================================================
// FUNCTION DEFINITIONS
// ============================================================

/*
 * Function: greet
 * Purpose: Displays a simple greeting
 * Parameters: None
 * Returns: Nothing (void)
 */
void greet() {
    cout << "Hello from greet()!" << endl;
}

/*
 * Function: greetPerson
 * Purpose: Greets a specific person
 * Parameters: name - the person's name
 * Returns: Nothing (void)
 */
void greetPerson(string name) {
    cout << "Hello, " << name << "!" << endl;
}

/*
 * Function: add
 * Purpose: Adds two integers
 * Parameters: a, b - numbers to add
 * Returns: Sum of a and b
 */
int add(int a, int b) {
    return a + b;
}

/*
 * Function: calculateArea
 * Purpose: Calculates area of a circle
 * Parameters: radius - radius of the circle
 * Returns: Area of the circle
 */
double calculateArea(double radius) {
    const double PI = 3.14159265359;
    return PI * radius * radius;
}

/*
 * Function: printLine
 * Purpose: Prints a line of characters
 * Parameters: 
 *   length - number of characters
 *   ch - character to print
 * Returns: Nothing (void)
 */
void printLine(int length, char ch) {
    for (int i = 0; i < length; i++) {
        cout << ch;
    }
    cout << endl;
}

/*
 * Function: isEven
 * Purpose: Checks if a number is even
 * Parameters: number - the number to check
 * Returns: true if even, false otherwise
 */
bool isEven(int number) {
    return number % 2 == 0;
}

/*
 * Function: factorial
 * Purpose: Calculates factorial of n
 * Parameters: n - non-negative integer
 * Returns: n! (n factorial)
 */
int factorial(int n) {
    if (n <= 1) {
        return 1;
    }
    
    int result = 1;
    for (int i = 2; i <= n; i++) {
        result *= i;
    }
    return result;
}

/*
 * Function: displayMenu
 * Purpose: Displays a sample menu
 * Parameters: None
 * Returns: Nothing (void)
 */
void displayMenu() {
    cout << "\n===== MENU =====" << endl;
    cout << "1. Option One" << endl;
    cout << "2. Option Two" << endl;
    cout << "3. Option Three" << endl;
    cout << "4. Exit" << endl;
    cout << "================" << endl;
}

// ============================================================
// EXERCISES:
// ============================================================
/*
 * 1. Write a function that returns the maximum of two numbers
 * 
 * 2. Write a function that checks if a number is prime
 * 
 * 3. Write a function that converts Fahrenheit to Celsius
 * 
 * 4. Write a function that counts digits in a number
 * 
 * 5. Write a function that prints a triangle pattern
 */
Functions - C++ Tutorial | DeepML