Basic Programs
Read two integers interactively, validate input, and print their sum.
Complete program
#include <stdio.h>
int main(void) {
int a, b;
printf("First number: ");
if (scanf("%d", &a) != 1) return 1;
printf("Second number: ");
if (scanf("%d", &b) != 1) return 1;
if (a < -1000000 || a > 1000000 || b < -1000000 || b > 1000000) {
puts("Use numbers between -1000000 and 1000000.");
return 1;
}
printf("Sum: %d\n", a + b);
return 0;
}
Opens a new program without replacing your saved code. Press Run when you are ready.
How it works
Each scanf call waits for the next integer. Its return value must be 1 before the variable is used. The ampersand passes the address where scanf should store the number.
The range check keeps the sum within the supported integer range. Enter ordinary representable integers; scanf is not a robust parser for arbitrarily large numeric text. Try one negative value and predict the sum before running.
Sample input
45
20Enter these values when prompted. The transcript below includes typed responses.
Expected output
First number: 45
Second number: 20
Sum: 65Concepts to practice
- Interactive stdin
- Addresses
- Input validation
- Arithmetic
Predict a different input or change one value, then compare the result with your prediction. Keep changes within the documented bounds and read warnings before trusting an answer.