printf() and scanf() in C
In this tutorial, you will learn to use scanf() function to take input from the user, and printf() function to display output to the user.
The printf() and scanf() functions are used for input and output in C language. Both functions are inbuilt library functions, defined in stdio.h (header file).
printf() function
In C programming, printf() is one of the main output function. The function sends formatted output to the screen.
The printf() function is used for output. It prints the given statement to the console.
Important points about printf():
- printf() function is defined in stdio.h header file. By using this function, we can print the data or user-defined message on monitor (also called the console).
- printf() can print a different kind of data format on the output string.
- To print on a new line on the screen, we use “\n” in printf() statement.
The syntax of printf() function is given below:
printf("format string",argument_list);
The format string can be %d (integer), %c (character), %s (string), %f (float) etc.
Example
#include <stdio.h>
int main()
{
// Displays the string inside quotations
printf("C Programming");
return 0;
}
Output
C Programming
How does this program work?
- The code execution begins from the start of the main() function.
- The printf() is a library function to send formatted output to the screen. The function prints the string inside quotations.
- To use printf() in our program, we need to include stdio.h header file using the #include <stdio.h> statement.
- The return 0; statement inside the main() function is the "Exit status" of the program. It's optional.
Integer Output
#include <stdio.h>
int main()
{
int testInteger = 5;
printf("Number = %d", testInteger);
return 0;
}
Output
Number = 5
scanf() function
In C programming, scanf() is one of the commonly used function to take input from the user. The scanf() function reads formatted input from the standard input such as keyboards.
The scanf() function is used to read input data from the console. The scanf() function is builtin function available in the C library. scanf() function can read character, string, numeric & other data from keyboard in C language.
Syntax:-
scanf("format string",argument_list);
Example:-
#include<stdio.h>
int main(){
int number;
printf("enter a number:");
scanf("%d",&number);
printf("cube of number is:%d ",number*number*number);
return 0;
}
Output
enter a number:8
cube of number is:512
Format Specifiers for I/O
As you can see from the above examples, we use
- %d for int
- %f for float
- %lf for double
- %c for char
Here's a list of commonly used C data types and their format specifiers.
Data
Type |
Format
Specifier |
int |
&d |
char |
%c |
float |
%f |
double |
%lf |
short
int |
%hd |
unsigned
int |
%u |
long int |
%li |
long
long int |
%lli |
unsigned
long int |
%lu |