Home » C++ programs

C++ program to find presence of a number X in the array recursively

Here, we are implementing a C++ program to find presence of a number X in the array recursively.
Submitted by Indrajeet Das, on December 06, 2018

Given an array of length N and an integer X, you need to find all the indexes where X is present in the input array. Save all the indexes in an array (in increasing order).
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:

    indexes where x is present in the array (separated by space)

Constraints:

    1 <= N <= 10^3

Example:

    Input:
    5
    9 8 10 8 8
    8

    Output:
    1 3 4

Description:

Here, the element we have to find in the array is 8. So, the element 8 present in the array are at indices 1 3 4 which comes out as the output.

Algorithm:

To find the elements using recursion, we call upon a recursive function maintaining an output array, its size and a variable currIndex for traversal of the input array. The base case of this function will be if currIndex is equal to the size of Input array. i.e we have finished traversing the array. On every recursive call, the input element at currIndex is compared with ‘x’, and if it matches is then stored within the output array (and hence incrementing the output array size by 1). Next recursive call is made by incrementing the currIndex.

Source Code/Functions:

#include <bits/stdc++.h>
using namespace std;

void findIndices(int input[], int size, int x, int output[], int &k, int currIndex){
	if(currIndex==size){
		return;
	}
	if(input[currIndex]==x){
		output[k] = currIndex;
		k++;
	}
	findIndices(input,size,x,output,k,++currIndex);
}

int allIndices(int input[], int size, int x, int output[]){
	int k = 0;
	findIndices(input,size,x,output,k,0);
	return k;
}

int main(){
	int size = 5;
	int input[] = {9,8,10,8,8};
	int x = 8;
	int output[5];
	
	int outputSize = allIndices(input,size,x,output);
	for(int i =0;i<outputSize;i++){
		cout<<output[i]<<" ";
	}
	
	return 0;
}

Output

1 3 4


Comments and Discussions!

Load comments ↻





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