1int arr={1,2,3,4,5,6};
2int length=sizeof(arr)/sizeof(int);
3int lastElement=aar[length-1];
1#include<iostream>
2/*To get the last element of the array we first get the size
3 of the array by using sizeof(). Unfortunately, this gives
4 us the size of the array in bytes. To fix this, we divide
5 the size (in bytes) by the size of the data type in the array.
6 In our case, this would be int, so we divide sizeof(array)
7 by sizeof(int). Since arrays start from 0 and not 1 we
8 subtract one to get the last element.
9 -yegor*/
10int array[5] = { 1, 2, 3, 4, 5 };
11printf("Last Element of Array: %d", array[(sizeof(array)/sizeof(int))-1]);
1vector<int> vec;
2vec.push_back(0);
3vec.push_back(1);
4int last_element = vec.back();
5int also_last_element = vec[vec.size() - 1];
6
1// C++ Program to print first and last element in an array
2#include <iostream>
3using namespace std;
4int main()
5{
6 int arr[] = { 4, 5, 7, 13, 25, 65, 98 };
7 int f, l, n;
8 n = sizeof(arr) / sizeof(arr[0]);
9 f = arr[0];
10 l = arr[n - 1];
11 cout << "First element: " << f << endl;
12 cout << "Last element: " << l << endl;
13 return 0;
14}
15
1#include <array>
2std::array<int, 5> a {1, 2, 3, 4, 5};
3int i = a[a.size() - 1]; // The last variable stored in i