Why Functions?

  • Name a task; hide its steps.
  • Reuse without copy–paste.
  • Test in isolation.
  • Enable teamwork via clear interfaces.

Value vs Reference

void inc(int n){ n++; }
int x=5; inc(x); // x ?
void inc(int& n){ n++; }
int x=5; inc(x); // x ?

Recursion (Factorial)

int fact(int n){
    if(n==0) return 1;
    return n*fact(n-1);
}

Step through the call stack (n=4):

[empty]

Mini‑Quiz (1 minute)

Q1. What does pass‑by‑value do?



Boss Battle: Fibonacci

long long fib_rec(int n){ return n<2? n : fib_rec(n-1)+fib_rec(n-2); }
long long fib_it (int n){ long long a=0,b=1; while(n--){ long long t=a+b; a=b; b=t;} return a; }

(JS simulates timing to contrast exponential vs linear ideas.)

When you replace copy–paste with a function…

function meme

Abstraction: fewer moving parts to break.

Summary

  • Functions provide names, contracts, and reuse.
  • Prefer `const&` for large inputs; return results, not side‑effects.
  • Overload prudently; keep interfaces minimal.
  • Recursion needs a base case; iterative alternatives often cheaper.
  • Lambdas enable on‑the‑spot behavior.