Need a project done?

C++ Programming Developer

Search This Blog

Recursive function to search through array

Recursive function to search through array.

Write a program that asks the user to enter 10 integers, stores these numbers in an array. The program should ask if the user would like to search an element in the array, in which case the program should then prompt the user to enter the number to look for. Use a recursive function find( int index, int target, int array[] ) that does sequential search for a target in this array. Display an appropriate message to the user after searching the element.

Solution:

#include <iostream>
using namespace std;

void find( int index, int target, int array[] );

int main()
{
cout << "Enter 10 integers seperated by spaces: ";
int array[10];
for (int i = 0; i<10; i++)
cin>>array[i];
cin.ignore();
cout << "Do you like to search an element in the array? ";
char a[4];
cin.getline(a,4,'\n');

if ((a[0] == 'y') | (a[0] == 'Y'))
{
cout << "Enter a number to search from the array: ";
int target;
cin >> target;
find(0,target,array);
}
else{
cout << " Ok, have a nice Day!" <<endl;}

return 0;
}

void find( int index, int target, int array[] )
{
if ( (index) >= 10 )
cout << target << " not found in array." << endl;
else
{
if (array[index] != target)
find(index+1,target,array);
else
cout << target << " Found." << endl;
}
}
"Don't let anyone ever make you feel like you don't deserve what you want."