Aslah P Hussain
Aslah P Hussain

Reputation: 11

Letter guessing game in C using if else statements

I'm new to programming and am trying to do this guessing game by a simple C program below. When I input letters from the word "apple", every letter (p,l,e) executes the wrong guess try again statement except for the letter 'a'. I can't seem to understand what I'm doing wrong here. Any insights is highly appreciated.

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define size 10

int main() {
    // initialize variables
    char word[size] = "apple";
    char guess;
    char arrayofdashes[size] = "_____";
    printf("guess a letter \n");
  
    // input loop
    for (int i = 0; i < strlen(word); i++)
    {
        scanf(" %c", &guess);
        for (int j = 0; j< strlen(word); j++ )
        {
            if (guess == word[j])
            {
                arrayofdashes[j] = guess;
                printf("%s \n", arrayofdashes);

            }
            else
            {
                printf("wrong guess. Try again \n");
                break;
            }
        }
    }
}

Upvotes: 0

Views: 1244

Answers (3)

PuzzledShaw
PuzzledShaw

Reputation: 113

Remove the break and add a flag variable to check the correctness of the input letter. And you need a better way to check if the word spelling is complete.

    char flag;
    int count = 0;
  
    // input loop
    while (count < strlen(word))
    {
        scanf(" %c", &guess);
        flag = 0;
        for (int j = 0; j< strlen(word); j++ )
        {   
            if (guess == word[j] && guess != arrayofdashes[j])
            {
                arrayofdashes[j] = guess;
                count++;
                flag = 1;
            }
        }
        if (flag)
            printf("%s \n", arrayofdashes);
        else
            printf("wrong guess. Try again \n");
    }

Upvotes: 1

BingoYoan
BingoYoan

Reputation: 41

for (int j = 0; j < strlen(word); j++)//no two loop
{
    scanf(" %c", &guess);
    if (guess == word[j])
    {
        arrayofdashes[j] = guess;
        printf("%s \n", arrayofdashes);
    }
    else
    {
        printf("wrong guess. Try again \n");
        j--;
    }
}

You don't need the input loop. And if the answer is not correct you should subtract one from j.

Upvotes: 0

Drew Shafer
Drew Shafer

Reputation: 4802

the problem is that you're using break - this drops out of your inner for-loop after comparing your input against the first character, and prevents it from being compared with subsequent characters.

What strategies have you tried for debugging this yourself? You'll have a few more changes to make aside from removing break, but figuring them out is part of the fun

Upvotes: 0

Related Questions