guessing from a list of numbers

Okay, I need help for another problem:

Write a program that picks a number between 1 and 100, and then lets the user guess what the
number is. The program should tell the user if their guess is too high, too low, or just right.

How do I get it to pick the number and tell the user if he/she guessed right or not?

Edit: This is what I have right now:

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
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int randRange(int low, int high);

int main()
{
    int guess;
    srand(time(NULL));
    rand();
    cout << "Guess a number between one and one-hundred: ";
    cin >> guess;
    for (int i = 0; i < 100; i++)
    {
        randRange(1, 100);
    }
}

int randRange(int low, int high)
{
    return rand() % (high - low) + low;
}


So yeah, how do I get it to pick a number, in the first place?
Last edited on
You use if statements. If guess is lower than the random number, then print out its too low, and vice versa.

Edit :
I'll give you a code snippet.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int num, guess, tries = 0;
	srand(time(NULL)); //seed random number generator
	num = rand() % 100 + 1; // random number between 1 and 100

	cout << "Guess My Number Game\n\n";
	
	do
	{
		cout << "Enter a guess between 1 and 100 : ";
		cin >> guess;

		if (guess > num)
			cout << "Too high!\n\n";
		else if (guess < num)
			cout << "Too low!\n\n";
		
	} while (guess != num);


Last edited on
Ah, thanks. That'll work.

I'll do that.

I also had to make a program that would check if a list is sorted or not, and sort if it's not. I wrote the program and it works, but I'd like to know if there's a better way of doing it.

Here is the code:

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
#include <iostream>
#include <algorithm>
#include <array>

using namespace std;

int main()
{
    array<int, 20> number_list {63, 20, 19, 3, 1, 89, 14, 400, 18, 78, 64, 12, 56, 45, 40, 35, 800, 5, 2, 52};
    if (!is_sorted(number_list.begin(), number_list.end()))
    {
        cout << "Unsorted Array:\n";
        for (int i = 0; i < 20; i++)
        {
            cout << number_list[i] << "\n";
        }

        cout << "\n";
        sort(number_list.begin(), number_list.end());
        if (is_sorted(number_list.begin(), number_list.end()))
        {
            cout << "Sorted Array:\n";
            for (int i = 0; i < 20; i++)
            {
                cout << number_list[i] << "\n";
            }
            cout << "\n";
        }
    }
}
Topic archived. No new replies allowed.