Example 1 — Read two numbers and print their sum
The user types 7 5 and presses Enter.
#include <stdio.h>
int main(void) {
int a, b;
printf("Enter two numbers: ");
if (scanf("%d %d", &a, &b) != 2) {
printf("Invalid input\n");
return 1;
}
printf("Sum = %d\n", a + b);
return 0;
} How It Works
scanfneeds the address of each variable, so use&aand&b.- It returns how many values it read; check for 2.
- Input
7 5is shown after the prompt; the program printsSum = 12.
