C Workshop · Square Function
Lesson C

Square Function

Write square(n) that returns n*n, then print square of 5.

What it is

square(n) returns n times n. main calls square(5) and prints 25. The multiply lives in the helper so main stays a short story: ask, print, leave.

Approach

  1. Define int square(int n) { return n * n; }
  2. In main, printf the result of square(5).

Where this is used in the real world

Diagram

1

5

argument

2

square

n*n

3

25

return

4

print

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. Prints:

square(5).

2. The parameter n is:

Argument.

3. Could square be void?

Then main would not receive 25.

4. The call expression square(5) is replaced by:

Return value.

5. Recursive square does not make sense because:

No natural smaller square.