Home » C++ programs

C++ program to find first occurrence of a Number Using Recursion in an array

Here, we are implementing a C++ program, that will be used to find the first occurrence of a number in an array.
Submitted by Indrajeet Das, on December 09, 2018

Given an array of length N and an integer x, you need to find and return the first index of integer x present in the array. Return -1 if it is not present in the array. First index means, the index of first occurrence of x in the input array. Do this recursively. Indexing in the array starts from 0.

Input Format:

  • Line 1 : An Integer N i.e. size of array
  • Line 2 : N integers which are elements of the array, separated by spaces
  • Line 3 : Integer x

Output Format: first index or -1

Constraints: 1 <= N <= 10^3

Example

    Input:
    4
    9 8 10 8
    8

    Output:
    1

Description:

Here, we have to find the first occurrence of x. Therefore in this example the first occurrence of 8 happens in index 1, and hence the output is 1.

Algorithm:

Step 1: To solve this using recursion, make a recursion function with inputs, and a variable currIndex to traverse the input array.

Step 2: Base Case: If currIndex == size of the input array, return -1, i.e element not found.

Step 3: If x == input[currIndex], then return currIndex.

Step 4: else return the next call of recursive function with currIndex incremented.

C++ Source Code/Function:

#include<bits/stdc++.h>

using namespace std;

int firstIndex(int input[], int size, int x, int currIndex){
    if(size==currIndex){
        return -1;
    }

    if(input[currIndex] == x){
        return currIndex;
    }

    return firstIndex(input,size,x,currIndex+1);
    
}

int main(){
    int input[] = {9,8,10,8};
    int x = 8;
    int size = 4;

    cout<<firstIndex(input,size,x,0);

    return 0;
}

Output

1


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.