Here, we discuss how we find the last element of an array using C++.
CODE
#include<iostream>
using namespace std;
int main(){
int arr[]={5,6,7,8,9}
int size = sizeof(arr) / sizeof(arr[0]);
int lastElement = arr[size - 1];
cout<<"The last element of the array is: "<<lastElement<<endl;
return 0;
}
OUTPUT
The last element of the array is: 9
EXPLANATION
The explanation of the above code id given below:
We first include the necessary header file iostream for input/output operations. We then define an array with some initial values. And then we calculate the size of the array using the formula sizeof(arr) / sizeof(arr[0]). This work because sizeof(arr) gives the total size of the array in bytes, and sizeof(arr[0]) gives the size of a single element in bytes. Dividing these two values give us the number of the elements in the array. We access the last element of the array using the index size -1. Arrays in C++ are zero-indexed, so the last element’s index is always one less than the size of the array. And then we print the last element using cout.