printf() and scanf()

These two functions are used in many beginner C programs. printf() is mainly used to display output, while scanf() is commonly used to read formatted input.

printf() — display output

int age = 20;
printf(“Age = %d”, age);

 

Important format specifiers

SpecifierMeaningExample
%dintegerprintf(“%d”, age);
%ffloating-point valueprintf(“%.2f”, price);
%csingle characterprintf(“%c”, grade);
%sstringprintf(“%s”, name);
%lfdouble with scanf()scanf(“%lf”, &value);

scanf() — take input

int age;
printf(“Enter age: “);
scanf(“%d”, &age);

 

The & before a normal variable gives its address. scanf() uses that address to store the input value.

Complete program

#include <stdio.h>

int main() {
int age;
float marks;
char grade;

printf(“Enter age: “);
scanf(“%d”, &age);

printf(“Enter marks: “);
scanf(“%f”, &marks);

printf(“Enter grade: “);
scanf(” %c”, &grade);

printf(“\nAge = %d”, age);
printf(“\nMarks = %.2f”, marks);
printf(“\nGrade = %c”, grade);

return 0;
}

 

OUTPUT
Enter age: 21
Enter marks: 87.5
Enter grade: A

Age = 21
Marks = 87.50
Grade = A

 

⭐ EASY TIP: Notice the space before %c in scanf(” %c”, &grade). It helps skip whitespace left in the input stream.
Scroll to Top