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;
}

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.