C++ and Mathematics
Functions and recursion
Defining and calling functions, pass by value vs by reference, recursion: factorial, Fibonacci, fast power, digit sum.
55 min 8 questions
01Functions
The mathematical function looks like this in C++: int f(int x) { return 2 * x + 1; }. f(f(3)) is exactly the composition .
Pass by value (int x): the function gets a copy and cannot change the caller's variable. Pass by reference (int &x): the function works on the original.
02Recursion
A recursive function calls itself — the code version of induction or a recurrence: , . A base case (e.g. ) is essential, otherwise the recursion never ends.
The naive fib(n) makes exponentially many calls because it recomputes the same values; with a loop or memoization it runs in linear time.
Fast power: for even and for odd — it takes about steps.
long long fact(int n) {
if (n <= 1) return 1; // base case
return n * fact(n - 1); // n! = n * (n-1)!
}Key formulas
Factorial recursion
Fibonacci numbers
Fast exponentiation
Worked examples
Example 1
How many calls does fact(5) make (including itself)?
fact(5) -> fact(4) -> fact(3) -> fact(2) -> fact(1)What does this code print?
#include <iostream>
using namespace std;
int f(int x) { return 2 * x + 1; }
int main() {
cout << f(f(3));
}Sample content: questions and lessons are illustrative and are not taken from official exams.
