Program to Read, Access and Display Elements of One Dimensional Array

#include <stdio.h>

int main() {
int n;

// Step 1: Read the size of the array
printf(“Enter the number of elements in the array: “);
scanf(“%d”, &n);

int arr[n]; // Declare the array with user-defined size

// Step 2: Read the elements of the array
printf(“Enter %d elements:”, n);
for (int i = 0; i < n; i++) {
printf(“Element [%d]: “, i);
scanf(“%d”, &arr[i]);
}

// Step 3: Display the elements of the array
printf(“\nThe elements of the array are:\n”);
for (int i = 0; i < n; i++) {
printf(“Element at index [%d]: %d\n”, i, arr[i]);
}

return 0;
}

Explanation of the Program

  1. Read Array Size:
    • The user specifies the size of the array, which is stored in the variable n.
  2. Read Array Elements:
    • A loop (for loop) is used to input n elements into the array arr.
  3. Display Array Elements:
    • Another loop is used to iterate through the array and display each element with its corresponding index.

Sample Input/Output

Input:

Enter the number of elements in the array: 5
Enter 5 elements:
Element [0]: 10
Element [1]: 20
Element [2]: 30
Element [3]: 40
Element [4]: 50

Output:

The elements of the array are:
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

Leave a Comment

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