How to find first index of an integer in an array in C++

In this tutorial, you will learn how to write a program to find the first index of a number in an array in C++. The first index of a number is the index value when the number appears for the first time in an array. To find the first index we use recursive functions. Finally, we return the value of the first index, and then we can find the value of the first index.

Program to the first index of an integer in C++

We can find the first index of a number in an array by using recursive functions. First, we initialize an array with value 5,2,3,3,4,4. And to find the size of the array we use sizeof(). And we ask the user to enter the target value to find out. Then create a function and pass the values of the array, the size of the array, and the target value.

In the function, after passing the elements we have to write the code to find the target element. We have to check whether the first element is equal to the target element. If it is equal then return 0. If not call the recursion passing array as (array+1,size-1,x) and then find the index and we can return the first index of integer.

#include<iostream>
using namespace std;
int firstindex(int array[],int target,int arraysize){
if(target==array[0])
return 0;
if(arraysize==0)
return -1;
return firstindex(array+1,target,arraysize-1)+1;
}
int main(){
int array[]={5,2,3,3,4,4};
int arraysize= sizeof(array)/sizeof(array[0]); // gives the array size.
int target;   //Enter the number to find out the index
cin>>target;
int ans = firstindex(array,target,arraysize);
if(ans==-1)
cout<<"-1"<<endl;
else
cout<<ans;
}
The output of the code:
3
2

Leave a Reply

Your email address will not be published.