Make a dice rolling game - c

A normal six-sided dice is thrown six times; the user must guess a number each time the dice
is thrown. If the number matches the guess, the user wins a point. Score 4 points to win.
I'm working on a project to make a dice throwing game. The goal is to guess the number that the dice is going to land on, and to repeat this loop until the user chooses to exit the program. Currently I'm just working on getting the inital stage to work, but for some reason my dice is coming up with an extremely large number and due to my limited understanding of srand I don't know how to fix it, so any help would be greatly appreciated
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int runs, correct, correct_guesses, guess;
srand(time(NULL));
correct_guesses = 0;
int roll = ((rand() % 6) + 1);
printf("Please guess the number the dice will land on\n");
printf("%d", &roll);
scanf("%d", &guess);
{
switch (guess)
{
case '1': correct = 1 == roll; break;
case '2': correct = 2 == roll; break;
case '3': correct = 3 == roll; break;
case '4': correct = 4 == roll; break;
case '5': correct = 5 == roll; break;
case '6': correct = 6 == roll; break;
default: correct = 0; printf("Not a possible outcome\n");
}
if (correct)
{
printf("You guessed correctly!\n");
}
else
printf("You guessed incorrectly\n");
}
}

Related

Can't get my code to continue when I enter 'y', it just exits out

It's my first time using switch case statements in my code so I could just be using it wrong in this scenario. I am attempting to make a simple dice roller that lets you roll the dice again.
My code for the dice roll works, but at the end when it asks you if you would like to roll again (y/n)
When I enter y
it just exits out.
`
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define WON 0
#define LOSE 1
int rollDice();
int playGame();
int rollAgain();
int rollDice()
{
return rand() % 6+ 1;
}
int playGame()
{
srand(time(NULL));
int dice_1 = 0;
int dice_2 = 0;
int sum = 0;
int result;
printf("--------------\n");
printf("- HOW TO WIN -\n");
printf("--------------\n");
printf("Your dice roll must equal 7 or 11 or else you lose.\n");
printf("\n");
printf("Want to test your luck? ");
printf("Press ENTER to roll the die\n");
fgetc(stdin);
dice_1 = rollDice();
dice_2 = rollDice();
sum = dice_1 + dice_2;
printf("Dice 1:%2d\nDice 2:%2d\nSum:%2d\n", dice_1, dice_2, sum);
switch ( sum )
{
case 7:
case 11:
result = WON;
break;
case 2:
case 3:
case 4:
case 5:
case 6:
case 8:
case 9:
case 10:
case 12:
result = LOSE;
break;
}
return result;
}
int rollAgain()
{
srand(time(NULL));
int dice_1 = 0;
int dice_2 = 0;
int sum = 0;
int result;
printf("Press ENTER to roll the die\n");
fgetc(stdin);
dice_1 = rollDice();
dice_2 = rollDice();
sum = dice_1 + dice_2;
printf("Dice 1:%2d\nDice 2:%2d\nSum:%2d\n", dice_1, dice_2, sum);
switch ( sum )
{
case 7:
case 11:
result = WON;
break;
case 2:
case 3:
case 4:
case 5:
case 6:
case 8:
case 9:
case 10:
case 12:
result = LOSE;
break;
}
}
int main()
{
char answer;
int result = playGame();
switch ( result )
{
case WON:
printf("You won the game.\n");
printf("Do you wish to play again? (y/n)");
scanf("%c", &answer);
if(answer == 'y' || answer == 'Y');
{
int rollAgain();
}
break;
case LOSE:
printf("You lost the game.\n");
printf("Do you wish to play again?");
scanf("%c", &answer);
if(answer == 'y' || answer == 'Y');
{
int rollAgain();
}
break;
}
return 0;
}
`
How do I get my code to 'roll the dice again'?
Why isn't the if statement working?
is it because I am using a scanf instead of something like fgets?
Like how I used the fgetc for the enter ?
The following code contains two errors:
if(answer == 'y' || answer == 'Y');
{
int rollAgain();
}
The line
if(answer == 'y' || answer == 'Y');
is wrong. The ; at the end of the line is an empty statement, so you are effectively telling the program to "do nothing" when the if condition is true. If you instead want the code block after the if statement to be associated with the if statement, you must remove the empty statement, by removing the ; in the line quoted above.
My gcc compiler warns me of this, when I enable all warnings. You may want to read this question: Why should I always enable compiler warnings?
Also, the line
int rollAgain();
is wrong. That line is a function declaration. If you want it to be a function call instead, you must remove the int from that line.
After fixing these two bugs, which both occur in two places in your program, the function rollAgain is now successfully being called:
--------------
- HOW TO WIN -
--------------
Your dice roll must equal 7 or 11 or else you lose.
Want to test your luck? Press ENTER to roll the die
Dice 1: 4
Dice 2: 6
Sum:10
You lost the game.
Do you wish to play again?y
Press ENTER to roll the die
Dice 1: 6
Dice 2: 5
Sum:11
However, it does not make much sense that you only allow the user to repeat once. It also does not make sense that you inform the user whether they won the first round, but not whether they won the second round.
It also does not make much sense that you have two functions playGame and rollAgain that are nearly identical. The main difference between these functions seems to be that the first function prints additional instructions to the user, which are only intended to be printed before the first round. Therefore, it would make sense to combine these two functions into one function, so that you don't have any unnecessary code duplication. The printing of the additional instructions could be handled in another function, which is called in main at the start of the program.
Another issue is that the line
scanf("%c", &answer);
in the function main will consume the y character from the input stream, but leave the newline character on the input stream. This means that when the function rollAgain is called, it will prompt the user like this:
Press ENTER to roll the die
However, afterwards, the line
fgetc(stdin);
will not wait for the user to press ENTER, but will instead immediately read the \n newline character that was left over by the function main.
In order to prevent such leftover characters, I recommend that you always read exactly one line of input at once, including the newline character, for example by using the function fgets instead of scanf or fgetc.
Another issue in your program is that you are calling srand several times in your program, which will cause the same sequence of random numbers to be generated if srand is called in the same second. See the following question for further information: srand() — why call it only once?
Here is a fixed version of your code, in which all the issues mentioned above have been addressed and some minor improvements have been added:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>
enum result
{
RESULT_WON = 0,
RESULT_LOST = 1
};
int rollDice();
enum result playGame();
int rollDice( void )
{
return rand() % 6 + 1;
}
void printInstructions( void )
{
printf("--------------\n");
printf("- HOW TO WIN -\n");
printf("--------------\n");
printf("Your dice roll must equal 7 or 11 or else you lose.\n");
printf("\n");
printf("Want to test your luck? ");
}
enum result playGame( void )
{
int dice_1;
int dice_2;
int sum;
int c;
printf("Press ENTER to roll the die\n");
//read characters from input stream until newline character
//is found
do
{
c = getchar();
} while ( c != EOF && c != '\n' );
dice_1 = rollDice();
dice_2 = rollDice();
sum = dice_1 + dice_2;
printf( "Dice 1:%2d\nDice 2:%2d\nSum:%2d\n", dice_1, dice_2, sum );
switch ( sum )
{
case 7:
case 11:
return RESULT_WON;
default:
return RESULT_LOST;
}
}
int main( void )
{
char line[200];
//seed the random number generator only once, at the
//start of the program
srand(time(NULL));
printInstructions();
do
{
switch ( playGame() )
{
case RESULT_WON:
printf( "You won the game.\n" );
break;
case RESULT_LOST:
printf("You lost the game.\n");
break;
}
printf( "Do you wish to play again? (y/n)" );
//read exactly one line of input
if ( fgets( line, sizeof line, stdin ) == NULL )
{
fprintf( stderr, "Input error!\n" );
exit( EXIT_FAILURE );
}
} while ( toupper( (unsigned char)line[0] ) == 'Y' );
return EXIT_SUCCESS;
}
This program has the following behavior:
--------------
- HOW TO WIN -
--------------
Your dice roll must equal 7 or 11 or else you lose.
Want to test your luck? Press ENTER to roll the die
Dice 1: 3
Dice 2: 6
Sum: 9
You lost the game.
Do you wish to play again? (y/n)y
Press ENTER to roll the die
Dice 1: 4
Dice 2: 1
Sum: 5
You lost the game.
Do you wish to play again? (y/n)y
Press ENTER to roll the die
Dice 1: 3
Dice 2: 4
Sum: 7
You won the game.
Do you wish to play again? (y/n)n

Trying to find duplicates in a Struct Array in C

I've attempted to find if the user has inputted a product id value that's a duplicate and if so, it just tells them that it's a duplicate value and then returns to the menu in my switch statement.
The actual result i get, is that after "productsfilled == 0", it won't utilise the For Loops to check for the duplicates and productsfilled will remain at 1. I've looked online and this way of finding duplicates tends to work and i have used it previously in my code, so I don't think that could be the issue.
Here's my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <conio.h>
int productsfilled;
struct ProductData{
int product_id;
char product_name[120];
int price;
};
int quiz_5(){
char ch;
int size, input = 0;
struct ProductData products[20];
while(1){
printf("\nWelcome To The Super Mall's Product List. Please Select An Option:\n1. Add Product\n2. Display Product\n3. Delete Product\n");
fflush(stdin);
switch(getchar()){
case '1':
printf("\nPlease Enter Product ID:");
scanf("%d",&products[productsfilled].product_id);
printf("\nPlease Enter Product Name:");
scanf("%s",&products[productsfilled].product_name);
printf("\nPlease Enter Product Price:");
scanf("%d",&products[productsfilled].price);
printf("Productsfilled: %d",productsfilled);
if(productsfilled == 0){
productsfilled = 1;
break;
}
for(int i = 0; i < productsfilled;i++){
for (int j = i + 1; j < productsfilled;j++){
if(products[i].product_id == products[j].product_id){
printf("\nPlease Use Different Product ID");
break;
}else{
printf("test");
productsfilled += 1;
break;
}
}
}
break;
case '2':
while(1){
for(int i = 0;i < productsfilled;i++){
printf("Product ID: %d Product Name: %s Product Price: %d\n",products[i].product_id,products[i].product_name,products[i].price);
}
printf("Please Press Enter To Continue");
fflush(stdin);
if(getchar() == '\n'){
break;
}
}
case '3':
break;
case '\n':
break;
default:
printf("Please Select An Option:\n1. Add Product\n2. Display Product\n3. Delete Product: ");
}
}
}
int main() {
int input = 1;
printf("Welcome to my assignment. Which quiz do you want to run (please input the number of the quiz e.g. for quiz 1, type 1): \n-Quiz 1\n-Quiz 2\n-Quiz 3\n-Quiz 4\n-Quiz 5\n-Quiz 6\n-Quiz 7\n");
while(input == 1){
fflush(stdin);
switch(getchar()){
case '5':
quiz_5();
break;
case '\n':
printf("Welcome to my assignment. Which quiz do you want to run (please input the number of the quiz e.g. for quiz 1, type 1): \n-Quiz 1\n-Quiz 2\n-Quiz 3\n-Quiz 4\n-Quiz 5\n-Quiz 6\n-Quiz 7\n");
getchar();
default:
printf("Invalid Input\n");
} }
return 0;
}
The problem is that you don't increment productsfilled before you enter the loop...therefore, productsfilled is always 1 less than the actual length of your array which means that you don't compare all elements in the array.
Try your program on 2 inputs, both with the same ID. You'll see that you don't compare anything.
You are wrong when using scanf for string input:
scanf("%s",&products[productsfilled].product_name);
You should not use &, you should use as below:
scanf("%119s",products[productsfilled].product_name);
OT, in main function:
switch(getchar()){
case '5':
...
Because getchar() will return int value, so if you want to access to quiz_5, you have to type 35 (ANSCI code) instead of type 5 when you run your program.
char a = '5';
similar to:
int a = 35;

How to use a do-while loop WITHIN A SWITCH-CASE STRUCTURE in C/C++ to restart a program from the beginning?

In this multiplication game, I have to generate two random numbers and multiply them. The user has to guess the right product. After the game, the user has a choice to either restart the game or quit (along with other choices to display/reset stats). I am required to use a switch-case structure for the choices the user decides on after the game. I also know I have to use a do-while loop for restarting/quitting the game but I don't know what to put in place of the bolded comments (after cases 1 and 3). Thanks in advance for taking the time to read. Any help is much appreciated!
#include <stdio.h>
#include <stlib.h>
#include <time.h>
#include <math.h>
int main () {
//Start do-while loop
do {
//Display rules of the game to the user.
printf("Two random numbers (1-12) will be generated and displayed. The objective of this game is to correctly guess the product of the numbers.");
//Generate two random integers between 1 and 12 and display them to the user
int i;
int n1;
int n2;
srand(time(NULL));
for(i = 1; i<=12;i++)
{
n1 = 1 + rand() % 12;
n2 = 1 + rand() % 12;
printf("The two random numbers generated are : %d and %d\n", n1,n2);
}
//Prompt the user to enter the product of the two numbers
int a;
printf("Enter the product of the two numbers: ");
scanf("%d", &a);
//Determine and display if or not the answer was right
int countCorrect;
int countIncorrect;
int product = n1*n2;
if (a == product)
{
printf("Correct response!");
countCorrect++;
}
else
{
printf("Incorrect response, the correct answer is: %d\n", product);
countIncorrect++;
}
//Start switch-case structure for post-game options
int choice;
switch (choice)
{
case 1:
printf("You have chosen to play again");
**//How do I restart the program so the user can play again?**
break;
case 2:
printf("You have chosen to see statistics");
printf("The number of correct answers are: %d\n", countCorrect);
printf("The number of incorrect answers are: %d\n", countIncorrect);
break;
case 3:
printf("You have chosen to reset statistics");
countCorrect = 0;
countIncorrect = 0;
break;
case 4:
printf("You have chosen to quit");
**//How do I quit the program?**
break;
default:
printf("Invalid number! Please enter a number from 1 to 4.");
break;
}
}
Several things that need to be fixed. When declaring variables, it's good practice to initialise them at the time of decleration. Rather than int a; a = x; And to only declare variables when needed. But this can obviously come down to preference and practice. In C89 variables had to be declared at the top of the scope but I can tell you're not compiling C89. You also didn't need to loop the rand 12 times. Just two calls is enough if you want two seperate ints. Keep in mind rand isn't very good but for practice it's okay. Placing a new line after print statement can make the output neater. countCorrect and countIncorrect were declared but not initialised to 0 then later incremented. This is bad practice because you don't know the initial value of either variable and you wouldn't get an accurate count.
I'm assuming you want to only quit when the user enters 4 but keep looping otherwise?
Place the switch outside the loop then after the user guesses the product, read the choice from the user and use that value the end of the do while loop.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int guess(){
int x = 1+rand()%12;
int y = 1+rand()%12;
printf("The two random numbers generated are : %d and %d\n", x,y);
printf("Enter the product of the two numbers: ");
int z = 0;
scanf("%d", &z);
if(z == (x*y)){
printf("Correct response!\n");
return 1;
}
printf("Incorrect response, the correct answer is: %d\n", x*y);
return 0;
}
int main () {
srand(time(NULL));
printf("Two random numbers (1-12) will be generated and displayed. The objective of this game is to correctly guess the product of the numbers.\n");
int correct = 0;
int incorrect = 0;
int choice = 1;
do{
if(choice==1){
if(guess()){
++correct;
}else{
++incorrect;
}
}
printf("Enter 1 to play again\nEnter 2 to see statistics\nEnter 3 to reset statistic\nEnter 4 to quit:");
scanf("%d",&choice);
switch (choice) {
case 1:
break;
case 2:
printf("You have chosen to see statistics\n");
printf("The number of correct answers are: %d\n", correct);
printf("The number of incorrect answers are: %d\n", incorrect);
break;
case 3:
printf("You have chosen to reset statistics\n");
correct = 0;
incorrect = 0;
break;
case 4:
printf("You have chosen to quit\n");
break;
default:
printf("Invalid number! Please enter a number from 1 to 4.\n");
break;
}
}while(choice !=4);
return 0;
}

Gradebook, array not saving

So I'm trying to make a grade book that does everything displayMenu() says. But i cant even get the student ID to save when i go to view the grades. Please Help.
Everything is initialized here
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define PAUSE system("pause")
#define CLS system("cls")
#define EXAMS 100
#define STUDENT 4
void displayArray(float grades[STUDENT][EXAMS]);
void newStudent(float grades[STUDENT][EXAMS]);
void displayStudentAverage(float grades[STUDENT][EXAMS]);
int main() {
float grades[STUDENT][EXAMS];
This is everything the program should do
displayMenu(grades, 0 );
} // end of main;
int displayMenu(float grades[STUDENT][EXAMS]) {
printf("\t \t MENU \t \t");
printf("Enter Corresponding Number\n");
printf("1.Enter New Student\n");
printf("2.Change Existing Grades\n");
printf("3.View All Grades\n");
printf("4.View Average Score Per Student\n");
printf("5.View Average Score Per Exam\n");
printf("6.View Average Score For The class\n");
printf("7.CLEAR GRADEBOOK\n");
printf("8. Save Gradebook\n");
printf("8.Exit\n");
int choice = 0;
scanf("%d", &choice);
switch (choice) {
case 1:
newStudent(grades, 0);
CLS;
displayMenu(grades,0);
break;
case 2:
break;
case 3: displayArray(grades, 0);
CLS;
displayMenu(grades,0);
break;
case 4:
displayStudentAverage(grades, 0);
break;
case 5:
break;
case 6:
break;
case 7:
break;
case 8:
exit(0);
break;
case 9:
exit(0);
break;
default: printf("You Have entered an incorrect number");
PAUSE;
}
}
This is what displays the grades
void displayArray(float grades[STUDENT][EXAMS]) {
printf("%.1f\t", grades[STUDENT][EXAMS]);
}
I'm trying to add the values to the array here
void newStudent(float grades[STUDENT][EXAMS]) {
float addgrade;
printf("Please Enter Student ID: ");
scanf("%f", &grades[STUDENT][EXAMS]);
printf("Enter four exam grades, use comma to split grades");
scanf("%f", addgrade);
grades[STUDENT][EXAMS] += addgrade;
PAUSE;
CLS;
}
void displayStudentAverage(float grades[STUDENT][EXAMS]) {
int sum, loop;
float avg;
sum = avg = 0;
for (loop = 0; loop < 10; loop++) {
sum = sum + grades[loop];
}
avg = (float)sum / loop;
printf("Average of array values is %.2f", avg);
}
First of all, it's always good check the compiler warnings to get some hints to possible bugs...
Here's a list of problems in the code:
no header files included
displayMenu prototype is missing
the grades array is used with inconsistent types (float/int)
with grades[STUDENT][EXAMS] the grades array is accessed out of bounds (for example if you define an array of size 5 you can only access position 0 to 4)
the return type of main needs to be int
the function newStudent has return type void but the code tries to return something with return &grades[STUDENT][EXAMS];
Apart from that, the code should work...

How do I get switch() to loop multiple times in C?

I have created this fruit machine game. However I would like to loop the output several times before printing a final output that is then scored. To simulate the moving nature of a real slot machine. When I try and loop my switch() statements no output is produced. How would I go about doing this?
#include <stdio.h>
#include <unistd.h>
int main ()
{
int firstReel, secondReel, thirdReel, loop;
// Generating three random numbers
srand(time(NULL));
int rndOne = rand () %4;
int rndTwo = rand () %4;
int rndThree = rand () %4;
// Assigning random numbers to clearer var names
firstReel = rndOne;
secondReel = rndTwo;
thirdReel = rndThree;
// Switch statements for each reel
switch(firstReel){
case 0:
printf("Bell ");
break;
case 1:
printf("Cherry ");
break;
case 2:
printf("Orange ");
break;
case 3:
printf("Horseshoe ");
break;
}
switch(secondReel){
case 0:
printf("Bell ");
break;
case 1:
printf("Cherry ");
break;
case 2:
printf("Orange ");
break;
case 3:
printf("Horseshoe ");
break;
}
switch(thirdReel){
case 0:
printf("Bell\n");
break;
case 1:
printf("Cherry\n");
break;
case 2:
printf("Orange\n");
break;
case 3:
printf("Horseshoe\n");
break;
}
// Win/lose conditions
if (firstReel == secondReel || firstReel == thirdReel || secondReel == thirdReel)
printf("Congratulations! You win!\n");
else
{
printf("Sorry, you lose. Play again? (Y/N)\n");
}
}
use some sort of counter/ looping statement
int i=0;
while(i< 10){
//Your switch statements
i++;
}
As a better programming practice please do include default case/scenario too when the switch input doesn't satisfy any of the cases.. helps in keeping the code structured and avoids any confusion also showing that other values have been taken care of. For ex:
default:
printf("Invalid value entered");
break;
Try using a loop as shown below :
Here I am running the loop for some x number of times.You can run the loop for any number of times you wish to.
int main ()
{
int firstReel;
int i=0;
// Generating three random numbers
srand(time(NULL));
// Assigning random numbers to clearer var names
while(i<7)
{
firstReel = rand () %4;
// Switch statements for each reel
switch(firstReel){
case 0:
printf("Bell ");
break;
case 1:
printf("Cherry ");
break;
case 2:
printf("Orange ");
break;
case 3:
printf("Horseshoe ");
break;
}
i++;
}
}
This will show the reels spinning and slowing to the final pattern (in a console).
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SYMBOLS 4
#define REELS 3
#define SPINS 20
char *symbol [SYMBOLS] = {" Bell ", " Cherry ", " Orange ", "Horseshoe "};
int reel [REELS];
int main(int argc, char **argv)
{
int s, r, elap, tix, counts;
srand ((unsigned)time(NULL));
for (s=SPINS; s>0; s--) {
printf ("\r");
for (r=0; r<REELS; r++) {
reel [r] = rand() % SYMBOLS;
printf ("%s", symbol [reel [r]]);
}
tix = clock();
counts = CLOCKS_PER_SEC / s;
do {
elap = clock() - tix;
}
while (elap < counts);
}
printf ("\n");
for (r=1; r<REELS; r++)
if (reel [r] != reel [r-1])
break;
if (r < REELS)
printf ("You lost!\n");
else
printf ("You won!\n");
return 0;
}

Resources