Ryan
Ryan

Reputation: 57

Do While or while?

I am trying to make my program run only while the user enters Y or y but it only runs once, and even if it isn't Y or y. Input will either be Y, y, N or n

printf("Welcome to the Jumble Puzzle Solver!\n\n");
printf("Would you like to enter a jumbled word?\n");
scanf("%s", &answer);


    do{

    printf("What word would you like scored?\n");
    scanf("%s", &letters);

    strcpy(changeletters, letters);

    recursivepermute(letters, changeletters, checkword, k, dictionary ,max, min);

    printf("Would you like to enter a jumbled word?\n");
    scanf("%s", &answer);

    }while (answer == 'Y' || answer == 'y');

Upvotes: 1

Views: 1289

Answers (2)

yohannist
yohannist

Reputation: 4204

if you want the user to play the game once and then be asked about playing again then the use of do-while loop is more appropriate. But if you want to give the user the option Not to play the game at all then use the while loop

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564413

do { } while() causes the body to always be executed at least once. If you want the condition checked first, just use while:

// If answer is:
// char answer;

scanf("%c", &answer);
while (answer == 'Y' || answer == 'y')
{
     printf("What word would you like scored?\n");
    // ...

    scanf("%c", &answer);
}

You also need to use scanf("%c" if answer is a char. The %s is to scan a string of characters (ie: char[20]), and would need to be checked differently, using a method like strcmp or similar.

Upvotes: 1

Related Questions