Write a c program for Accessing an element

Data Structure / Array

124

Given Input:

array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Enter the index of the element you want to access: 5

Expected Output:

The element at index 5 is 6

Program:

#include <stdio.h>

int main()
{
    int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int index, element;
    
    printf("Enter the index of the element you want to access: ");
    scanf("%d", &index);
    
    /* Check if the entered index is within the array bounds */
    if (index < 0 || index >= 10)
    {
        printf("Invalid index. Array size is 10.\n");
        return 0;
    }
    
    element = array[index];
    printf("The element at index %d is %d\n", index, element);
    
    return 0;
}

Output:


                                        

Explanation:

This program allows the user to enter an index of an element they want to access in an array. The program then checks if the entered index is within the array bounds, and if it is, it prints out the element at that index. If the entered index is not within the array bounds, the program will print an error message and exit.


This Particular section is dedicated to Programs only. If you want learn more about Data Structure. Then you can visit below links to get more depth on this subject.