Ask Your Question
0

How can I modify my basic C guessing game to use either if/else statements exclusively or a loop?

asked 2022-07-24 11:00:00 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-03-04 13:00:00 +0000

lalupa gravatar image

Using if/else statements exclusively:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {

    srand(time(NULL));
    int num = rand()%10+1;
    int guess;

    printf("Guess a number from 1 to 10\n");
    scanf("%d", &guess);

    if(guess == num) {
        printf("Congratulations, you guessed the number!\n");
    }
    else if(guess > num) {
        printf("Your guess is too high, try again.\n");
        scanf("%d", &guess);
        if(guess == num) {
            printf("Congratulations, you guessed the number!\n");
        }
        else if(guess > num) {
            printf("Your guess is too high, you lose.\n");
        }
        else {
            printf("Your guess is too low, you lose.\n");
        }
    }
    else {
        printf("Your guess is too low, try again.\n");
        scanf("%d", &guess);
        if(guess == num) {
            printf("Congratulations, you guessed the number!\n");
        }
        else if(guess > num) {
            printf("Your guess is too high, you lose.\n");
        }
        else {
            printf("Your guess is too low, you lose.\n");
        }
    }

    return 0;
}

Using a loop:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {

    srand(time(NULL));
    int num = rand()%10+1;
    int guess;

    printf("Guess a number from 1 to 10\n");
    scanf("%d", &guess);

    while(guess != num) {
        if(guess > num) {
            printf("Your guess is too high, try again.\n");
        }
        else {
            printf("Your guess is too low, try again.\n");
        }
        scanf("%d", &guess);
    }

    printf("Congratulations, you guessed the number!\n");

    return 0;
}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-07-24 11:00:00 +0000

Seen: 1 times

Last updated: Mar 04 '22