C - Read Console Input


Consider the following code


#include <stdio.h>

int main(void)
      float radius = 0.0f;                  // The radius of the table
      float diameter = 0.0f;                // The diameter of the table
      float circumference = 0.0f;           // The circumference of the table
      float area = 0.0f;                    // The area of the table
      float Pi = 3.14159265f;
    //from  ww w .  ja v  a2s  .  c  o m
      printf("Input the diameter of the table:");
      scanf("%f", &diameter);               // Read the diameter from the keyboard
      radius = diameter/2.0f;               // Calculate the radius
      circumference = 2.0f*Pi*radius;       // Calculate the circumference
      area = Pi*radius*radius;              // Calculate the area
      printf("\nThe circumference is %.2f", circumference);
      printf("\nThe area is %.2f\n", area);
      return 0;


You declare and initialize five variables, where Pi has its usual value.

The following statement reads the value for the diameter of the table.

You use a new standard library function, the scanf() function, to do this:

scanf("%f", &diameter);                   // Read the diameter from the keyboard

scanf() function is another function that requires the stdio.h header file to be included.

This function handles input from the keyboard.

It takes what you enter and converts it as control string between double quotes.

In this case the control string is "%f" because you're reading a value of type float.

It stores the result in the variable specified by the second argument, diameter in this instance.

The first argument is a control string similar to what we used with the printf() function.

& preceding the variable name diameter is called the address of operator.

It allows the scanf() function to store the value that is read from the keyboard in your variable, diameter.

Related Topics