KEYBOARD INPUT
There is a function in C which allows the programmer to accept
input from a keyboard. The following program illustrates the use
of this function,
#include <stdio.h> main() /* program which introduces keyboard input */ { int number; printf("Type in a number \n"); scanf("%d", &number); printf("The number you typed was %d\n", number); } Sample Program Output Type in a number 23 The number you typed was 23
An integer called number is defined. A prompt to enter in a number is then printed using the statement
printf("Type in a number \n:");
The scanf routine, which accepts the response, has two arguments. The first ("%d") specifies what type of data type is expected (ie char, int, or float). List of formatters for scanf() found here.
The second argument (&number) specifies the variable into which the typed response will be placed. In this case the response will be placed into the memory location associated with the variable number.
This explains the special significance of the & character (which means the address of).
Sample program illustrating use of scanf() to read integers, characters and floats
#include < stdio.h > main() { int sum; char letter; float money; printf("Please enter an integer value "); scanf("%d", &sum ); printf("Please enter a character "); /* the leading space before the %c ignores space characters in the input */ scanf(" %c", &letter ); printf("Please enter a float variable "); scanf("%f", &money ); printf("\nThe variables you entered were\n"); printf("value of sum = %d\n", sum ); printf("value of letter = %c\n", letter ); printf("value of money = %f\n", money ); } Sample Program Output Please enter an integer value 34 Please enter a character W Please enter a float variable 32.3 The variables you entered were value of sum = 34 value of letter = W value of money = 32.300000
This program illustrates several important points.