Get The Last Element Of Array In C++
Code snippet for how to Get The Last Element Of Array In C++ with sample and detail explanation
Navigating and manipulating arrays efficiently is an essential skill in C++ programming. One may often need to access the last element of an array for a variety of operations. This article outlines a simple line of code that can be used to access the last element of an array in C++ and explains how it works.
Code Snippet: Accessing Last Element of an Array in C++
#include<iostream>
using namespace std;
int main()
{
int arr[] = {1, 2, 3, 4, 5};
int last_element = arr[sizeof(arr)/sizeof(*arr) - 1];
cout<<"Last element of array is: "<<last_element<<endl;
return 0;
}
Code Explanation: Accessing Last Element of an Array in C++
The code snippet above demonstrates a simple, effective, and immediate way of accessing the last element of an array in C++. Let’s break down how this works:
-
We start by declaring and initializing the array ‘arr’ with integers from 1 to 5.
int arr[] = {1, 2, 3, 4, 5};
-
We then declare a variable ‘last_element’ to store the value of the last element of the array.
-
To get the last element, we use the expression
sizeof(arr) / sizeof(*arr) - 1
.The sizeof operator gives the total size of the array in bytes. It functions by dividing the total size of the array (using
sizeof(arr)
) by the size of one element in the array (usingsizeof(*arr)
). The result is exactly the number of elements in the array. The ‘-1’ at the end deducts one to give the last index since array in C++ starts with 0. -
The calculated index is then used to access the element from the array.
int last_element = arr[sizeof(arr)/sizeof(*arr) - 1];
-
Finally, we print the value of ‘last_element’ using the cout function.
cout<<"Last element of array is: "<<last_element<<endl;
-
Thus, this program displays: “Last element of array is: 5”
So, the above-mentioned C++ code provides a handy method for accessing the last element of an array, regardless of the array’s size.