how to access last element of array c++ code example

Example 1: find last element of an array c++

int arr={1,2,3,4,5,6};
int length=sizeof(arr)/sizeof(int);
int lastElement=aar[length-1];

Example 2: get the last element of an array c++

// C++ Program to print first and last element in an array
#include <iostream>
using namespace std;
int main()
{
	int arr[] = { 4, 5, 7, 13, 25, 65, 98 };
	int f, l, n;
	n = sizeof(arr) / sizeof(arr[0]);
	f = arr[0];
	l = arr[n - 1];
	cout << "First element: " << f << endl;
	cout << "Last element: " << l << endl;
	return 0;
}

Tags:

Cpp Example