c++ program to get the last element of array | c++ programs

Get the last element from an Array, c++ code

#include < iostream >
#include < vector >
int main() {
/**
* first find the size of an array using sizeof()
*
* size of an array, s = sizeof(array) in bytes.
* find out the size of first element, sof = sizeof(array[0])
*
* find out the total number of elements, N = s / sof
*
* index of last item in array, iol = N - 1 <-- it is the index of last element */ 
// s=20 bytes // sof=4 bytes
// N=5 // iol=4 
int nArray[]={1, 2, 3, 4, 9};
std::cout << 
nArray[sizeof(nArray)/sizeof(nArray[0]) - 1];
return 0; 
}

Share this Post

Leave a Reply

Your email address will not be published. Required fields are marked *