Question

c++ please. Write a recursive method that takes the following parameters: * a sorted array of...

c++ please.

Write a recursive method that takes the following parameters:

* a sorted array of ints
* an int representing the size of the array
* an int representing a value to be searched for

Your function should return a bool. If the element is in the array, return true. Otherwise, return false. Your function should never produce memory access errors, regardless of the size of the array.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

C++ CODE :

#include <iostream>
using namespace std;

bool func(int a[], int n, int num)
{
if (a[n] == num)
{
return true; // return true if they found element
}
else if (n == -1)
{
return false; // return false if nothing found
}
else
{
return func(a, n - 1, num); // recursion function
}
}

int main()
{
int n, num;
cout <<"Enter the size of array : ";
cin >> n; // read the size of array
  
int a[n];
cout <<"\nEnter the elements of array : ";
for(int i = 0; i < n; i++)
{
cin >> a[i]; // read array of elements
}
  
cout <<"\nEnter the element to search in array : ";
cin >> num; // read the element to be searched
  
if(func(a, n, num)) // call function
{
cout << "\nTrue"; // if element found
}
else
{
cout << "\nFalse"; // if element not found
}
  
return 0;
}

OUTPUT :

Enter the size of array : 5 Enter the elements of array : 1 2 3 4 5 Enter the element to search in array : 3 True ... Program

Add a comment
Know the answer?
Add Answer to:
c++ please. Write a recursive method that takes the following parameters: * a sorted array of...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT