Consider this program.
#include<stdio.h>
int main()
{
int V;
V = 15;
printf("The value of V is %d\n", V);
return 0;
}
The value of
V is assigned with 15. Thus the printed text will be
"The value of V is 15". Now, what if we want to print different value of V. We have to go back to the source code and change 15 to the desired value. And what if we want the value to be set during the program execution. For example, the program might ask a value which the user wants to print. Such operation can be effected by using a function called
scanf. The
scanf function is the opposite of
printf function. While
printf prints values at the terminal,
scanf reads values entered by users into the program. The following program prints a message which asking the user to enter a value of V.
#include<stdio.h>
int main()
{
int V;
printf("Enter the value of voltage, V: ");
scanf("%d", &V);
printf("The value of V is %d\n", V);
return 0;
}
Output
Enter the value of voltage, V: 5
The value of V is 5
The first
printf prints "Enter the value of voltage, V: ". This message prompts the user to type in a value for voltage. Then
scanf function is invoked. The
scanf contains two arguments. The first argument is the
format control string specifies the data type of value to be read from the terminal. In this example
%d is specified which indicates integer value is expected to be read. The second argument specifies which variable to be used to store the inputted value. The ampersand (
&) is necessary in this case. The function of
& will be explained later. For now don't forget to put leading
& in front of the variable when using
scanf function.
As explained in the preceding discussion, integer value is to be read from the terminal and stored in
V. 5 is type in as given in the example. Thus, 5 is printed by the subsequent
printf function and then the program execution is complete.