Home >>C Tutorial >Printf and scanf in C

Printf and scanf in C

Difference between printf and scanf in c

The difference between printf() and scanf() in C is mentioned in this tutorial, these are the functions used for providing input and deriving the output in the C. Point to be noted is that both the functions are inbuilt library functions and are defined in the stdio.h (header file).

printf() function

The printf() function is basically used for deriving the output. The given statement is printed to the console by this function.

Here is the syntax of the printf() function:

printf("format string",argument_list);  

Please note that the format string can be any of them like %d (integer), %c (character), %s (string), %f (float) etc.

Scanf() function

The scanf() function is generally used for getting the input. The input data from the console is read by this function.

Here is the syntax of the scanf() function:

scanf("format string",argument_list); 

Here is an example of the program used to print the cube of a given number.

This simple example of the C language gets input from the user and prints the cube of the given number.

 #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:3
cube of number is:27

The scanf("%d",&number) statement is used to read the integer number from the console and it stores the provided value in the number variable.

Here is another example to print the sum of the two numbers in C language.

In the given example, the sum of two numbers is printed.

#include<stdio.h>    
int main()
{    
int x=0,y=0,result=0;    
printf("enter first number:");  
scanf("%d",&x);  
printf("enter second number:");  
scanf("%d",&y);  
result=x+y;  
printf("sum of 2 numbers:%d ",result);  
return 0;  
}    
Output
Enter first number: 3
Enter second number: 5
Sum of 2 numbers: 8

No Sidebar ads