In: Computer Science
"Write a function named "firstLast2" that takes as input a vector of integers. The function should return true if the vector starts and ends with the digit 2. Otherwise, it should return false. Test your function with vectors of different length and with the digit 2 at the beginning of the vector, end of the vector, middle of the vector, and missing from the vector."
Additional Requirements:
>Must use a loop allowing the user to continue until he/she quits.
>Read the full name, middle (if there is any) and last name separately.
>Must work even if there is no middle name.
Solution:
#include<iostream>
#include<vector>
#include<stdio.h>
using namespace std;
int main()
{
vector<int> v;
char first[20],middle[20],last[20],choice='y';
bool firstLast2(vector<int>),check;
int i,n,a,check_middle;
cout<<"Enter your First Name:";
scanf("%s",first);
cout<<"Do you have a middle name(Press 1 if
you):";
cin>>check_middle;
if(check_middle==1){
cout<<"Enter your Middle Name:";
scanf("%s",middle);
}
cout<<"Enter your Last Name:";
scanf("%s",last);
while(choice!='n')
{
cout<<"How many elements do
you want to enter:";
cin>>n;
cout<<"Enter
"<<n<<" elements\n";
for(i=0;i<n;i++){
cin>>a;
v.push_back(a);
}
check=firstLast2(v);
if(check_middle==1)
printf("Hey %s
%s %s\n",first,middle,last);
else
printf("Hey %s
%s\n",first,last);
if(check)
cout<<"The
vector starts and ends with two\n";
else
cout<<"The
vector either does not start with two or does not end with
two\n";
cout<<"Do you want to
continue(y/n):";
cin>>choice;
}
return 0;
}
bool firstLast2(vector<int>v)
{
if(v.front()==2 && v.back()==2)
return true;
else
return false;
}
Output:
