OneBite.Dev - Coding blog in a bite size

Get The Nth Element Of Array In C++

Code snippet for how to Get The Nth Element Of Array In C++ with sample and detail explanation

Accessing elements within an array is a common task in programming. In C++, obtaining the Nth element of an array involves using a simple syntax along with an understanding of how arrays are indexed.

Code snippet for getting the Nth element of an array

Here’s a simple example of how to access the Nth element of an array in C++:

#include <iostream>
using namespace std;

int main() {
    int array[5] = {1, 2, 3, 4, 5};

    int N;
    cout << "Enter the index to access:" << endl;
    cin >> N;

    if (N >= 0 && N < 5) {
        cout << "The element at index " << N << " is " << array[N] << endl;
    } else {
        cout << "Index out of range." << endl;
    }
    return 0;
}

Code Explanation for getting the Nth element of an array

This code demonstrates how to get the Nth item from an array using C++. Let’s break it down to make it more understandable.

  1. We start with the inclusion directive #include <iostream> which is responsible for input and output stream. It makes sure we can use basic functionalities like ‘cout’, ‘cin’, etc. We then declare the use of the standard namespace by mentioning using namespace std;.

  2. The int main() function is the starting point of our code. This function is called when the program is run.

  3. Inside the main() function, we declare an array array[5] of size 5 and add five elements {1, 2, 3, 4, 5} to the array.

  4. We then declare an integer N that will store the user’s input for the index of the array element they want to access.

  5. We also display a message to the user to enter the desired index, using cout, and then read their input using cin >> N;.

  6. We use an if-else statement to check if the provided index is within the range of the array. If it is within the range, we display the value of the element at that index, using array[N]. Here, N is the index provided by the user.

    If the index provided by the user is out of range (meaning it is less than 0 or greater than or equal to the size of the array), we display an error message of “Index out of range.”

  7. The return 0; is a default statement, which is the convention in C++ to signal to the operating system that the program has executed correctly.

In conclusion, getting the Nth element of an array in C++ involves understanding the indexing of the array and accepting user inputs for the index.

c-plus-plus