Reading data from keyboard


A way of giving values to variables is to input data through keyboard using the scanf method. It is a general input function available in C and is very similar in concept to the printf method. The general format of scanf is as follows :

scanf("cs", &v1,&v2,...);

The information obtained in cs contains the format. The ampersand & symbol and an operator that specifies the name of the variable before each variable name. We must always use this operator, otherwise unexpected results may come.

scanf("%d",&num);

When this statement is encountered by the computer, the execution stops and waits for the value of the variable num to be typed in. Since the control string "% d" specifies that an integer value must be read from the terminal, we must type the value as an integer. Once the number is typed in and the "Return" Key is pressed, the computer then proceeds to the next statement. Thus, the use of scanf provides an interactive feature and makes the program 'user friendly'. The value is assigned to the variable num.

Example

Program
#include <stdio.h>

int main()
{
  int a, b;
  printf ("Enter your two numbers \n");
  scanf ("%d%d", &a, &b);
  if (a > b)
    printf ("First number is big.");
  else
    printf ("Second number is big.");
  return 0;
}

In the above example, two numbers (a, b) are taken as integers from the user's keyboard and the larger of the two numbers is found out.


Example

Program
// calculate the area of a rectangle using user input
#include <stdio.h>

int main()
{
  float Length,Width,Area=0;
  printf("Enter the Length of Rectangle \n");
  scanf("%f",&Length);
  printf("Enter the Width of Rectangle \n");
  scanf("%f",&Width);
  Area=Length*Width;
  printf("Area = %f",Area);
  return 0;
}

In the above example the area of a rectangle is found out. Here the values of Lenth and Width are taken from the user as a float so "%f" is used in scanf.