In C, we use scanf to take input from the user, and often it is necessary to take multiple inputs simultaneously. In this article, we will learn about how to take multiple inputs from the users in C.
Multiple Inputs From a User in C
To take multiple inputs from users in C, we can declare an array to store the user input and repeatedly call the scanf() function within loop to keep taking the inputs until required. While reading strings as inputs the user may encounter spaces, to deal with them the fgets() function can be used to read strings with spaces.
C Program to Take Multiple Inputs from the User
The below program demonstrates how we can take multiple inputs from the users in C.
// C Program to Take Multiple Inputs from User
#include <stdio.h>
int main()
{
// Declare variables to hold the number of integers and
// loop index
int n, i;
// Prompt the user to enter the number of inputs they
// want to enter
printf(
"Enter the number of integers you want to input: ");
scanf("%d", &n);
// Declare an array of size n to hold the integers
int arr[n];
printf("Enter %d integers:\n", n);
// Loop to read n integers from the user
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Print the integers entered by the user
printf("You entered:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Output
Enter the number of integers you want to input: 5
Enter 5 integers:
10
20
30
40
50
You entered:
10 20 30 40 50
Time Complexity: O(N), here N denotes the number of inputs.
Auxiliary Space: O(N)