How to Read Data From Keyboard Using scanf() Function
Similar to printf() function, scanf() function also uses the %d, %f, %c and other format specifiers to specify the kind of data to be read from the keyboard.
However, it expects the programmer to prefix the address operator '&' to every variable written in the argument list as show below:
int roll;
scanf("%d",$roll);
The above set of statements declares the variable 'roll' of data type 'int', and reads the value for 'roll' from the keyboard. It may be noted that '&' the address operator, is prefixed to the variable 'roll'. The reason for specifying '&' would be discussed later.
Similarly, other format specifiers can be to input data from the keyboard.
Example 1: Write an interactive program that reads the marks secured by a student for four subjects 'Sub1', 'Sub2', 'Sub3' and 'Sub4' the maximum marks of a subject being 100. The program shall compute the percentage of marks obtained by the student.
Solution : The scanf() and printf() functions would be used to do the required task. The required program is as follows :
#include<stdio.h>
main()
{
int sub1,sub2,sub3,sub4;
float percent;
printf("Enter the marks for four subjects :");
scanf("%d %d %d %d", &sub1, &sub2, &sub3, &sub4);
percent = (sub1 + sub2 + sub3 + sub4)/400.00*100;
printf("The percentage = %f", & percent);
}
For input data : 45 56 76 90
The above program computes the percentage and displays the following output :
Outout :
The percentage = 66.750000
0 comments:
Post a Comment