Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to end a loop early in C?

Tags:

c

loops

I have a basic C program that produces a number and the user has to guess it (yup, you've already called it: homework). I am able to get pretty much all of it so I am kinda proud, but I open to any errors I have made of course I am still learning. My main two questions are

  1. How can I end this program early once the user has selected the correct number, before it has reached the #10 of tries? And
  2. Any obvious errors a guru can see that I'm not with my code?

I am trying to program as best as I can :)

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;
}
like image 614
Zach Smith Avatar asked Oct 02 '09 01:10

Zach Smith


1 Answers

Here are three possibilities. Read about them!!! (goto considered harmful)

 if (guess == target)
 {
     printf("You win! \n\n");
     break;
 }

 if (guess == target)
 {
     printf("You win! \n\n");
     goto end;
 }


 if (guess == target)
 {
     printf("You win! \n\n");
     i=n;
 }
like image 169
Tom Avatar answered Nov 05 '22 11:11

Tom