Multiple inputs
- C course
- Beginner
- Lesson 32/116
- 4 min
Learn to read multiple values with a single scanf.
One scanf, several values
You can read several values with a single scanf call. The specifier count in the format string must match the variable count; the space between them lets users separate values with spaces or Enter.
int a, b;
printf("Two numbers: ");
scanf("%d %d", &a, &b);
printf("Sum: %d\n", a + b);If the user enters 3 4, then a=3, b=4. 3\n4 or 3 4 also works; scanf skips whitespace automatically.
Mixing different types
You can mix different types in the same scanf call. Each specifier must match the type of the next variable.
int id;
char initial;
printf("Number and letter: ");
scanf("%d %c", &id, &initial);
printf("Record: %d-%c\n", id, initial);If the user enters 7 A, the output is Record: 7-A. The space before %c is important; without it, %c reads the space character. So writing " %c" is safer.
Practice Read two numbers, sum and print
Write a C program. Declare int a, b;. Print a request line with printf. Read two integers with scanf("%d %d", &a, &b);. Print the sum a + b using printf with the %d specifier. Put #include <stdio.h> at the top.
Starter code
#include <stdio.h>
int main(void) {
// Declare a and b, read two numbers, print the sum
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
int a, b;
printf("Two numbers: ");
scanf("%d %d", &a, &b);
printf("Sum: %d\n", a + b);
return 0;
}Expected output
Two numbers: Sum: 7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How many values does scanf("%d %d", &a, &b) read?
int a, b;
scanf("%d %d", &a, &b);- 2 Correct answer
- 1
- 0
- 3
Explanation: Two %d specifiers read two values.
2 Read two numbers
scanf("____", &x, &y);
scanf("%d %d", &x, &y);
Explanation: %d %d reads two integers separated by whitespace.
3 Match format and types
| Term | Meaning |
|---|---|
%d %d |
Two integers |
%f %f |
Two decimals |
%d %c |
Number and letter |
%c %c |
Two characters |