tags:

views:

468

answers:

6

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;
}
+10  A: 

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;
}
Andrew Hare
You shouldn't post complete modified programs in response to homework questions. Even if the poster learns the material without applying the answer given, the poster could still get in trouble for someone having shown them a complete answer.
Novelocrat
@Novelocrat - Point taken :)
Andrew Hare
+6  A: 

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!

Nathan Taylor
A: 

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.

Carsten
I very much dislike using `exit()` to exit the program; I'd personally reserve its use for fatal errors. In this example it's trivial to use 'break' instead, or change the while condition as has also been suggested.
Twisol
+7  A: 

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

 ...}while(i < x || guess !== target);
Anthony
It would be better to use break since the intent of the code would be more apparent.
Dana Robinson
You think so? I think ending it on the while is more apparent. It's like saying "I'll keep asking until you either get it right or run out of chances". Having a break makes it seem like an error has occurred or something more important needs attention...
Anthony
I would disagree. In this case it can be seen entering the loop when it will end. Using break, one has to read to go through the code to know that.
jd
Break statements have a tendency to obscure the terminating logic of a loop. Imagine trying to deduce all of the logic of a very large loop with a break statements scattered throughout versus one where the end logic can be found either right at the top or bottom (depending on the type of loop).
Nathan Taylor
+6  A: 

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;
 }
Tom
And in some contexts `return some_value;` too.
dmckee
+1  A: 

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").

DVK