Skip to content
Devtoolry

Basics · beginner

C Program to Add Two Numbers

Add two numbers in C with scanf() and printf(), check that scanf() really read them, and use double for decimals and long long for big integers.

Adding two numbers is the classic first C program after "Hello, World". It introduces the two functions every beginner uses: scanf() to read input and printf() to print it, each with format specifiers such as %d for int and %lf for double.

The program also checks the value scanf() returns: the number of items it read. Without that check, a typo in the input leaves the variables uninitialized and the program prints garbage.

The program

C
#include <stdio.h>

int main(void) {
    double a, b;

    if (scanf("%lf %lf", &a, &b) != 2) {
        printf("Please enter two numbers.\n");
        return 1;
    }

    double sum = a + b;
    printf("%.2f + %.2f = %.2f\n", a, b, sum);
    return 0;
}
Input (stdin)
2.5 4.25
Output
2.50 + 4.25 = 6.75

How it works

  1. #include <stdio.h> declares scanf() and printf().
  2. scanf("%lf %lf", &a, &b) reads two doubles. The & passes the address of each variable, so scanf can store the values in them.
  3. scanf returns how many values it converted; anything other than 2 means the input was not two numbers, so the program stops with an error code.
  4. printf with %.2f prints each double with two decimal places.
  5. return 0 tells the operating system the program succeeded.

Another way: Whole numbers with int and long long

For integers use int with %d. An int usually holds up to 2,147,483,647, so adding two large values overflows; long long (%lld) holds about 9.2 × 10¹⁸.

C
#include <stdio.h>

int main(void) {
    int a = 7, b = 5;
    long long big = 2000000000LL + 2000000000LL;
    printf("%d + %d = %d\n", a, b, a + b);
    printf("%lld\n", big);
    return 0;
}
Output
7 + 5 = 12
4000000000

Common mistakes

  • Forgetting the & in scanf("%d", &a): scanf then writes to a random address and the program usually crashes.
  • Reading a double with %f in scanf: for double it must be %lf (in printf, %f works for both).
  • Ignoring scanf's return value, so bad input leaves a and b uninitialized.
  • Adding two large ints, which overflows (undefined behaviour in C) instead of giving the big result.

Try it yourself

  • Print the difference, product and quotient as well.
  • Read numbers until the input ends and print their total.

Open the program in the C Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.

Browse all 25 C examples, or write your own program in the online C Compiler.