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
[code]
#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;
}
Your search routine is far too complicated. Pass it: the current value, the intended end value and the increment. All it has to do then is:
- output the current value;
- if the end value is less than current then call it recursively with current-increment, end, increment/2
- if the end value is greater than current then call it recursively with current+increment, end, increment/2.
The first call will have current=1024, increment=512.
You also have no input validation as required by your assignment.