Random number game C - c

The game works fine my first time through, although; the second time it only gives you two lives... I have tried to change the number of lives but still can't figure out what I'm doing wrong.
// C_program_random_number_game
#include<stdio.h>
#include<time.h>
#include <stdlib.h>
int main()
{
srand(time(NULL));
int num1,x = 0;
char game, cont, replay;
printf("Would you like to play a game? : ");
scanf("%c",&game);
if (game == 'y' || game == 'Y')
{
printf("\nThe rules are simple. You have have 5 tries to guess the computers number. \n \n If you succeed you win the game, if you dont you lose the game. Good luck!");
do
{
int r = rand()%5 +1;
printf("\n\nEnter a number between 1 and 5 : ");
scanf("\n%d",&num1);
x++;
if(num1 > 0 && num1 < 5)
{
do
{
if(num1 < r)
{
printf("\nClose! try a little higher... : ");
x++;
}
else if (num1 > r)
{
printf("\nClose! try a little lower...: ");
x++;
}
scanf("%d",&num1);
}while(num1!=r && x <3);
if(num1 == r)
{
printf("\nWinner! >> you entered %d and the computer generated %d! \n",num1, r);
}
else if(num1 != r)
{
printf("\nBetter luck next time!");
}
printf("\n\nWould you like to play again? (y or n) : ");
scanf("\n%c",&replay);
}
else
{
printf("Sorry! Try again : ");
scanf("%d",&num1);
}
}while(replay == 'y'|| replay == 'Y');
}
else if (game == 'n' || game == 'N')
{
printf("Okay, maybe next time! ");
}
else
{
printf("Sorry, invalid data! ");
}
return 0;
}

There are all kinds of issues with you code (most of them are minor in terms of programming). Most of the errors are typos in what you want done via this question and what you printf().
As is, this code will random between 1-25, accept an input of any valid int, see if you matched it, and only give you 5 tries. (I didn't add error checking to enforce that the input is between 1-25. That should probably be added.)
I commented my code below with all my changes and went by that you had in the printf()s.
Note: See my comments above for explanations of my changes since I already pointed them out. I also formatted it so its a little more easy to read.
Note2: I did this quickly using an online compiler. If you find anything wrong with this or not working as you'd like, just comment below and I'll address it.
// C_program_random_number_game
#include<stdio.h>
#include<time.h>
#include <stdlib.h>
int main()
{
srand(time(NULL));
int num1,x = 0;
char game, cont, replay;
printf("Would you like to play a game? : ");
scanf("%c",&game);
if (game == 'y' || game == 'Y')
{
printf("\nThe rules are simple. You have have 5 tries to guess the computers number. \n \n If you succeed you win the game, if you dont you lose the game. Good luck!");
do
{
int r = rand()%25 +1;
printf("\n\nEnter a number between 1 and 25 : ");
scanf("%d",&num1);
do
{
printf("r = %d\n", r);
if(num1 < r)
{
printf("\nClose! try a little higher... : ");
x++; //Increment x if wrong guess
}
else if (num1 > r)
{
printf("\nClose! try a little lower...: ");
x++; //Increment x if wrong guess
}
scanf("%d",&num1);
}while(num1!=r && x < 5); //If x is 5 or more, they ran out of guesses (also, you want an && not an ||)
if(num1 == r) //Only print "winner" if they won!
{
printf("\nWinner! >> you entered %d and the computer generated %d! \n",num1, r);
}
printf("\nWould you like to play again? (y or n) : ");
scanf("\n%c",&replay);
}while(replay == 'y'|| replay == 'Y');
}
printf("Thanks for playing! ");
if (game == 'n' || game == 'N')
{
printf("Okay, maybe next time! ");
}
return 0;
}

There are a combination of two problems. The first is that you're not breaking out of the "for" loop when the number matches. Therefore the match is only checked on every third guess.
The second problem is in this logic check:
}while(num1!=r || x <= 3);
We see that this turns into "true" if the for loop is broken out of early.

Related

Can't find the problem with my number guessing game. (C)

I have managed to create a game that tries to guess what the user is thinking about, but the problem is that the number guessed is stored into l_guess or h_guess depending on the condition met, how can I store it into a third variable that would be the new guess used on the next guess?
My question might not be clear, but I hope looking at the code will help.
// Assignment #7
// This program guesses the number that you have picked.
#include <stdio.h>
#define UPPER 100
#define first_Guess 50
char answer;
int h_Guess;
int l_Guess;
int new_Guess;
void game_Start();
void game_Play();
int main(void)
{
h_Guess = (first_Guess + UPPER) / 2;
l_Guess = first_Guess;
game_Start();
game_Play();
return 0;
}
void game_Start()
{
printf("Hello, and welcome to the guessing game\n Think of a number between 0 and 100 and I will try to guess it.\n");
printf("... Is it %d ?", first_Guess);
printf("If the answer is correct, press (c) \n If your number is higher, press (h)\n if your number is lower, press (l)\n");
scanf("%c", &answer);
}
void game_Play()
{
while (answer != 'c')
{
if (answer == 'h')
{
printf("Then ... is it %d?\n", h_Guess);
h_Guess = (h_Guess + UPPER) / 2;
}
else if (answer == 'l')
{
l_Guess = l_Guess / 2;
printf("Then ... is it %d?\n", l_Guess);
}
scanf("%c", &answer);
}
printf(" I knew it, I am a genius\n");
}
You're not properly re-setting the boundaries of your guesses.
void game_Play()
{
int upper = MAX;
int lower = MIN;
int guess = FIRST_GUESS;
while (answer != 'c')
{
if (answer == 'h')
{
lower = guess;
}
else if (answer == 'l')
{
upper = guess;
}
guess = (upper + lower) / 2;
printf("Then is it %d?\n", guess);
scanf(" %c", &answer);
}
printf(" I knew it. I am a genius.\n");
}
Note: with your constants defined as they are, there is an edge-case error in my solution. Can you find it, and fix it?

Craps game - scanf automatically input huge number

The instructions for the part of the project I am having trouble with are:
"Playing" the game:
A second function playing() will be used to play a single game of craps until the player either wins or loses a bet, based upon the rules given above. This function should be modify the current $ amount of the player's bank roll according to the game result, modify the array values of the player won or lost, and whether the player bet for or against him/herself. Within the function, the player is asked whether s/he would like to place a bet. If so, the player must choose whether to bet "for" or "against" him/herself (see game rules above). The player then "rolls the dice" (simulated by a call to the dice-rolling function rolling()). This should be done interactively (via a key press from the player), rather than simply having the program continuously roll the dice until the game is over. After each roll, this function should report the two random dice values and the sum of the two. If, after the first roll, the game is not over, the player should be asked whether s/he would like to double the amount of the bet. When a roll causes the end of a game, the player is notified whether s/he won or lost money in that game overall, and the amount won or lost. In all other cases, the player is notified that s/he needs to roll again.
I have to code in a craps game that asks user for a bet amount and then they play craps. They have an initial bank roll of $100. I have to scan a bet amount in using scanf but it keeps making my bet amount very large without any user input. Can someone please help me, I have this project due tonight.
#include <stdio.h> /* printf, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h>
//function prototype
int rolling(void);
int playing(int c_amt);//inital money $100, min bet of $5, no max except money you have
void beginning(void);
void ending(void);
int
main()
{
printf("\nWelcome to Craps! Get ready to play!");
int bank_amt = 100;
char y_n = 'n';
do
{
bank_amt = playing(bank_amt);
if(bank_amt == 0)
{
printf("\nYou bet and lost all your money! You can't play anymore. Goodbye!");
exit(0);
}
if(bank_amt != 0)
{
printf("\nYour current balance is %d %d", &bank_amt, bank_amt);
printf("\nDo you want to play again? (y/n): ");
scanf("\n%c", &y_n);
}
}
while(y_n != 'n' && y_n != 'N');
}
int
rolling(void)
{
int dice1, dice2;
char roll;
srand((int)(time(NULL))); // "Seed" random number gen. with system time
printf("\nPress enter to roll the dice!");
fflush(stdin);
scanf("%c",&roll);
dice1 = 1+rand()%6; // random num from 1-6
dice2 = 1+rand()%6; // random num from 1-6
return dice1+dice2;
}
int
playing(int c_amt)
{
char gametype, y_n = 'n';
int total, point, for_u, against_u, winlose, win = 0, lose = 0;
int moneychange, bet_amt, final_amt;
printf("\nPlease press 'f' if you are betting for yourself and 'a' if your are betting against yourself.\n");
scanf("\n%c", &gametype);
do
{
printf("\nYour current bank balance is %d.", c_amt);
printf("\nEnter the amount you want to bet: ");
scanf(" %d", &bet_amt);
printf("Bet amount: %d", bet_amt);
if(bet_amt > c_amt || bet_amt < 5)
{
printf("\nYou dont have that much money or you placed a bet less than the minimum. Please place a proper bet.");
}
}
while(bet_amt > c_amt);
if (gametype == 'f' || gametype == 'F')
{
for_u++;
printf("\nYou are betting for yourself!\nLets get started!");
total = rolling();
printf("\nThe value rolled is %d.", total);
if (total == 7 || total == 11)
{
printf("\nGood job! You win :)");
winlose = 1;
}
else if (total == 2 || total == 3 || total == 12)
{
printf("\nCraps, you lose.");
winlose = 0;
}
else
{
point = total;
printf("\nYour point is %d.", point);
if(bet_amt*2 <= c_amt)
{
printf("\nWould you like to double your bet? (y/n)");
scanf("\n%c", &y_n);
}
if(y_n == 'y' || y_n == 'Y')
{
bet_amt = bet_amt*2;
}
do
{
total = rolling();
if(total == point)
{
printf("\nGood job! You win! :)");
winlose = 1;
break;
}
}
while(total != 7);
if(total == 7)
{
printf("You rolled a seven. You lose! :(");
winlose = 0;
}
}
}
else if (gametype == 'a' || gametype == 'A')
{
against_u++;
printf("You are betting against yourself!\nLet\'s get started!");
total = rolling();
printf("\nThe value rolled is %d.", total);
if (total == 2 || total == 3 || total == 12
{
printf("Good job! You win :)\n");
}
else if (total == 7 || total == 11)
{
printf("Craps, you lose.\n");
}
else
{
point = total;
printf("Your point is %d.\n", point);
if(bet_amt*2 <= c_amt)
{
printf("\nWould you like to double your bet? (y/n)");
scanf("\n%c", &y_n);
}
if(y_n == 'y' || y_n == 'Y')
{
bet_amt = bet_amt*2;
}
do
{
total = rolling();
if(total == 7)
{
printf("\nGood job! You win! :)");
winlose=1;
break;
}
}
while(total != point);
if(total == 7)
{
printf("You rolled a seven before making your point. You lose! :(");
winlose = 0;
}
}
}
if(winlose == 1)
{
final_amt = bet_amt + c_amt;
win++;
}
else
{
final_amt = c_amt - bet_amt;
lose++;
}
printf("Final amount is %d.", final_amt);
return final_amt;
}
Here is sample output:
Welcome to Craps! Get ready to play!
Please press 'f' if you are betting for yourself and 'a' if your are betting against yourself.
Your current bank balance is 100.
Enter the amount you want to bet: Bet amount: -1219958512
You dont have that much money or you placed a bet less than the minimum. Please place a proper bet.Final amount is 1219958612.
Your current balance is -1074871812 1219958612
Do you want to play again? (y/n):
Your formatting needs a lot of fixing to understand. However, the real issue is a buffer overflow, caused by not allocating enough memory to the char. Instead, I would suggest using simple int values like 0 and 1 to determine the player's choices.

If and if else statements working, but not else

I am making a number guessing game program and am having some trouble with my else statements. In the main block where the number is trying to be guessed, the if and if else statements work, but the else statement does nothing. I am trying to make it where a number outside of the range 0 < number < 100 trigger the else statement.
Furthermore, I am trying to make the game repeat itself if '1' is entered but no matter what is entered, the program crashes.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
/*Number guessing game: The number that needs to be guessed is 52*/
int guess;
int attempt = 6;
int playAgain = 1;
printf("Guess the integer that I am thinking of between 1 and 100\n");
printf("I will tell you if you guess too high or too low\n");
printf("You have 6 attempts\n");
printf("What is your first guess?\n");
if (playAgain == 1)
{
while (attempt > 0)
{
scanf_s("%d", &guess);
if (guess > 0)
{
if (guess < 52)
{
attempt--;
printf("Sorry! Too low! You have %d more tries:\n", attempt);
}
}
else if (guess <100)
{
if (guess > 52)
{
attempt--;
printf("Sorry! Too high! You have %d more tries:\n", attempt);
}
}
else if (guess == 52)
{
printf("Correct! You win!\n");
attempt = 0;
}
else
{
printf("Invalid input: Please enter an integer between 1 and 100:\n");
}
}
printf("Enter '1' to play again or anything else to terminate\n");
scanf_s("%d", playAgain);
attempt = 6;
}
else
{
printf("Thanks for playing!\n");
}
return 0;
}
When you use if else if without brackets, make sure it can't be ambigous.
When you do :
if (true)
if (true)
{
}
else if (false)
{
}
How to know if the else if correspond to the first or the second if ? That's why everyone yell at you to put brackets.
if (true)
{
if (true)
{
}
}
else if (false)
{
}
Corrected and simplified version :
Your program crashes because you forgot the & sign inscanf("%d", &playAgain);.
The logic in your program is wrong, you intermix the test if the number is lower, equal or higher than the input with the test if the input is lower than 0 or higher than 100.
In this corrected version the "invalid input" problem is separated from the actuel "number guessing" problem.
Furthermore the number to be guessed (52) is nor longer hard coded but a variable numbertobeguessed is used instead. Later you should enhance the program so that a random number is generated.
int main(void)
{
/*Number guessing game: The number that needs to be guessed is 52*/
int numbertobeguessed = 52 ;
int guess;
int attempt = 6;
int playAgain = 1;
printf("Guess the integer that I am thinking of between 1 and 100\n");
printf("I will tell you if you guess too high or too low\n");
printf("You have 6 attempts\n");
printf("What is your first guess?\n");
if (playAgain == 1)
{
while (attempt > 0)
{
scanf_s("%d", &guess);
if (guess < 0 || guess > 100)
{
printf("Invalid input: Please enter an integer between 1 and 100:\n");
}
else
{
if (guess < numbertobeguessed)
{
attempt--;
printf("Sorry! Too low! You have %d more tries:\n", attempt);
}
else if (guess > numbertobeguessed)
{
attempt--;
printf("Sorry! Too high! You have %d more tries:\n", attempt);
}
else
{
printf("Correct! You win!\n");
attempt = 0;
}
}
}
printf("Enter '1' to play again or anything else to terminate\n");
scanf_s("%d", &playAgain);
attempt = 6;
}
else
{
printf("Thanks for playing!\n");
}
return 0;
}
the else statement which gives message "Invalid input: Please enter an integer between 1 and 100:\n" is considered as the else part of inner most if-else-if statement. there fore that statement is never executed as the execution enters that if-else-if statement only if 0 < guess < 100. so use {} properly to make the proper combination of if-else statements.
Your nesting is wrong. Put brackets for each if and else to make your code work (quickfix), and use proper indentation to make it readable to humans (if you wish).
Here's an example of how things can go wrong (pseudo code):
a = 4
if (a > 0)
if (a < 3)
a = 2
else
a = 3
What do you expect is the end value of a?
Anyway, your:
if (guess > 0)
if (guess < 52)
should become this:
if (guess > 0 && guess < 52)
and your:
else if (guess <100) // this is where the problems start
if (guess > 52)
should become:
else if (guess < 100 && guess > 52)
and your code will work.
hope this helps
#include <stdio.h>
#include <stdlib.h>
int main()
{
int guess; //variable to hold the number from player
int attempts = 6;
char play = 'y';
do
{
while(attempts)
{
printf("\nEnter you guess: "); scanf("%d", &guess);
attempts--;
if(guess>0 && guess <100 )
{
if(guess>52)
printf("\nThat's not it. Try something lower than that.");
else if(guess<52)
printf("\nThat's not the number. Try something higher than that.");
else if(guess==52)
{ printf("\nYou got it!. You won the game.");
attempts = 0; //we're setting it to zero; we don't want the loop to run anymore
}
}
else
printf("\nNumber enter is not in range!");
}//end of while loop
printf("\nDo you want to play again? (y/n): "); scanf("%c", &play);
}while(play=='y' || play=='Y'); //run till player enter 'Y'
return 0;
}

Simple random numbers game program

Here is my code, It is a simple number game where the user tries to guess the random number however, I can not figure out why it you never win..There are two things i am having trouble solving 1) The user never guesses the correct number 2) I want to have a cap of 3 tries of guessing although I cant seem catch what i'm overlooking
// C_program_random_number_game
#include<stdio.h>
#include<time.h>
#include <stdlib.h>
int main(){
srand(time(NULL));
int num1,x;
char game, cont, replay;
printf("Would you like to play a game? : ");
scanf("%c",&game);
if (game == 'y' || game == 'Y'){
printf("\nThe rules are simple. You have have 5 tries to guess the computers number. \n \n If you succeed you win the game, if you dont you lose the game. Good luck!");
do{
int r = rand()%25 +1;
printf("\n\nEnter a number between 1 and 5 : ");
scanf("%d",&num1);
do{
for(x=1; x<=3; x++){
if(num1 < r){
printf("\nClose! try a little higher... : ");
}
else if (num1 > r){
printf("\nClose! try a little lower...: ");
}
scanf("%d",&num1);
}
}while(num1!=r || x <= 3);
printf("\nWinner! >> you entered %d and the computer generated %d! \n",num1, r);
printf("\nWould you like to play again? (y or n) : ");
scanf("\n%c",&replay);
}while(replay == 'y'|| replay == 'Y');
}
printf("Thanks for playing! ");
if (game == 'n' || game == 'N'){
printf("Okay, maybe next time! ");
}
return 0;
}
One definite problem is that the format specifier is incorrect:
scanf("&d",&num1);
should be:
scanf("%d",&num1);
Moreover, the last 2 conditions in your while loop would never be evaluated since it'd not enter the loop if the guess is equal to the random number. Use a do-while loop instead to loop infinitely, and break out of it as per the user input. Remember to take user input for the guess within the loop.
There are various flaws, here is the code you are looking for:
while(num1 != r){
if(num1 < r){
printf("higher... : ");
}
else{
printf("lower...: ");
}
scanf("%d",&num1);
}
printf("Winner! >> you entered %d and the computer generated %d! \n",num1, r);
printf("Would you like to play again? (y or n) : ");
scanf("%c",&replay);
As I pointed out in the comment above, previously, inside the while loop, there would never be a time when num1==r and thus the if statement inside will never be true. Now, the loop jsut simply stops after it reaches the number.

Monty hall show simulation unexpected results

#include <stdio.h>
#include <time.h>
int main (void)
{
int pickedDoor, remainingDoor, hostDoor, winningDoor, option, games = 0, wins = 0;
float frequency = 0;
srand (time(NULL));
while (1)
{
printf ("Pick one of the three doors infront of you, which do you want?\n");
scanf ("%d", &pickedDoor);
if (pickedDoor > 3 || pickedDoor <= 0)
{
break;
}
winningDoor = rand() % 3 + 1;
do
{
hostDoor = rand() % 3 + 1;
} while (hostDoor == pickedDoor || hostDoor == winningDoor);
do
{
remainingDoor = rand() % 3+1;
} while (remainingDoor == pickedDoor || remainingDoor == hostDoor);
printf ("The door the host picked is %d\n", hostDoor);
do
{
printf("Do you want to switch doors? Please enter in the door you want:\n", hostdoor);
scanf("%d", &option);
if (option > 3 || option <= 0)
{return 0;}
}while (option == hostDoor);
if (option == winningDoor)
{
printf("You Won!\n");
wins++;
}
else
{
printf("YOU LOSE!\n");
}
games++;
}
frequency = ((float) wins / games) *100;
printf ("The number of games that you won is %d\n", wins);
printf ("The frequency of winning is %.0f%%\n", frequency);
return 0;
}
Hi, this is my version of the monty hall game show, im getting unexpected results though.
sometimes when I enter in a door for my option it just brings me back to the "pick one of the three doors infront of you" statement, when it should tell me if i have won or lost.
I think this is because the "option" door is equal to the "hostDoor.
I thought having "option != hostDoor" would fix it but it does not.
If i am correct in that assumption how can I fix it? If not why is it not working and how can I fix it?
To simulate correctly, OP needs to show the host door.
do {
printf("Do you want to switch doors? Please enter in the door you want:\n");
scanf("%d", &option);
if (option > 3 || option <= 0 ) {
return 0;
}
} while (option == hostDoor);
// instead of
#if 0
printf("Do you want to switch doors? Please enter in the door you want:\n");
scanf("%d", &option);
if (option > 3 || option <= 0 ) { return 0; }
#endif
To deal with OP " it should tell me if i have won or lost." problem, change
else if (option == remainingDoor)
to
else
Your scanf("%d", &option) is OK. I prefer the fgets()/sscanf() combo and its alway useful to check the result of scanf() family, but that is not your issue here.
Its because of these:
scanf ("%d", &pickedDoor);// reads \n after the last input
scanf("%d", &option); // reads \n after the last input
**option != hostDoor; // completely useless .. get rid of it**
I would suggest putting a getchar() after each scanf to get rid of the \n character
so something like this:
#include <stdio.h>
#include <time.h>
int main (void)
{
int pickedDoor, remainingDoor, hostDoor, winningDoor, option, games = 0, wins = 0;
char collect; //variable to collect any extra input like \n
float frequency = 0;
srand (time(NULL));
while (1)
{
printf ("Pick one of the three doors infront of you, which do you want?\n");
scanf ("%d", &pickedDoor);
collect = getchar(); // get rid of the \n from the input stream
printf("collect = %c\n",collect);
if(collect!='\n'){ // is it actually a \n or did you take in something else
putchar(collect); // if it isn't \n put it back
}
if (pickedDoor > 3 || pickedDoor <= 0)
{
break;
}
winningDoor = rand() % 3 + 1;
do
{
hostDoor = rand() % 3 + 1;
} while (hostDoor == pickedDoor || hostDoor == winningDoor);
do
{
remainingDoor = rand() % 3+1;
} while (remainingDoor == pickedDoor || remainingDoor == hostDoor);
printf("Do you want to switch doors? Please enter in the door you want:\n");
scanf("%d", &option);
collect = getchar(); // get rid of the \n from the input stream
printf("collect = %c\n",collect);
if(collect!='\n'){ // is it actually a \n or did you take in something else
putchar(collect); // if it isn't \n put it back
}
if (option > 3 || option <= 0 )
{
return 0;
}
if (option == winningDoor)
{
printf("You Won!\n");
wins++;
}
else if (option == remainingDoor)
{
printf("YOU LOSE!\n");
}
games++;
}
frequency = ((float) wins / games) *100;
printf ("The number of games that you won is %d\n", wins);
printf ("The frequency of winning is %.0f%%\n", frequency);
return 0;
}
Another more efficient way would be to use fgets or to have error checks on scanf() itself
srand and rand belongs to stdlib header file
#include<stdlib.h> // include this header file
option != hostDoor; // this statement does not do anything
and your else if (option == remainingDoor) should be else { printf("you lose");}

Resources