C - Reading and Displaying Elements of a 1D Array

To read and display elements of a one-dimensional (1D) array in C, you can use a loop to iterate through the array and print each element. Here's a C program that demonstrates how to do this:


#include <stdio.h>

int main() {
    // Declare and initialize a one-dimensional integer array with 5 elements.
    int numbers[5] = {10, 20, 30, 40, 50};

    // Use a loop to read and display each element of the array.
    printf("Elements of the array:\n");
    for (int i = 0; i < 5; i++) {
        printf("Element at index %d: %d\n", i, numbers[i]);
    }

    return 0;
}
    

Explanation:

  1. We declare and initialize a one-dimensional integer array named numbers with 5 elements.
  2. We use a for loop to iterate through the array. The loop variable i represents the index of each element.
  3. Inside the loop, we use printf to display each element along with its index. The format string %d is used to print integers.
  4. The loop runs from i = 0 (the index of the first element) to i = 4 (the index of the last element) to cover all elements in the array.
  5. The program prints the elements one by one, including their indices.

When you run this program, it will read and display the elements of the 1D array as follows:


Elements of the array:
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50
    

This demonstrates how to read and display the elements of a 1D array in C using a loop.