Click here to Skip to main content
15,895,084 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
as described below.
First, the user is requested to enter a number between 1 and 1024. A user defined function
should validate the user’s input value. If the value is not between 1 and 1024, then an error
message should be displayed.
Second, a recursive function searches the user input value in a systematic method and
prints all the guess values during the process. The recursive function find the number as
shown below with its guess values.
Assume user enters 625. Then the programme print its guess values while searching for the
user’s input value as shown below.
1024,
512,
768,
640,
576,
608,
624,
632,
628,
626,
625

Assume user enters 300. Then the programme print its guess values while searching for the
user’s input value as shown below.
1024,
512,
256,
384,
320,
288,
304,
296,
300

What I have tried:

#include <iostream>
#include <math.h>
int search(int num);
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int sum=0;
int main(int argc, char** argv) {
	int x;
	cout <<"enter number between 0 to 1024 ";
	cin>>x;
	search(x);
	
	return 0;
}
int search(int num){
	int p=num;
	if(sum!=num){
		for(int i=0;i<100;i++){
			if(sum<num){
			sum=1024/2*pow(2,i)+sum;
			cout<<sum<<endl;
		}else{
			sum=1024/(2*pow(2,i))-sum;
			cout<<sum<<endl;
		}
		
		
	}return search(sum);
}else{
	return 1;
}
}
Posted
Updated 17-Sep-18 4:54am

This is an example of binary search algorithm in which you take the maximum and minimum value and go to halfway point. If the value is still larger than the value to be searched then, the minimum becomes halfway and less than halfway, the maximum becomes halfway.
You should try it it is fun and there is this recursion thing to twist it a little bit. But in the end it is just recursion and some if else.
 
Share this answer
 
It's a simple binary chop: Binary search algorithm - Wikipedia[^] - one of the most basic ways of "narrowing in" on a unknown value in a range.
You start with the max and min possible values, and you guess halfway between them.
If the value is greater then halfway, the minimum becomes halfway.
If it is the same, you found it.
if it is less than halfway, the maximum becomes halfway
Repeat until found.

The twist here is that your homework requires it to be recursive (which is a pretty bad example of recursion, but hey! That's homework for you!)

And I'd add a test to your code to check the user input is in range...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900