Read Multiple Inputs from User using a Loop in C
In C, we can read multiple inputs from the user efficiently using loops such as for
, while
, or do-while
. By using a loop, we avoid redundant code and allow the user to input multiple values dynamically. This approach is commonly used in programs that require user-defined lists, calculations, or data storage.
Examples of Reading Multiple Inputs
1. Reading Multiple Integers Using a for
Loop
In this example, we will ask the user to enter 5 integers and store them in an array using a for
loop.
main.c
#include <stdio.h>
int main() {
int numbers[5];
// Using a for loop to take 5 inputs
printf("Enter 5 integers:\n");
for (int i = 0; i < 5; i++) {
scanf("%d", &numbers[i]);
}
// Displaying the entered numbers
printf("You entered: ");
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
return 0;
}
Explanation:
- We declare an integer array
numbers[5]
to store 5 integers. - We use a
for
loop to iterate 5 times and read user inputs usingscanf("%d", &numbers[i])
. - We then use another
for
loop to print the stored values.
Output:
Enter 5 integers:
10 20 30 40 50
You entered: 10 20 30 40 50
2. Reading Multiple Inputs Until User Enters Zero
In this example, we will allow the user to keep entering numbers until they enter zero. We will use a while
loop for this.
main.c
#include <stdio.h>
int main() {
int number;
// Using while loop to take inputs until 0 is entered
printf("Enter numbers (enter 0 to stop):\n");
while (1) {
scanf("%d", &number);
if (number == 0) {
break;
}
printf("You entered: %d\n", number);
}
return 0;
}
Explanation:
- We declare an integer variable
number
to store user input. - A
while(1)
loop is used to continuously take inputs. - If the user enters
0
, we usebreak
to exit the loop. - Otherwise, we print the entered number.
Output:
Enter numbers (enter 0 to stop):
5
You entered: 5
8
You entered: 8
0
3. Reading Multiple Strings Using a for
Loop
In this example, we will read multiple strings from the user and store them in an array of strings.
main.c
#include <stdio.h>
int main() {
char names[3][20];
// Using for loop to take multiple string inputs
printf("Enter 3 names:\n");
for (int i = 0; i < 3; i++) {
scanf("%s", names[i]);
}
// Displaying the entered names
printf("You entered:\n");
for (int i = 0; i < 3; i++) {
printf("%s\n", names[i]);
}
return 0;
}
Explanation:
- We declare a 2D character array
names[3][20]
to store 3 strings, each up to 20 characters. - A
for
loop is used to take 3 string inputs usingscanf("%s", names[i])
. - Another
for
loop prints the stored names.
Output:
Enter 3 names:
Arjun
Ram
Priya
You entered:
Arjun
Ram
Priya
Conclusion
In this tutorial, we explored different ways to read multiple inputs from the user using loops in C:
for
Loop: Used when we know how many inputs we need.while
Loop: Useful when the number of inputs is unknown (e.g., stopping on a condition).- Reading Strings: Demonstrated how to take multiple string inputs.