Create and fill an array using Inputs from Command Line
In all the programming examples on arrays so far, we have hard coded all the values present in the array. But in most of the practical scenarios, we will have to take inputs dynamically when the program is actually being run. In this article, we will go through details of how to initialize and array and fill in the elements at run time by taking user input through command line or terminal.
For ease of understanding, the code is kept consistent for all programming languages. For example, in python, we can directly keep appending values to the end of list. But to explain array concepts, instead of appending values, we pre-initialize array with desired size and use indexes to fill in elements.
Below are the implementations in different programming languages to initialize an array with required size and then fill in elements one by one using user input:
#include <stdio.h>
int main() {
int count; // To store the size of the array
printf("Enter the size of the array: ");
scanf("%d", &count);
// Check if the count is non-negative
if (count <= 0) {
printf("Invalid size. Please enter a positive integer.\n");
return 1; // Exit with an error code
}
int arr[count]; // Declare an array of the specified size
printf("Enter %d elements, one at a time:\n", count);
// Keep reading values until the array is filled
for (int i = 0; i < count; i++) {
printf("Element %d: ", i + 1);
scanf("%d", &arr[i]);
}
printf("You entered the following elements:\n");
for (int i = 0; i < count; i++) {
printf("%d ", arr[i]);
}
return 0;
}
def main():
try:
count = int(input("Enter the size of the array: "))
if count <= 0:
print("Invalid size. Please enter a positive integer.")
return
arr = [0] * count # Create an array of zeros with the specified size
print(f"Enter {count} elements, one at a time:")
# Keep reading values until the array is filled
for i in range(count):
element = int(input(f"Element {i + 1}: "))
arr[i] = element # Assign the element to the array at the specified index
print("You entered the following elements:")
for element in arr:
print(element, end=" ")
except ValueError:
print("Invalid input. Please enter integers only.")
if __name__ == "__main__":
main()
function main() {
try {
const count = parseInt(prompt("Enter the size of the array:"));
if (count <= 0 || isNaN(count)) {
console.log("Invalid size. Please enter a positive integer.");
return;
}
const arr = new Array(count); // Create an array with the specified size
console.log(`Enter ${count} elements, one at a time:`);
// Keep reading values until the array is filled
for (let i = 0; i < count; i++) {
const element = parseInt(prompt(`Element ${i + 1}:`));
arr[i] = element; // Assign the element to the array at the specified index
}
console.log("You entered the following elements:");
console.log(arr.join(" "));
} catch (error) {
console.log("Invalid input. Please enter integers only.");
}
}
main();
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter the size of the array: ");
int count = scanner.nextInt();
if (count <= 0) {
System.out.println("Invalid size. Please enter a positive integer.");
return;
}
int[] arr = new int[count]; // Create an array with the specified size
System.out.println("Enter " + count + " elements, one at a time:");
// Keep reading values until the array is filled
for (int i = 0; i < count; i++) {
System.out.print("Element " + (i + 1) + ": ");
arr[i] = scanner.nextInt(); // Assign the element to the array at the specified index
}
System.out.println("You entered the following elements:");
for (int element : arr) {
System.out.print(element + " ");
}
} catch (java.util.InputMismatchException e) {
System.out.println("Invalid input. Please enter integers only.");
}
}
}
Below are the different steps performed:
Prompt the user to enter the size of the array which is stored in (count) variable.
Check if the entered size is non-negative and valid.
Declare an integer array (arr) of size count.
Prompt the user to input each element of the array one by one.
Finally, print all the entered elements to confirm the user’s input.
TODO: Add compact ways of initializing and adding elements to array.