December 22, 2024

C Programming Tutorial: Fill in Array Entries From User Input

In this C programming tutorial, we explain two basic methods for filling in array entries from the user input. Although this problem might look simple to more advanced students, the solution and correct implementation of this problem are not trivial. It is good learning practice to go through this problem. In this tutorial, we will present two basic solutions to this problem. Note that the presented solutions are not the most optimal ones, and they are not very robust taking into account that a user can enter a mix of different data types. However, for people learning C, these solutions are good enough and they explain a number of aspects of the C programming language. The YouTube tutorial is given below.

Problem Definition

In this tutorial, we consider the following two problems.

Problem 1: A person first enters the capacity of an array that needs to be filled in. The array should be filled in until it is full. Write a C program that will ask the person to enter the numbers one by one. At the end of the program, the array entries are printed out.

Problem 2: A person enters a series of numbers without specifying upfront the total number of entries. To mark the end of the input, the user enters -1. Write a C program that will read the series of numbers specified by the user and that will store these numbers in the array. At the end of the program, the array entries are printed out.

Solution of Problem 1

The code given below solves the first problem.

#include<stdio.h>
#include <stdlib.h>
int main()
{
    int size;

    printf("Enter the desired number of entries in the integer array: \n");
    scanf("%d",&size);

    int* array =(int* ) malloc(size*sizeof(int));
    if (array)
    {
        for (int i=0; i<size; i++)
        {
            printf("Enter the array entry number %d: ",i);
            scanf("%d",&array[i]);
        }

        printf("Printing the array entries...\n");
        for (int j=0; j<size; j++)
        {
            printf("The entry %d is %d \n",j, array[j]);
        }

    }
    free(array);
    array=NULL;

    return 0;

}

Solution of Problem 2

The code given below solves the second problem.

#include<stdlib.h>
#include <stdio.h>
#define MAX_SIZE 255
int main()
{
    
    int array[MAX_SIZE]={0};
    unsigned int counter=0;

    printf("Enter integers to fill-in the array (max number of entries is %d)\n",MAX_SIZE);
    printf("Enter -1 to complete the entry. \n");
    printf(": \n");
    scanf("%d",&array[counter]);
    
    while(array[counter]!=-1 && counter<MAX_SIZE)
    {
        scanf("%d",&array[counter+1]);
        counter++;
    }
    
    counter=0;
    while(array[counter]!=-1)
    {
        printf("The entry %d is %d \n",counter, array[counter]);
        counter++;
    }
    return 0;
}