do....while loop problems

I'm very new to c++, and having alot of issues with a project I have to do. The project is

Write a program in which:
A random integer between 0 and 500 is generated at the beginning.
The user is asked to guess the number.
The user is told whether her/his guess was too high or too low, and asked to guess again, until the guess is correct.

I just cannot get the program to loop. When I run it, I enter a number and it says "Sorry, too low", and then nothing happens.

I'd really appreciate any help as I'm new to this and really want to learn! The code I have so far;


#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
int num, guess;
num = rand() % 500 ;


do{
cout<< "Guess the random number: ";
cin>> guess;}

while (guess < num);
cout<< "Sorry, too low.";

while (guess > num);
cout<< "Sorry, too high.";

while (guess != num);
cout<< "Congratulations, you got it!";

return 0;
}
do while loop doesnt work that way. what your program does is it waits until you enter a number greater than num

1
2
3
4
5
do
{ // do this
    cout<< "Guess the random number: ";
    cin>> guess;
}while (guess < num);// when guess is less than num 


then it says "sorry too low" and then it enters another loop

 
while (guess < num);


it has an empty statement so it does nothing and never reaches the rest of the code.
What you should probably do is in the do while loop make some if statements to check if the number is correct.
Last edited on
ok, so in your opinion, would it be easier with a if else loop? sorry about this, only started with c++ last week as part of my course in uni!
You should put if and elses inside your do while loop

1
2
3
4
5
6
7
8
9
10
11
12
13
do
{ // do this
    cout<< "Guess the random number: ";
    cin>> guess;

    if(guess > num)
   {
        //do something unbelievable
   }
   else if(...)
   {
   }
}while (...);


and btw if and elses arent loops :P
Last edited on
thank you so much, just did what you said and it worked finally, breathing a big sigh of relief, although my random number is always 41!!

Thanks again!! I'll post up the code I ended up with;

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
int num, guess;
num = rand() % 500 ;


do{
cout<< "Guess the random number: ";
cin>> guess;

if (guess<num){
cout<< "Sorry, that is too low."<<endl;}

else if (guess>num){
cout<< "Sorry, that is too high."<<endl;}

}
while (guess !=num);
cout<<"Congratulations, you've got it!"<<endl;

return 0;
}



Topic archived. No new replies allowed.