C Workshop · Functions
Foundation C

Functions

A function is a named recipe: inputs go in, a result comes back. main calls it, then continues.

What it is

A function is a named recipe with inputs and (often) a result. main calls it, the recipe runs, a value comes back, and main continues. The call stack is just “who is waiting for whom.”

Approach

  1. Write the helper above main (or add a prototype).
  2. Call it with an argument.
  3. Use the returned value (here, print it).

Where this is used in the real world

Diagram

1

main

call square(5)

2

square

n*n

3

return 25

back to main

4

printf

25

Run algorithm

Each step highlights the matching C line. Program output appears only when a line that prints actually runs.

Ready
C code
1#include <stdio.h>
2int square(int n) {
3    return n * n;
4}
5int main(void) {
6    printf("%d\n", square(5));
7    return 0;
8}
What this line does
Press Run algorithm. The highlight will move through the C code.
Program output
(no output yet)

Check your understanding

Five questions. Pick one answer each, then Check answers. The correct choice turns green.

1. square(5) returns:

5*5.

2. After return, execution continues in:

Call then resume.

3. A void function:

void.

4. Why not put n*n only in main?

Decomposition.

5. A prototype is useful when:

Declare before call.