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:
- Understand the 3 parts of a function: Prototype, Definition, and Call.
- Pass data using Call by Value and Call by Reference.
- Implement recursive functions for mathematical problems.
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.
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.
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
- Create separate functions for
add(),subtract(), andmultiply(). - Take two numbers and an operation choice from the user.
- Call the appropriate function based on the choice.
Step-by-Step Process
- Define function prototypes at the top.
- Use a
switchcase inmain()to handle user choice. - Write the logic for each operation in its respective function definition.
Expected Deliverables
calculator_functions.cppsource file.