C Workshop · Sum Two Numbers
Lesson C

Sum Two Numbers

Read two ints from input, add them, print the result.

What it is

This program reads two whole numbers, adds them, and prints the total. The new idea is scanf: it waits for you to type, then writes what you typed into a variable.

Approach

  1. Declare two ints.
  2. scanf each value (one per line in the sample).
  3. Print a + b with %d.

Where this is used in the real world

Diagram

1

stdin

user types 3 then 7

scanf waits until a number is available.
2

a = 3

first box fills

Need &a because scanf writes to the address.
3

b = 7

second box fills

Same idea for b.
4

a + b

expression 10

No extra variable required.
5

stdout

print 10

Format %d matches int.

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 main(void) {
3  int a, b;
4  scanf("%d", &a);
5  scanf("%d", &b);
6  printf("%d\n", a + b);
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. Why does scanf need &a?

Pass the address so scanf can store.

2. Sample 3 and 7 prints:

3+7=10.

3. scanf("%d", &a) reads:

One integer.

4. If you write scanf("%d", a) without & for an int:

Need & for scalars.

5. a + b is evaluated:

The expression runs, then prints.