Zach Smith
Zach Smith

Reputation: 5704

How to end a loop early in C?

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;
}

Upvotes: 12

Views: 114324

Answers (6)

DVK
DVK

Reputation: 129559

I do not see any "obvious errors" that previous posters did not mention, other than the fact that, with the break, you no longer need both "i" and "numGuess" as they would always have the same value. Just use numGuess instead of "i" in the while's condition.

But I would like to highly recommend you to make your code more readable - the best time to get into the habit of good coding style is now, before you acquire and solidify bad habits.

  • Always use self-describing identifyers (variable/function names). E.g. your "x" should really be called "maxGuesses".

  • Don't skimp on white space. E.g. "}while(i < x);" should be "} while (i < x);"

  • You seem to have already gotten into the habit of not skimping on comments - good!!!

    Just remember that the comments should always describe the purpose behind what the code does instead of the mechanics of how it does it unless the mechanics is so tricky and clever that it also needs explanation.

The reason that this is important is two-fold:

  • 80-90% of development time/efforts are usually spent on maintaining existing code, your own or someone else's. That task is VASTLY easier with well documented and easily readable code. (you have no idea how much brain damage someone can sustain from reading unfamiliar code at 2am during production problem just because the bozo who wrote it didn't indent the code consistently).

  • Having well documented and readable code makes it easier for you to write it, since it clarifies your own thoughts and discourages stupid typo-originated bugs ("oups, i meant to use x instead of y").

Upvotes: 1

Tom
Tom

Reputation: 45174

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;
 }

Upvotes: 10

Anthony
Anthony

Reputation: 37085

Why not set the while condition to the user's guess? Something like:

 ...}while(i < x || guess !== target);

Upvotes: 9

Nathan Taylor
Nathan Taylor

Reputation: 24606

You are looking for the break command.

for (int i = 0; i < 10; i++) {
    if(i == 5)
       break;
}

This resource looks like it would be very helpful to you.

As a side note: your "You lose" text will always be displayed no matter what. You may want to evaluate that inside the do{ } loop.


Always one step ahead of me with the posts/edits on this answer Andrew Hare!

Upvotes: 9

Andrew Hare
Andrew Hare

Reputation: 351748

Use the break statement to hop out of a loop: In this case though that may not be what you want since once you break out of the loop you will instantly see the "you lose" message. You may need to restructure your program to account for this.

Try something like this:

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");
            break;
        }
        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);

    if (guess != target) {
        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;
}

Upvotes: 17

Carsten
Carsten

Reputation: 4334

In the case of your program the best way to achieve this is probably to call

void exit(int status);

(include stdlib.h )

after printing "You Win"

In general you can use the keyword "break" to exit a loop at any time. This does not have the desired effect in your case as it would go on to print "you lose ...." . If you want to use "break" you would have to put an "if" statement around the "you lose ..." bit and check whether the user has not in fact won.

Upvotes: 0

Related Questions