Q:

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

belongs to collection: C++ programs on various topics

0

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

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ programs on various topics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C++ program to print all subsequences of a String... >>
<< C++ program to Convert Roman Number to Integer Num...