KevD97
KevD97

Reputation: 1

Guess the number game in c where it doesn't count the same guess twice

I'm working on a code that involves the user guessing a number between 1 and 20, however it counts every guess, including numbers repeated. How can I edit it so it only counts each number guessed once? Here's what I have so far:

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

int main(void)
{
    srand(time(NULL));
    int r = rand() %20 + 1;
    int guess; 
    int correct = 0;
    int count = 0;

    printf("Let's play a number guessing game!\n");
    printf("Guess a number between 1 and 20.\n");


    do
    {
        scanf("%d", &guess);

        if (guess == r)
        {
            count++;
            printf("Congrats! you guessed the right answer in %d attempts!\n", count);
            correct = 1;
        }

        if (guess < r)
        {
            count++;
            printf("Too low, try again.\n");
        }

        if (guess > r)
        {
            count++;
            printf("Too high, try again.\n");
        }
    }
    while (correct == 0);

    return 0;
}   

Upvotes: 0

Views: 60

Answers (1)

David Ranieri
David Ranieri

Reputation: 41017

You can use a lookup table to detect if a number is repeated:

int used[21] = {0};

do
{
    scanf("%d", &guess)
    if (guess < 1 || guess > 20) {
        puts("pssst ... from 1 to 20");
        continue;
    }
    if (used[guess] == 1) {
        puts("Repeated!");
        continue; /* without counting */
    } else {
        used[guess] = 1;
    }
    ...

Upvotes: 1

Related Questions