#include
#include
void main()
{
float price,qty,total;
price=24.5;
qty=2;
total=price*qty;
printf("\nThe total bill is %d",total);
}
Whenever this program is compiled the result will always be 49. Why ? simple because the price has been set to 24.5 and qty to 2. This poses a big problem. What if the user wants to change the value of price or qty so that he/she can have different answer. The answer lies in the function "scanf()" which is used to accept input any value from the user so that we can different answer everytime.
Let the user input the value - The scanf function
The scanf() function expects the user to specify two thing a) The type of data b) The memory location where the value will be saved. Consider its syntax
scanf("%format",&varname);
The format part will be replaced by the specifiers like %d,%f,or %c as per the condition while varname will be replaced by the name of a variable. The "&" pronounced(ampersand) is called the "address of" operator will remain there only (more about it later).
Let's try to use scanf() and rewrite the above program
#include
#include
void main()
{
float price,qty,total;
printf("\nEnter price ");
scanf("%f",&price);
printf("\nEnter quantity ");
scanf("%f",&qty);
total=price*qty;
printf("\nThe total bill is %f",total);
}
Type the code and run it. You will will the following output
Enter price (Here the program will wait for you enter a value. Enter a valid value and press enter)
Enter quantity (the program will again wait for your input. Type a value and again hit the enter key)
Once you have entered the values the program will return to the code window (editor window). Press Alt + F5 to see that the output is the multiplication of the values entered by you and not 49 as it was previously. This is the advantage of scanf(). Whenever the program is compiled it will ask for the value of price and quantity from you and will display different results as per the values entered by you.
0 comments:
Post a Comment