How to find the last index of an integer in an array in C++

In this tutorial, we will write a program to find the last index of an integer in an array in C++. There are different ways to write code to a problem, To find the last index of a number we use the concept of recursion here. Recursion is calling the function itself. In the recursion process, we break the problem into two parts. One part we have to take care of and do some calculations and the other part recursion will check.

Program to find the last index in an array in C++

To find the last tutorial we use iostream header file. Then we initialize an array and name it and declare some integers. We need to find the size of the array to proceed further. So to find the size of the array we use the sizeof function. And we have to ask the user to enter the target element to find out in that array. After entering the target element, we have to check where is the last time the element is found. For that, we create the function and pass the values of (newarray,sizeofarray-1, targetelement). Also, we have to check whether the last element is equal to recursion or not. If equal then we have to return (sizeofarray-1). If not, call the recursive function by passing an array as (newarray,sizeofarray-1,x), where x is the target element.

#include<iostream>
using namespace std;
int lastindex(int newarray[],int targetelement,int sizeofarray){
    if(targetelement==newarray[sizeofarray-1])
        return sizeofarray-1;
    if(sizeofarray==0)
        return -1;
    return lastindex(newarray,targetelement,sizeofarray-1);
}
int main(){
    int newarray[]={5,2,3,0,4,5};
    int sizeofarray= sizeof(newarray)/sizeof(newarray[0]);
    int targetelement;
    cin>>targetelement;
    int answer = lastindex(newarray,targetelement,sizeofarray);
    if(answer==-1)
        cout<<"-1"<<endl;
    else
        cout<<answer;
}

In the above code if the input value of the target is 5 then the output value of the last index is 5.

Input Value of target element is 5, then

TheĀ  output of the code:

5

Leave a Reply

Your email address will not be published. Required fields are marked *