Get first and last elements from Array and Vector in CPP

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.