Input from keyboard

If we want to input from keyboard and assign a value to a variable, we can use scanf()function as follows:

#include<stdio.h>
int main()
{
      int a;
     printf("Enter an integer  value : ");
     scanf("%d", &a);
     printf("You entered : %d", a);
     return 0;
}

 

OUTPUT

Enter an integer value : 13
You entered : 13

Explanation:
When you ran the program you will see “Enter an integer value : ” message. This message is just for informing you that you should input an integer value.
Let you input 13 from keyboard. scanf(“%d”,&a); — this line will cause to assign 13 to variable ‘a’. Pay attention you have to use ‘&’ sign before variable name in case of scanf() but ‘&’ is not needed in case of printf().
printf(“You entered : %d”, a); will print You entered : then encounter to %d and hence it will start to find a variable and it will find a variable named ‘a’. So %d will replace by the value of ‘a’. Thus You entered : 13 will be printed.

Look at the following code:

int a,b,c;
scanf("%d%d%d",&a,&b,&c);

Here first %d refers to &a, second %d refers to &b, third %d refers to &c and if you enter there number from keyboard as follows: 10 20 30 then 10 will assign to a, 20 will assign to b and 30 will assign to c.

Problem: What is the error of the following code?

char a;
float b;
int c;
scanf("%d%f%c",&c,&a,&b);

Solution:
%d should refer an integer type variable and it refers to ‘c’ which is integer type variable. So  when you input from keyboard i should be an integer type value.
%f refers should refer a float type variable and it refers to ‘a’ which is not float but character. It is wrong.
And %c should refer to character type variable and it refers to ‘b’ which is not character type but float type.It is wrong.

So

scanf("%d%f%c",&c,&a,&b);

should be

scanf("%d%f%c",&c,&b,&a); or  scanf("%d%c%f",&c,&a,&b);

Next Previous