⚡0 XP🔥0

Functions and Recursion

Lesson 7 of 13 ⏱ 6 min read ✎ 3 exercises ❓ 5-question quiz ▶ Runs C

Write your own functions - declaration, definition, parameters, return values, call by value, scope, static variables and recursion.

A function is a named block of code that does one job. You have already used functions: main, printf, scanf. Now you will write your own.

Why functions?

  • Reuse - write once, call many times.
  • Readability - calculateGST(price) explains itself.
  • Easier debugging - test each small piece separately.

Declaring, defining and calling#

int add(int a, int b);           // 1. declaration (prototype)

int main() {
    int s = add(3, 4);           // 3. call
}

int add(int a, int b) {          // 2. definition
    return a + b;
}
▶ Try it YourselfC
Ctrl + Enter to run
Output
12 + 30 = 42
Direct: 350
  • int before the name is the return type.
  • a and b are parameters; x and y (or 100, 250) are the arguments passed in.
  • return sends a value back to the caller and ends the function.
Note

If you define the function above main, you do not need a separate prototype. In bigger programs, prototypes go in header (.h) files.

void functions and functions without parameters#

▶ Try it YourselfC
Ctrl + Enter to run
Output
========================
Welcome to Vindhyaedu!
------------------------

Call by value#

C passes copies of the arguments. The function can change its copy, but the original stays the same:

▶ Try it YourselfC
Ctrl + Enter to run
Output
Inside function: n = 80
In main: marks = 40
हिंदी में समझें

C में function को variable की copy मिलती है (call by value)। Function के अंदर बदलाव करने से main वाला असली variable नहीं बदलता। असली variable बदलना हो तो उसका address (pointer) भेजना पड़ता है - यह हम Pointers वाले lesson में सीखेंगे।

Scope: local and global variables#

  • A local variable is declared inside a function or block and exists only there.
  • A global variable is declared outside all functions and can be used everywhere (use sparingly).
  • A static local variable keeps its value between calls.
▶ Try it YourselfC
Ctrl + Enter to run
Output
normal=1 kept=1
normal=1 kept=2
normal=1 kept=3
totalCalls=3

Recursion#

A recursive function calls itself. Every recursive solution needs:

  1. a base case - a simple input answered directly (it stops the recursion), and
  2. a recursive case - which calls the function on a smaller problem.
▶ Try it YourselfC
Ctrl + Enter to run
Output
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720

How factorial(4) is evaluated:

factorial(4) = 4 * factorial(3)
             = 4 * (3 * factorial(2))
             = 4 * (3 * (2 * factorial(1)))
             = 4 * (3 * (2 * 1))      ← base case reached, now multiply back up
             = 24

Each call waits on the call stack until the call below it returns.

▶ Try it YourselfC
Ctrl + Enter to run
Output
5... 4... 3... 2... 1... Go!
Sum of digits of 9075 = 21
Common Mistake

A recursive function without a correct base case calls itself until memory for the call stack runs out ("stack overflow" / segmentation fault). Also, simple recursive Fibonacci is very slow for big n because it recomputes the same values again and again - a loop is better there.

Library functions: math.h#

C's standard library has many ready-made functions. <math.h> gives sqrt, pow, fabs, ceil, floor, round, sin, cos, log...

▶ Try it YourselfC
Ctrl + Enter to run
Output
sqrt(144)   = 12.0
pow(2, 8)   = 256
ceil(4.2)   = 5
floor(4.8)  = 4
fabs(-7.5)  = 7.5
hypotenuse  = 5.00
Tip

On Linux, link the math library with -lm: gcc prog.c -o prog -lm. The online compiler already does this.

Summary#

  • A function has a return type, a name, parameters and a body; declare it with a prototype if it is defined after main.
  • Arguments are passed by value (copies).
  • Local variables live inside their block; static locals keep their value; globals are visible everywhere.
  • Recursion = base case + smaller recursive call.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Power function

Write long long power(int base, int exp) that returns base^exp using a loop (no pow). main reads base and exp and prints 2^10 = 1024. Test input 3 13.

Test input:
3 13
Expected output:
3^13 = 1594323
2

Recursive Fibonacci

Write a recursive function int fib(int n) where fib(0) = 0, fib(1) = 1 and fib(n) = fib(n-1) + fib(n-2). Print the first n Fibonacci numbers separated by spaces. Test input 10 → 0 1 1 2 3 5 8 13 21 34.

Test input:
10
Expected output:
0 1 1 2 3 5 8 13 21 34
3

GCD (Euclid)

Write a recursive int gcd(int a, int b) using Euclid's rule gcd(a, b) = gcd(b, a % b), with gcd(a, 0) = a. Print GCD = 6 for input 48 18. Test input 84 120.

Test input:
84 120
Expected output:
GCD = 12

Quick Quiz

Q1.

What is a function prototype?

Q2.

In C, arguments are passed to a function...

Q3.

What is the return type of a function that returns nothing?

Q4.

Every recursive function must have...

Q5.

A static local variable...