C Language



Admission Enquiry Form

  

Use of printf() and scanf() functions in C

What is printf() and scanf() in C Programming?

printf() function is used for output in the console and scanf() function is used to take input in the console from the user.These are predefined or inbuilt library functions in C programming language which are by default available in C library . These functions are declared in stdio.h (header file).




printf() function

The printf function is used to print the given statement in the console.This function is used for output.It is declared inside the stdio.h (header file)

Syntax

printf("format specifier",argument1,argument2,...);


The format specifier may be %d (integer),%f (float), %c (character), %s (string) etc.



Example 1

#include<stdio.h>
#include<conio.h>
void main()
{
//displaying a string
printf("Welcome to Learn C in COMPUHELP");
getch();
}//end of main


Output

Welcome to Learn C in COMPUHELP



Example 2:

#include<stdio.h>
#include<conio.h>
void main()
{
int num1=10;
float num2=10.5;
char ch='C';
// printing value of num1 integer using format specifier %d
printf("Value of num1 is %d",num1);
// printing value of num2 float using format specifier %f
printf("\nValue of num2 is %f",num2);
// printing value of ch charecter using format specifier %c
printf("\nValue of ch is %c",ch);
getch();
}//end of main


Output

Value of num1 is 10
Value of num2 is 10.500000
Value of ch is C

In the above example 2 \n is used to move the cursor to the next line.



scanf() function

The scanf function is used to take input from the user in the console.This function is used for input.It is declared inside the stdio.h (header file)

Syntax

printf("format specifier",argument1,argument2,...);


The format specifier may be %d (integer),%f (float), %c (character), %s (string) etc.



Example 1:Addition of two numbers using printf() and scanf()

#include<stdio.h>
#include<conio.h>
void main()
{
int num1,num2,res;
printf("Enter first number: ");
scanf("%d",&num1);
printf("Enter second number: ");
scanf("%d",&num2);
res=num1+num2;
printf("Sum is %d",res);
getch();
}//end of main


Output

Enter first number: 10
Enter second number: 20
Sum is 30


The scanf("%d",&num1) and scanf("%d",&num2) statements read integer number from the console and stores the given values in num1 and num2 variables.
The printf("Sum is %d",res); statement prints the sum of num1 and num2 which is stored in res variable on the console.