Chapter 4 — C++ Functions & Recursion

📚 Chapter Overview

Large programs are difficult to manage. Functions allow you to break code into small, reusable modules. In this chapter, you will learn how to define functions, pass data through parameters, and understand the concept of recursion.

Learning Objectives:

4.1 Function Basics

Part 1 — Definition

A Function is a block of code that performs a specific task. It runs only when it is called. Functions help in Code Reusability (write once, use many times) and make the program more modular and easier to debug.

Part 2 — Syntax

// 1. Prototype
void greet();

int main() {
    // 2. Call
    greet();
    return 0;
}

// 3. Definition
void greet() {
    cout << "Hello!";
}

Part 3 — Example

Problem: Create a function that calculates the sum of two numbers.

Main.cpp
int add(int a, int b) {
    return a + b;
}

int main() {
    int res = add(10, 20);
    cout << "Sum: " << res;
    return 0;
}

Output: Sum: 30

Part 4 — Video

Video: Coming Soon


4.2 Recursion

Part 1 — Definition

Recursion is the process in which a function calls itself directly or indirectly. It is used to solve problems that can be broken down into smaller, similar sub-problems (like Factorials or Fibonacci sequences). Every recursive function must have a Base Case to stop the recursion.

Part 2 — Syntax

void recurse() {
    if (base_condition) return;
    recurse(); // Self call
}

Part 3 — Example

Problem: Calculate the Factorial of a number using recursion.

Main.cpp
int fact(int n) {
    if (n <= 1) return 1; // Base case
    return n * fact(n - 1); // Recursive call
}

Observation: If you forget the base case, the program will crash with a "Stack Overflow" error.

Part 4 — Video

Video: Coming Soon


🏆 Chapter Challenge

Challenge Objective

Build a "Modular Calculator" that uses multiple functions for different operations.

Requirements

Step-by-Step Process

  1. Define function prototypes at the top.
  2. Use a switch case in main() to handle user choice.
  3. Write the logic for each operation in its respective function definition.

Expected Deliverables

Solve in Compiler