Working dice challenge with looping!

+2 Mattheus Lee · August 27, 2014
Hey,
I managed to program a code that would allow the user to keep playing the game as long as they guessed correctly, and keeping track of their score as they went along. Tell me what you guys think! (:


#include <stdio.h>

int main(void)
{
    int dice1, dice2, dice3, dicetotal, i, wins=0;
    char guess[5];

    printf("Welcome to the dice guessing game!\n");

    dice1=((rand()%6)+1);
    dice2=((rand()%6)+1);
    dice3=((rand()%6)+1);
    dicetotal=dice1+dice2+dice3;
    printf("\nThe three dice rolls are %d, %d and %d for a total of %d.\n", dice1, dice2, dice3, dicetotal);

    while (1<2) //A little bit embarrased about the condition, but I need something there so it'll loop.
    {
        printf("Do you think the next dice roll will be higher, lower, or the same? h/l/s: ");
        scanf("%s", &guess);
        i=dicetotal;

        dice1=((rand()%6)+1);
        dice2=((rand()%6)+1);
        dice3=((rand()%6)+1);
        dicetotal=dice1+dice2+dice3;
        printf("\nThe three dice rolls are %d, %d and %d for a total of %d.\n", dice1, dice2, dice3,dicetotal);

        if (dicetotal>i && guess[0]=='h')
            {printf("\nCongratulations you guessed right! Let's play again.\n");
            wins++;}
        else if (dicetotal<i && guess[0]=='l')
                {printf("\nCongratulations you guessed right! Let's play again.\n");
                wins++;}
             else if (dicetotal==i && guess[0]=='s')
                    {printf("\nCongratulations you guessed right! Let's play again.\n");
                    wins++;}
                  else
                    {printf("You got it right %d times. Try again next time!\n", wins);
                    break;}
    }
    return 0;
}




Post a Reply

Replies

Oldest  Newest  Rating
+2 Bucky Roberts · August 27, 2014
Awesome. Also, you can just use...
while(1)

...to create an infinite loop (this will cause the loop to keep repeating until it comes across a break)
+1 Mattheus Lee · August 27, 2014
ah right, thanks! that looks way more elegant too. (:
+1 Yujin D. Great · August 31, 2014
you don't need to add the ampersand (&) sign in your code here


scanf("%s", &guess);
  • 1

C

107,243 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator