#include<stdlib.h>
#include<stdio.h>
#include<time.h>
int main(void)
{
int x = 10;
int i = 0;
int target, guess;
int numGuess = 0;
/*create a random number*/
//create random function
srand(time(NULL));//this creates new number based on time which changes every second :)
target = rand() % 99; //create a random number using the rand() function, from 0 -99
do{
//increase the loop until it meets the x variable
i++;
numGuess++;
//allow user to input a number for guess
scanf("%d", &guess);
if (guess == target)
{
printf("You win! \n\n");
}
else if (guess > target)
{
printf("You are too high. Guess a number:\n\n");
}
else if (guess < target)
{
printf("You are too low. Guess a number:\n\n");
}
}while(i < x);
printf("You lose, the number was %d. \n", target);
printf("Number of tries %d\n", numGuess);
printf("Enter any key to exit...");
getchar();
getchar();
return 0;
}
How do I end a do/while loop early in C?
Started by zacharyrs, Oct 01 2009 05:05 PM
8 replies to this topic
#1
Posted 01 October 2009 - 05:05 PM
I was able to set a variable and increase it each time to show the number of tries. Yay for me. Anyone know best way of stopping the loop when the user has guessed the number, thus ending the loop before it has reached 10? Any help would be greatly appreciated.
|
|
|
#2
Posted 01 October 2009 - 05:24 PM
break;
#3
Posted 01 October 2009 - 05:47 PM
In your example, you would put the break keyword right after your printf() so it would look like so...
When a break command is encountered, it'll immediately leave the loop and end up at
printf("You win! \n\n");
break;
When a break command is encountered, it'll immediately leave the loop and end up at
printf("You lose, the number was %d. \n", target);
#4
Posted 01 October 2009 - 05:57 PM
If you're unfortunate enough to have to have a switch statement inside a loop, the break statement won't work, though. Moral: don't use switch statements inside loops.
sudo rm -rf /
#5
Posted 02 October 2009 - 05:02 AM
Alternatively, just add that condition to the exit condition.
#6
Posted 02 October 2009 - 12:49 PM
#7
Posted 02 October 2009 - 01:30 PM
He's referring to
which could have been
}while(i < x);
which could have been
}while(i < x || guess == target);
#8
Posted 02 October 2009 - 03:32 PM
#9
Posted 02 October 2009 - 04:09 PM
nah, just got in with my 2 cents kinda late.
tk's right. I find that people tend to be focussed on half of their real exit condition for a loop, and when the detect the other condition don't consider applying it directly where it can be tested.
tk's right. I find that people tend to be focussed on half of their real exit condition for a loop, and when the detect the other condition don't consider applying it directly where it can be tested.


Sign In
Create Account

Back to top









