C printf and scanf
printf() prints output on the screen and scanf() reads input from the keyboard. Both are defined in the stdio.h header file.
printf()
#include <stdio.h>
int main(void) {
int age = 21;
float marks = 86.5f;
char grade = 'A';
printf("Welcome to C\n");
printf("Age: %d, Marks: %.1f, Grade: %c\n", age, marks, grade);
return 0;
}
Output:
Output of the above program is
Welcome to C
Age: 21, Marks: 86.5, Grade: A
scanf()
scanf() needs the address of the variable, so we write & before its name. Here the user types 20 and 30.
#include <stdio.h>
int main(void) {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("Sum = %d\n", a + b);
return 0;
}
Output:
Output of the above program is
Enter two numbers: 20 30
Sum = 50
Reading different types
#include <stdio.h>
int main(void) {
int age;
float height;
char initial;
scanf("%d %f %c", &age, &height, &initial);
printf("%d, %.2f, %c\n", age, height, initial);
return 0;
}
Output:
Output of the above program is
19, 5.70, R
Common mistakes
- Forgetting
&inscanf("%d", &n). This crashes the program. - Using a wrong format specifier, like
%dfor a float. scanf("%s")stops at the first space, so it cannot read a full name with spaces.
Note:
The format specifiers are explained in C Format Specifiers.
Next: C Escape Sequences.
Congratulations! Chapter Finished. Learn more about the similar topics: