Just like printf() to display output a ready-made function scanf() is also available in C Library to take input from user through keyboard. scanf() function is also defined in a Header file stdio.h so if you want to use scanf function in your program then first you have to include the header file stdio.h in your program.
The general form of scanf() function is,
scanf("format string",list of variables);
- %d used in format string for an integer.
- %f used in format string for a real number.
- %c used in format string for a character.
#include<stdio.h> #include<conio.h> int main() { int a; float b; printf("Enter an Integer = "); scanf("%d",&a); printf("Enter a Real number = "); scanf("%f",&b); printf("Integer number = %d \n",a); printf("Real number = %f",b); getch(); return 0; }
Output
Enter an Integer = 35 Enter a Real number = 45.56 Integer number = 35 Real number = 45.560000
In above c program the ampersand(&) is used before variables in scanf() function. & is known as "Address of " operator and it gives address of variable in memory.
- More than one input can be taken in a single scanf() function.
scanf("%d%d%d",&a,&b,&c);
A Program to subtract two integer number in C
#include<stdio.h> #include<conio.h> int main() { int a,b,sub; printf("Enter First Number = "); scanf("%d",&a); printf("Enter Second Number = "); scanf("%d",&b); sub = a-b; printf("Subtraction of %d and %d = %d",a,b,sub); getch(); return 0; }
Output
Enter First Number = 20 Enter Second Number = 5 Subtraction of 20 and 5 = 15
Before going to next chapter you first need to write some programs in c like.
- To Add two numbers using scanf().
- To Multiply two numbers using scanf().
- To Divide two numbers using scanf().