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.
- scanf()
- printf() format specifiers
- int and double
- checking return values
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
#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;
}2.5 4.252.50 + 4.25 = 6.75How it works
- #include <stdio.h> declares scanf() and printf().
- scanf("%lf %lf", &a, &b) reads two doubles. The & passes the address of each variable, so scanf can store the values in them.
- 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.
- printf with %.2f prints each double with two decimal places.
- 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¹⁸.
#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;
}7 + 5 = 12
4000000000Common 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.
Related examples
Browse all 25 C examples, or write your own program in the online C Compiler.