Given an array, find first and last elements of it.
CPP
CPP
CPP
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:
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.
First element: 4 Last element: 98
// 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:
In case of vectors in C++, there are functions like front and back to find first and last elements.
First element: 4 Last element: 98
// 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:
We can use front and back even when vector is passed as a parameter.v.front() is now 4 v.back() is now 98