Write a c program for Accessing an element
Write a c program for Accessing an element
Write a c program for Accessing an element
array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Enter the index of the element you want to access: 5
The element at index 5 is 6
#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;
}
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.
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.