Jump to content

Check out our Community Blogs

Register and join over 40,000 other developers!

Recent Status Updates

View All Updates

- - - - -

Need While Loop Help


  • Please log in to reply
3 replies to this topic

#1 shampaynes


    CC Lurker

  • Just Joined
  • Pip
  • 4 posts

Posted 25 February 2008 - 08:53 PM

I created a guessing game but I just can't figure out why it won't repeat when I say yes to playing again.

#include <stdio.h>

void ignore_to_end_of_line(void)
char ignored;
while (ignored!='\n');

bool GuessAgain(char* prompt)
char play;
printf("%s (y/n)? ", prompt);
scanf("%c", &play);

switch (play)
case 'y': case 'Y':
return true;
case 'n': case 'N':
return false;
printf("Try Again");

return false;
int main (void)

printf("I'm thinking of a number between 1 and 100\n");

int number;
for (number=1;number==1;++number)
printf("Your guess:");
if (number<=20)
printf("Too low\n");
else if (number>=21 && number<=39)
printf("Too high\n");
else if (number>=40)
printf("Almost there\n");
else if (number==53)
printf("Congrats you guessed my number\n");


while(GuessAgain("Guess Again"));

return 0;

  • 0

#2 v0id



  • Retired Mod
  • PipPipPipPipPipPipPipPip
  • 2313 posts

Posted 25 February 2008 - 09:46 PM

Your problem is your for-loop. Look at how it's constructed. You set "number" to be 1, and say that the for-loop shall only run while "number" is 1, but at the same time you're increasing "number", so it naturally only run through the loop one time.

Also, it's a really strange place you've put your while loop.

I think you shall read more about both for- and while-loops.
  • 0
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#3 Rothzael


    CC Regular

  • Just Joined
  • PipPipPip
  • 25 posts

Posted 26 February 2008 - 05:29 AM

Instead of the for loop, try:
while(1) {
     /*** guess and check code ***/
    if(GuessAgain("Guess Again")) { continue; }
    else { break; }

  • 0

#4 Chinmoy


    CC Addict

  • Just Joined
  • PipPipPipPipPip
  • 365 posts

Posted 02 March 2008 - 02:22 AM

in your case checks you are checking for the same response 'Y' for both affirmations.one of the 'Y' 's should probably be 'y'.hope you dont work with your keyboard in uppercase or else you would have got the return true.
change the 'Y' to 'y' and check.
  • 0

Also tagged with one or more of these keywords: loop

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download