scanf-function-in-c
In the first c program, we have seen how to display a message on the output screen. Now We are going to learn how to use a scanf function in c to take the input from the user.

What is a scanf() function?

This function is counter-part of the printf() function. printf() outputs the values to the screen whereas scanf() receives them from the keyboard. 

We will perform a simple program to understand how the scanf function works.

C Program To Calculate Simple Interest 

#include<stdio.h>
#include<conio.h>
void main()
{
 int p,n;
 float r,si;
 clrscr();

 p=5000;
 n=5;
 r=5.5;

 /* formula for simple interest */
 si=p*n*r/100;

 printf("\n Simple Interest : %.2f",si);

 getch();
}
Output :
Output-Calculate-Simple-Interest





In the above program, we assumed the values of p, n and r to be 5000,5 and 5.5 respectively. Everytime we run the program we would get the same value for simple interest.
If we want to calculate simple interest for any other values of p,n and r, we are required to make the relevant change in the program, and again compile and execute it.
Thus, the program is not general enough to calculate the simple interest for any set of values without being required to make the changes in the program.
To make the program general, the program itself should ask the user to supply the values of p,n and r through the keyboard during the run time. This can be achieved using a scanf() function.

Calculate Simple Interest Using Scanf Function

#include<stdio.h>
#include<conio.h>
void main()
{
 int p,n;
 float r,si;
 clrscr();

 printf("\n Enter The Values :\n");

 printf("\n P = ");
 scanf("%d",&p);

 printf("\n N = ");
 scanf("%d",&n);

 printf("\n R = ");
 scanf("%f",&r);

 /* formula for simple interest */
 si=p*n*r/100;

 printf("\n Simple Interest : %.2f",si);

 getch();
}

Output : 
Output-Calculate-Simple-Interest-With-Scanf







What scanf 
function does is it asks the user to enter the values from the keyboard. Thus, we can take different no. of values and obtain different results each time we compile and run the program without making the changes in it.
Note that the ampersand symbol (&) before the variables in the scanf() function is a must.
  • & is an 'Address of operator'. It gives the location number used by the variable in memory. 
  • When we say &p we are telling scanf() at which memory location should it store the value.
We should make a habit of taking the input from the user itself if required in the program.