printf() and scanf() in C
The printf() and scanf() functions are fundamental in C for input and output operations. They belong to the stdio.h
(Standard Input Output) library, which provides basic input/output capabilities.
printf() function
The printf() function is used for output. It prints the given statement to the console.
Syntax:
printf("format string",argument_list);
Example:
#include <stdio.h>
int main()
{
int num = 10;
float pi = 3.14;
char ch = 'A';
printf("Integer: %d\n", num);
printf("Floating point: %.2f\n", pi);
printf("Character: %c\n", ch);
return 0;
}
Output
Integer: 10
Floating point: 3.14
Character: A
Floating point: 3.14
Character: A
scanf() function
The scanf() function is used to take input from the user and store it in variables. It uses format specifiers to determine the type of input.
Syntax:
scanf("format string",argument_list);
Example:
#include <stdio.h>
int main()
{
int age;
float height;
char name[50];
printf("Enter your name: ");
scanf("%s", name);
printf("Enter your age: ");
scanf("%d", &age);
printf("Enter your height: ");
scanf("%f", &height);
printf("Name: %s\nAge: %d\nHeight: %.2f\n", name, age, height);
return 0;
}
Output
Input:
Enter your name: John
Enter your age: 25
Enter your height: 5.9
Output:
Name: John
Age: 25
Height: 5.90
Enter your name: John
Enter your age: 25
Enter your height: 5.9
Output:
Name: John
Age: 25
Height: 5.90