The Wayback Machine - https://web.archive.org/web/20240204104421/https://www.geeksforgeeks.org/get-first-and-last-elements-from-array-and-vector-in-cpp/
Open In App
Related Articles

Get first and last elements from Array and Vector in CPP

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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

We should not sizeof when arrays are passed as parameters, there we must pass size and use that size to find first and last elements.




// 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.


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!


Last Updated : 10 Nov, 2018
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads