Home / Programs / Write a c program for Accessing an element
🚀 Programming Example

Write a c program for Accessing an element

👁 196 Views
💻 Practical Program
📘 Step Learning

Write a c program for Accessing an element

📌 Information & Algorithm

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 Code

#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;
}

                        

📘 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.

📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

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.

🔥 Practice suggestion

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.