Get first and last elements from Array and Vector in CPP

Share Your Love

Suppose, to get first and last elements from array-

Given an array, find first and last elements of it.

Input: {4, 5, 7, 13, 25, 65, 98}
Output: First element: 4
Last element: 98

In C++, we can use sizeof operator to find number of elements in an array.

// 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;
}

Output:

First element: 4
Last element: 98

Generally we shouldn’t passed the sizeof array as parameters in function, so we only pass the array size and get from first and last elements from that array.

// C++ Program to print first and last element in an array
#include <iostream>
using namespace std;

int printFirstLast(int arr[], int n)
{
	int f = arr[0];
	int l = arr[n - 1];
	cout << "First element: " << f << endl;
	cout << "Last element: " << l << endl;
}

int main()
{
	int arr[] = { 4, 5, 7, 13, 25, 65, 98 };
	int n = sizeof(arr) / sizeof(arr[0]);
	printFirstLast(arr, n);
	return 0;
}

Output:

First element: 4
Last element: 98

In case of vectors in C++, there are functions like front and back to find first and last elements.

// C++ Program to find first and last elements in vector
#include <iostream>
#include <vector>
using namespace std;
int main()
{
	vector<int> v;

	v.push_back(4);
	v.push_back(5);
	v.push_back(7);
	v.push_back(13);
	v.push_back(25);
	v.push_back(65);
	v.push_back(98);
	cout << "v.front() is now " << v.front() << '\n';
	cout << "v.back() is now " << v.back() << '\n';
	return 0;
}

Output:

v.front() is now 4
v.back() is now 98

We can use front and back even when vector is passed as a parameter.

If you find this article is helpful, then share us or Interested to publish article then WhatsApp me.

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 429

Newsletter Updates

Enter your email address below to subscribe to our newsletter