Showing posts with label scanf. Show all posts
Showing posts with label scanf. Show all posts

Friday, October 21, 2011

Fetching an input from the user

The following program demonstrates how an input is fetched from the user in the program :

Program:

#include<stdio.h>
void main()
{
    int i;
    printf("Please enter a value for i : \t");
    scanf("%d",&i);
    printf("\n Value of i : \t%d",i); 
}
The scanf() function is used to fetch an input from the user.

 The line 6 shows how to use a scanf() function to fetch an input from the user. The '%d' shows that an integer type variable is fetched from the user and the value is stored in i.
Output:

Please enter a value for i : 5
Value of i : 5

Similarly we can also fetch multiple values using scanf

Program:
 
#include<stdio.h>
int main()
{
    int i;
    float j;
    char k;
    printf("\n Enter the value for i : \t");
    scanf("%d",&i);
    printf("\n Enter the value for j: \t");
    scanf("%f",&j);
    printf("\n Enter the value for k: \t");
    scanf("\n%c",&k);
    printf("\n Value of i : \t%d",i);
    printf("\n Value of j : \t%f",j);
    printf("\n Value of k : \t%c",k);    
    return 0;   
 }

'%f' is used to fetch floating number and '%c' is used to fetch a character from the user.

Look at line 13. I have added \n before '%c'. There is a reason behind this. After you enter your input for j (floating point number), you will press 'Enter' key. It is also a character (\n). This character '\n' will be assigned to 'k'. To avoid this, i've placed \n (New Line) before %c. Thus it will ignore the pressing of 'Enter' key which produces '\n' key character.
Output:

Enter the value for i :   4
Enter the value for j :   4.6
Enter the value for k :   h
Value of i :   4
Value of j :   4.600000
Value of k :   h