How can I restructure this control flow to avoid use of goto?
As a homework assignment for my introductory programming course I have to design and implement a program that generates a random number(1-100), then gives the player 7 guesses to correctly guess the number开发者_运维百科. I've come up with this algorithm:
However, I can't work out how to translate this conceptual representation of the algorithm into control structures. (We're using Pascal, so the structures available are if statements, pre-order loops, and post-order loops). Neither pre-order nor post-order looping fits for the inner loop, as the loop condition is in the middle of the loop and there are two exit points!
Could anybody give me a pointer on how to structure this more clearly?
I don't know Pascal at all, but I do know that it has a while loop...so I would structure it in a manner similar to the following...(written in pseudo-code)
boolean userWishesToPlay = true;
int userGuess = -1;
int ranValue;
int guessCount = 0;
while (userWishesToPlay) {
ranValue = generateRandomValue();
while(userGuess != ranValue && guessCount < 7) {
// Give hint if user has guessed more than once
if (guessCount >= 1) {
// give hint
}
userGuess = // get input from user
guessCount += 1;
}
if (userGuess == ranValue) {
// print congrats!
} else {
// print game over
}
userWishesToPlay = // get input from user on whether to play again or not
userGuess = -1; // since random value will be between 1 and 100 this is safe
guessCount = 0;
}
i will write it out in c style
bool gameover;
int tries = 0;
while(!gameover)
{
game over = (tries > 7);
if(answer == correct)
break;
tries++
}
LINK FOR WHILE LOOP IN PASCAL: http://www.hkbu.edu.hk/~bba_ism/ISM2110/pas024.htm
It looks solid to me. I don't know Pascal, but can't you "break" out of the inner loop? The inner loop is reading the user's guess, showing a hint, and incrementing the count. It also checks two things: the guess is correct, and the count is less than 7. If either are true, it shows an appropriate message and then breaks out of that inner loop, falling into the outer loop where it then asks if the user wants to play again.
精彩评论