mercredi 11 novembre 2020

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

Aucun commentaire:

Enregistrer un commentaire