Input Instruction (user input)

Default input device is keyboard. Input instruction makes possible to user input data from keyboard






scanf()

  • scanf() is a predefined function.
  • It is used to input data from keyboard and stores in variables of the program.

Syntax

scanf(“format specifier”, address of variable);

Example:

int main()
{
int a;
scanf(“%d”,&a);
return(0);
}

In this program, we have declared a variable a of type int. scanf() function takes one integer value through keyboard and stores it in the variable a.

Note the address of operator (&) before variable a. don’t forget to put this operator before variable name. Function scanf is called by passing address of variable a. It is too early to unveiled about address of operator and the reason why it is used in scanf. We will understand about address of operator in great detail in Pointers chapter.

Multiple input using sing scanf() function

int main()
{
int a;
float y;
scanf(“%d %f”,&a,&y);
return(0);
}

For float variable format specifier should be %f.
User can now input two values from the keyboard. scanf() function converts the raw sequence of characters into type int and float respectively. First value goes to variable a and second value stores in y.

Write a program to add two number.
int main()
{
int a,b,c;
printf(“Enter two numbers”);
scanf(“%d %d”,&a,&b);
c=a+b;
printf(“Sum is %d”,c);
getch();
return(0);
}

Output
Enter two numbers5
6
Sum is 11

User Input