While loop help

Hello. I need some ideas regarding this exercise I have.

1.Program asks user to enter a random number between 0-100 and limit the region as shown in code.
2. After entering number, program should execute two counting methods : from 0-50 and from 50-100 and check if number lies in those bounded regions.
3. If number lies in one of the regions, program should ask if user wants to further limit the region; e.g program scans from 1-10 with a while loop to check if number lies there, 11-20 etc etc.

I really cannot think of a working code or method to this. I am still a beginner in C++. If anyone could guide me with a way to go about that, that would be great. PLease forgive me if it is not a very efficient code but Im just doing this for an exercise.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
 #include<iostream>

using namespace std;

int main() {
	int number;
	char ask; //either yes or no

	cout << "enter a number" << endl;
	cin >> number;

	if (number == 0) {
		cout << "number is 0" << endl;
	}
	else if (number == 50) {
		cout << "number is 50" << endl;
	}
	else if (number > 50 && number <=100) {
		cout << "number is between 50 and 100" << endl;
	}
	else if (number > 0 && number <50) {
		cout << "number is between 0 and 50" << endl;
	}

	cout << "continue limiting range? [y/n]" << endl;
	cin >> ask;


	if (ask = 'y' && number<50 && number>0) {
		if (number <= 10) {
			while()//what is the best way to do a while loop to search?
		}
	}

	

}
Last edited on
A recursive function that squeezes user input into ever tightening ranges framed by the upper and lower boundaries:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>

void numberBound(int lowerBound, int upperBound)
{
    int number{};
    do
    {
        std::cout << "Enter number b/w " << lowerBound << " and " << upperBound <<": ";
        std::cin >> number;

    } while ((number < lowerBound) || (number > upperBound));
    //additional input validations above
    if (number == lowerBound || number == upperBound)
    {
        std::cout << "Boundary hit \n"; return;
    }
    else
    {
        number < (lowerBound + upperBound)/2 ? upperBound = (lowerBound + upperBound)/2
                                            : lowerBound = (lowerBound + upperBound) / 2;
        //integer division - can choose whether to round up or round down

        numberBound(lowerBound, upperBound);
        //program should also set the max num of tries at each stage or globally ...
        // ...  or else user may keep entering invalid nos indefinitely
    }
}

int main()
{
  numberBound(0, 100);

}
Last edited on
Topic archived. No new replies allowed.