Freshers Aptitude technical questions
Freshers Job Alert
Bookmark and Share

C Programming Tutorial

Learn C programming in an easy way.This C programming tutorial is completly free for your use.

How you can help us back is let us know about more tutorials and send us the tutorial with your small photo and name.We will publish tutorial in your name.

 

<< Tutorial Home

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.
the c language provides no error checking for user input. The user is expected to enter the correct data type. For instance, if a user entered a character when an integer value was expected, the program may enter an infinite loop or abort abnormally.
its up to the programmer to validate data for correct type and range of values.

 

 

<< Tutorial Home