We have already used printf function to display formatted output. The scanf is a similar function that is used to read data into a program. The scanf function accepts formatted input from the keyboard. Program-2.10 demonstrates the use of the scanf function:
/* Program-2.10 */
#include <stdio.h>
int main()
{
float a,b,sum;
scanf("%f", &a); // read 1st number
scanf("%f", &b); // read 2nd number
sum = a + b; // total
printf("a+b = %f\n", sum); //display answer as float
return 0;
}
Three variables are declared (a, b and sum) in Program-2.10. Values of “a” and “b” are to be read from the keyboard using the scanf function, while the value of the variable “sum” is calculated as the summation of “a” and “b”. The scanf function uses the same set of formatting characters as the printf function to describe the type of expected input.
Note that the scanf function uses the variables “a” and “b”as “&a” and “&b”. The symbol “&” is called the address of operator. The string “&a” represents the memory address containing variable “a” and is called a pointer (see Section 8).
When the program executes, it waits for the user to type the value of “a” followed by the Enter key and then it waits for the value of “b” followed by another the Enter key. The supplied input values can be separated either by pressing Enter key or by leaving a blank space between the numbers. Both of the following inputs are valid for Program-2.10.
23
Answer > 5.000000
or
2 3
Answer > 5.000000
Exercise 2.6: Modify Program-2.10 so that it displays the answer with only two decimal points. The scanf function also supports mixed types of input data. Consider the following line of code: scanf("%d%f",& a,&b);
The scanf function accepts variable “a” as an integer and “b” as a floating point number. In certain cases you may want to separate your inputs using a comma (,) rather than using the Enter key or a blank space. In such cases you must include the comma between format characters as: scanf("%f,%f", &a,&b);
For such a program your inputs should be in the form:
2,3
One deficiency of the scanf function is that it cannot display strings while waiting for user input. This will require use of an additional function like the printf in order to display a message as a prompt for the user reminding the required data item.
Exercise 2.7: Modify Program-2.10 so that it displays the following output when executed.
Enter 1st number : 2
Enter 2nd number : 3
Answer > 5
No comments:
Post a Comment