AlgoDaily

Functions And Recursion

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

Why Functions Matter

From control flow to reusable ideas

In Operators, Conditions, and Loops, you learned how programs make decisions and repeat work. Now we're ready to package that work into functions.

A function is a named block of code that can:

  • Take inputs
  • Perform one focused task
  • Return a result
  • Be reused from many places

If variables are named memory, functions are named behavior.

For a web developer, this should feel familiar: just like JavaScript functions help organize UI logic or API calls, C++ functions help organize fast, predictable computation — from finance calculations to AI model utilities.

Why Functions Matter

Define And Call

Function shape in C++

A basic C++ function has this structure:

return_type function_name(parameter_list) {
    // work
    return value;
}

Then you call the function by writing its name with arguments.

Important vocabulary:

  • Parameter: the variable listed in the function definition
  • Argument: the actual value passed during a call
  • Return type: the type of value the function sends back

C++ cares about types, so the return type and parameter types are part of the function's contract.

```cpp
#include <iostream>
using namespace std;

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

void printWelcome() {
    cout << "Welcome to function-powered C++!" << endl;
}

int main() {
    printWelcome();

    int result = add(7, 5);
    cout << "7 + 5 = " << result << endl;

    return 0;
}
```

Parameter Or Argument

In the function call below, what is 42?

analyzeScore(42);

Inputs And Results

Functions as tiny machines

Think of a function as a small machine with a contract:

inputs -> function -> output

For example, a finance calculation might accept a principal amount, an interest rate, and a number of years, then return the projected value.

This keeps main() readable. Instead of mixing every formula into one long program, we give the calculation a meaningful name.

```cpp
#include <iostream>
using namespace std;

double futureValue(double principal, double annualRate, int years) {
    double value = principal;

    for (int year = 1; year <= years; year++) {
        value = value * (1 + annualRate);
    }

    return value;
}

int main() {
    double startingAmount = 1000.0;
    double rate = 0.06;
    int years = 5;

    double projected = futureValue(startingAmount, rate, years);

    cout << "Projected value: $" << projected << endl;
    return 0;
}
```

Fill The Keyword

Fill in the blank:

A non-void C++ function sends a value back to the caller using the keyword ____.

Function Contracts

Good functions are focused

As programs grow, functions become your first serious tool for managing complexity.

A strong function usually has:

  • A clear name: calculateAverage, not doThing
  • A small purpose: one job, not ten
  • Predictable inputs and output
  • Minimal surprise for the caller

In C++, function declarations also help the compiler understand what exists before it sees the full function body.

// declaration / prototype
int square(int x);

// definition
int square(int x) {
    return x * x;
}

This matters because C++ is compiled ahead of time, as you saw in Introduction to C++.

Function Contracts

Recursion Starts Here

A function can call itself

Recursion is when a function solves a problem by calling itself on a smaller version of the same problem.

Every recursive solution needs two parts:

  1. Base case: when to stop
  2. Recursive case: how to reduce the problem

A classic example is factorial:

5! = 5 × 4 × 3 × 2 × 1

Recursive thinking says:

factorial(5) = 5 × factorial(4)
factorial(4) = 4 × factorial(3)
...
factorial(1) = 1

The key idea: each call makes the problem smaller until it reaches a simple answer.

Recursion Starts Here

Base Case Check

True or false?

A recursive function should have a base case so it eventually stops calling itself.

Recursive Factorial

Translating the idea to C++

Here is recursive factorial in C++.

Notice how directly the code mirrors the math:

factorial(n) = n × factorial(n - 1)

The if handles the base case. The return n * factorial(n - 1); line is the recursive case.

```cpp
#include <iostream>
using namespace std;

int factorial(int n) {
    if (n <= 1) {
        return 1;
    }

    return n * factorial(n - 1);
}

int main() {
    int n = 5;
    cout << n << "! = " << factorial(n) << endl;
    return 0;
}
```

Call Stack Mental Model

Recursion uses the call stack

Each function call gets its own temporary workspace. With recursion, many calls can be waiting at once.

For factorial(4), the calls build up like this:

factorial(4)
  waits for factorial(3)
    waits for factorial(2)
      waits for factorial(1)

Then results return upward:

factorial(1) -> 1
factorial(2) -> 2 * 1
factorial(3) -> 3 * 2
factorial(4) -> 4 * 6

This is powerful, but it has a cost: too many nested calls can exhaust stack memory. Later, when you learn more real-world C++, you'll often compare recursive and iterative versions for clarity and performance.

Call Stack Mental Model

Open interactive view →