C Workshop · Max of Two
Lesson C

Max of Two

A helper can choose. Return the larger of two ints.

What it is

max2(a, b) returns whichever of two ints is larger. 3 and 9 go in, 9 comes out. Choosing is still a function — it just uses if instead of multiply.

Approach

  1. Define max2(a, b).
  2. Return a if a > b, else b.
  3. Print max2(3, 9).

Where this is used in the real world

Diagram

1

3

a

2

9

b

3

a>b?

no

4

return b

9

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 max2(int a, int b) {
3    if (a > b) return a;
4    return b;
5}
6int main(void) {
7    printf("%d\n", max2(3, 9));
8    return 0;
9}
What this line does
Press Run algorithm. The highlight will move through the C code.
True branch
the if body runs
False branch
else / skip
Program output
(no output yet)

Check your understanding

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

1. max2(3,9) is:

b is larger.

2. The false branch of a > b returns:

return b.

3. Ternary form is:

Same choose.

4. To max three numbers you could:

Compose helpers.

5. void max2 would be a problem if:

Need a return value.