‘User input’ in programming is simply any input a user gives during the execution of a program or application. In C, there are many standard functions to take input from the user. In this program, we will take input from the user and store it in a variable using the standard scanf() function.
Sample Program
#include<stdio>
int main()
{
int x;
printf("Enter a number");
scanf("%d", &x);
printf("The number is %d", x);
return 0;
}
Output:
Enter a number7
The number is 7
Working of this program
- The first line of this program is written to include the standard header file stdio. This file contains the functions printf() and scanf().
- The execution of the program starts from the main function. The open brace ‘{‘ and the closing brace ‘}’ represents the scope of the main function.
- The statement int x is written to create (or declare) a new variable named x which should store integer type value.
- The printf function is an inbuilt function used to display something on the screen. In this case the printf function will display a message “Enter a number”.
- The scanf function is also an inbuilt function found in stdio standard library. This function will take user input and store the value in the variable x. The symbol ‘&’ used with x (i.e., &x) represents the memory address of the variable x. So this statement means that whatever value the user gives would be stored at the memory address of x (or indirectly inside ‘x’).
- The final statement (printf(“The number is %d”, x);) will print the output, i.e. the value of x that is given by the user on the screen.
Taking multiple values from the user simultaneously
We can take multiple inputs using a single scanf() function.
#include<stdio.h>
int main()
{
int x, y;
printf("Enter the numbers :");
scanf("%d%d", &x, &y);
printf("The first number is %d", x);
printf("The second number is %d", y);
return 0;
}