The printf() and scanf() functions are the most commonly used functions in C Programming. These functions are widely used in majority of the C programs. In this tutorial, you will learn, what are these functions, how to use them in C programs.
The scanf()
and printf()
functions are used for input and output in c programs receptively. These functions are defined in stdio.h
header file, so you must include this header file in your program, if you are using any of these functions.
printf() function:
The prinf() function is used to display (or print) output on the console screen.
Syntax of printf() function:
printf("format string",arguments);
The format string (or format specifier) is a string that is used for formatting the input and output. Format string always starts with a ‘%’ character. For example format string for integer is %d, for string %s, for float %f and so on.
scanf() function:
The scanf() function is used to read the input entered by user.
Syntax of scanf() function:
scanf("format string",arguments);
Example 1: use printf() and scanf() functions to add two input numbers
In the following example, we are calculating the sum of two user entered numbers. Program prints message on console to enter the numbers using printf(). The input numbers are read and stored in the variables num1
and num2
by scanf() function. After the sum is calculated, the result is displayed on console using printf() function.
#include<stdio.h>
int main(){
int num1,num2,sum;
printf("Enter first number: ");
//Reading the first input number
scanf("%d",&num1);
printf("Enter second number: ");
//Reading the second input number
scanf("%d",&num2);
//calculating sum of two entered numbers
sum=num1+num2;
//Printing the sum of input numbers using printf()
printf("Sum of %d and %d is: %d ",num1, num2, sum);
return 0;
}
Output:
Example 2: Print the square of input number
In this example of printf() and scanf() functions, we are displaying the square of an input number. We are reading a number entered by user using scanf()
and printing the square of the input number using printf()
.
#include<stdio.h>
int main(){
int num;
printf("Enter a number: ");
scanf("%d",&num);
printf("Square of entered number is: %d ",num*num);
return 0;
}
Output: