Taking User's Input:

In C, we can use scanf function to take input from the user.

input.c
#include <stdio.h>

int main() {
  int age;
  
  // Reading an integer
  printf("Enter your age : ");
  scanf("%d", &age);
      
  // Printing the values entered by the user
  printf("You age is %d", age);
  
  return 0;
}
  

Point : When we take input from the user, we have to store it in a variable. At this point, we have learnt to take input in integer variable. In next example, we will see that how we can take input in vaiables with different data types.


In our example;

  • Declared int type variable age first.
  • Prompting user to enter age.
  • Taking input and storing in age variable.
  • Printing value in age variable with some text.
  • Returning from the main function.

Taking Different types of Variables as Input:

Till now, we know that how we can take input in int type variable. In this example, we will see that how can we take input in variables with different data types and print them.

input.c
#include <stdio.h>

int main() {
  float per;
  char grade;
  char name[50];
  
  
  // Taking input in a float type variable
  printf("Enter your percentage : ");
  scanf("%f", &per);
  
  // Taking input in a character type variable
  printf("Enter your grade : ");
  scanf(" %c", &grade);   

  // Taking input in a string of characters
  printf("Enter your name without spaces : ");
  scanf("%s", name);

  // Printing the values entered by the user
  printf("Name = %s \n", name);
  printf("Percentage = %f \n", per);
  printf("Grade = %c, \n", grade);
  
  return 0;
}

In this way, we can take input in different types of variables and use them later for processing. We can do calculations with data stored in variables using different types of operators which we will discuss in Operators section.

Note : Variables are stored at some place in memory when they are declared. The data value which is provided by the user as input is stored in the variables.