• Home
  • 5.4 Reading Array Elements from the User

5.4 Reading Array Elements from the User

View Categories

5.4 Reading Array Elements from the User

Table of Contents

Array elements can be populated with user input using scanf(). A loop can read multiple values by accessing each element through its index.

#include <stdio.h>

int main(void)
{
    int numbers[5];

    for (int i = 0; i < 5; i++)
    {
        printf("Enter number %d: ", i + 1);
        scanf("%d", &numbers[i]);
    }

    printf("Array elements: ");

    for (int i = 0; i < 5; i++)
    {
        printf("%d ", numbers[i]);
    }

    printf("\n");

    return 0;
}

Example Output #

Enter number 1: 10
Enter number 2: 20
Enter number 3: 30
Enter number 4: 40
Enter number 5: 50
Array elements: 10 20 30 40 50

Explanation #

The array declaration reserves space for five integer elements:

int numbers[5];

The first loop reads a value for each element:

for (int i = 0; i < 5; i++)
{
    scanf("%d", &numbers[i]);
}

The expression &numbers[i] provides the address of the current element, allowing scanf() to store the input value there.

The second loop prints the stored values:

printf("%d ", numbers[i]);

The index i ranges from 0 to 4, accessing all five elements.

Important: scanf() returns the number of successfully assigned input items. Production code should check this return value before relying on the input.

if (scanf("%d", &numbers[i]) != 1)
{
    printf("Invalid input\n");
    return 1;
}

This check prevents the program from treating an unsuccessful conversion as a valid input value.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *