OneBite.Dev - Coding blog in a bite size

Get The First Element Of Array In C++

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

It is quite common while programming in C++ to come across situations where you need to manipulate, search or access various elements of an array. Let’s talk about the simplest case, to get the first element of an array in C++.

Code snippet to Get The First Element Of Array In C++

Here’s a simple example of how you can get the first element of an array.

#include<iostream>
using namespace std; 

int main() {
    int numbers[] = {5, 10, 15, 20, 25};
    cout << "The first element of the array is: " << numbers[0] << endl; 
    return 0; 
}

Code Explanation for Getting The First Element Of Array In C++

Let’s start off gradually by explaining each line of the code snippet.

  1. #include<iostream>: This line is a preprocessor directive, which tells the compiler to include the iostream library. The iostream library is necessary for input/output operations, such as cout and cin.

  2. using namespace std;: Namespaces are containers for code and can hold functions, classes and variables, typically of a similar type. Using namespace std allows us to use elements in the std namespace without having to prefix std:: to each of them.

  3. int main() {}: This is the starting point of our program. When the program runs, function main() gets invoked first.

  4. Inside the main function, int numbers[] = {5, 10, 15, 20, 25}; is an array declaration and initialization. We are declaring an array of integers named ‘numbers’ and initializing it with five values.

  5. The next line cout << "The first element of the array is: " << numbers[0] << endl; is outputting a message to the console. The cout is used for output, and the << operator is used to send the output to the standard output stream, usually the screen. endl stands for ‘end line’, and adds a newline character. Here, numbers[0] accesses the first element of the array. In C++, arrays are zero-indexed, meaning the first element is stored at index 0.

  6. Finally, return 0; indicates that the program has ended successfully. The return value of the main function is usually an indicator of how the program ended.

With this understanding, you can now implement the concept of getting the first element of an array in C++ in any projects or tasks where you may need it.

c-plus-plus