I need help finishing my program. I can't seem to get the last step, when the user enters 'y' to play another game it should start again. If the user enters 'n' then it should end. Thank you in advance for any help. Below is the code I have so far.
Here is the problem:
Write a C program that plays a number guessing game with the user.
Below is the sample run:
OK, I am thinking of a number. Try to guess it.
Your guess? 50
Too high!
Your guess? 250
Illegal guess. Your guess must be between 1 and 200.
Try again. Your guess? 30
**** CORRECT ****
Want to play again? y
Ok, I am thinking of a number. Try to guess it.
Your guess? 58
**** CORRECT ***
Want to play again? n
Goodbye, It was fun. Play again soon.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int i, number, currentGuess, MAX_GUESS = 5;
int answer = 'n';
time_t t;
srand((unsigned) time(&t));
number = rand() % 200 + 1;
printf("Welcome to the game of Guess It! \nI will choose a number between 1 and 200. \nYou will try to guess that number.");
printf("If you guess wrong, I will tell you if you guessed too high or too low. \nYou have 5 tries to get the number. \n");
printf("\nOK, I am thinking of a number. Try to guess it. \n");
for (i = 0; i < MAX_GUESS; i++) {
printf("\nYour guess?");
scanf("%i", ¤tGuess);
if (currentGuess > 200) {
printf("Illegal guess. Your guess must be between 1 and 200.\n");
printf("Try again.\n ");
}
else if (currentGuess > number) {
printf("Too high!\n");
}
else if (currentGuess < number) {
printf("Too low!\n");
}
else {
printf("****CORRECT****\n");
return 0;
}
}
printf("Sorry you have entered the maximum number of tries. \n");
printf("Want to play again? \n");
scanf("%i", &answer);
if(answer == 'n') {
printf("Goodbye, it was fun. Play again soon.\n");
return 0;
}
else if (answer != 'n') {
printf("Ok, I am thinking of a number. Try to guess it.\n");
}
}
Here's an idea for you to do this in your code:
char answer = 'y';
do
{
// ...
printf( "Want to play again (y/n)? " );
scanf( " %c", &answer );
// Mind ^ the space here to discard any
// previously read newline character
} while ( answer == 'y' );
Check the below code, you might wanna understand the code, rather than just copy pasting it.
The code delegates the task of doing a repetitive task to a function.
The code then relies on the function to say how many chances player has played, or -1 for successful.
And note the getchar() rather than scanf.
NOTE: The extra getchar() is needed, because I don't know but taking character input after taking integer input puts a '\n' character in the stdin, which results in unwanted behaviour. So this is a small trick I always use to tackle such cases.
Pay attention to the do while loop, this case becomes a classic example where you should use do while loop.
Also I have used macros to define MAX_GUESS. That's a good practice. You might wanna google it for "why?"
If you have any further queries, do comment in the answer.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>
#define MAX_GUESS 5
int playGame(int number)
{
printf("\nOK, I am thinking of a number. Try to guess it. \n");
int i, currentGuess;
for (i=0; i<MAX_GUESS; i++){
printf("\nYour guess?: ");
scanf("%i", ¤tGuess);
if (currentGuess > 200) {
printf("Illegal guess. Your guess must be between 1 and 200.\n");
printf("Try again.\n ");
}
else if (currentGuess > number) {
printf("Too high!\n");
}
else if (currentGuess < number) {
printf("Too low!\n");
}
else {
printf("****CORRECT****\n");
return 0;
}
}
return i;
}
int main() {
int i, number, x;
char answer = 'n';
time_t t;
srand((unsigned)time(&t));
printf("Welcome to the game of Guess It! \nI will choose a number between 1 and 200. \nYou will try to guess that number.");
printf("If you guess wrong, I will tell you if you guessed too high or too low. \nYou have 5 tries to get the number. \n");
do
{
number = rand()%200+1;
x = playGame(number);
if (x == MAX_GUESS)
printf("Sorry you have entered the maximum number of tries. \n");
printf("Want to play again? \n");
// To flush the newline character
getchar();
answer = getchar();
} while (answer != 'n' || answer != 'N');
printf("Goodbye, it was fun. Play again soon.\n");
return 0;
}
Related
Im making a program where it asks the user to guess a number 1-100 that the computer is thinking about.
In the end of the program, when the user has guessed the correct number, im trying to get the program to ask if user wants to play again (restart the program).
To solve this, i tried using a do while loop & char repeat;. The loop is stretching from almost the beginning of the program, until the end, althought without success. Does anyone know what im doing wrong? Is it because of the function talfunktion, that the loop won't pass?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int talfunktion (int tal, int guess, int tries, char repeat);
int main () {
do {
srand(time(NULL));
int tal = rand() % 100 + 1; //tal is the correct value that the code is thinking of
int guess; //guess is the guessed value of the user
int tries = 0; // amount of tries it took until getting correct
char repeat;
printf("Psst, the right number is: %d \n", tal); // remove later, not relevant to uppg.
printf("Im thinking of a number between 1 and 100, guess which!");
printf("\nEnter: ");
scanf("%d", &guess);
guess = talfunktion(tal, guess, tries, repeat);
getchar();
getchar();
return 0;
}
int talfunktion(int tal, int guess, int tries, char repeat) {
do {
if (guess < tal) {
tries++;
printf("\nYour guess is too low, try again!");
printf("\nEnter: ");
scanf("%d", &guess);
}
else if (guess > tal) {
tries++;
printf("\nYour guess is too high, try again!");
printf("\nEnter: ");
scanf("%d", &guess);
}
} while (guess > tal || guess < tal);
if (guess == tal) {
printf("\nCongratulations, that is correct!");
tries++;
printf("\nYou made %d attempt(s)", tries);
printf("\nPlay Again? (y/n)");
scanf("%c", &repeat);
}
} while (repeat == 'y' || repeat == 'Y');
}
This is one possible solution
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void talfunktion(int tal, int guess, int* tries)
{
if (guess < tal)
{
(*tries)++;
printf("\nYour guess is too low, try again!");
}
else if (guess > tal)
{
(*tries)++;
printf("\nYour guess is too high, try again!");
}
else if (guess == tal)
{
(*tries)++;
printf("\nCongratulations, that is correct!");
printf("\nYou made %d attempt(s)", *tries);
}
}
int main (void)
{
int tal; //tal is the correct value that the code is thinking of
int guess; //guess is the guessed value of the user
int tries = 0; // amount of tries it took until getting correct
char playAgain;
do {
srand(time(NULL));
tal = rand() % 100 + 1; //tal is the correct value that the code is thinking of
printf("\nIm thinking of a number between 1 and 100, guess which!");
printf("\nEnter: ");
scanf("%d", &guess);
talfunktion(tal, guess, &tries);
printf("\nPsst, the right number is: %d", tal); // remove later, not relevant to uppg.
getchar(); //to halt the code for taking the input
if(guess == tal)
{
tries = 0;
printf("\nPlay Again? (y/n)\n");
scanf("%c", &playAgain);
}
} while (playAgain != 'n');
return 0;
}
There are several things mentioned in the comments that describe problems,
Things you should look at:
Do not define a function inside another function
be careful where you place return statements
when using character testing, use char type for variable
consider simplifying your logical comparisons. (eg guess > tal || guess < tal is the same as guess != tal )
make sure automatic variables are placed such that they are visible where used.
Place space in format specifier: " %c" for scanf() to consume newline character. (instead of excessive use of getchar())
Here is a simplified version of your code, with modified main and talfunktion functions...
char talfunktion(int tal);
int main (void) {
int tal=0;//remove from inside {...} to make it visible to rest of function
char repeat = 'n';
srand(time(NULL));
tal = rand() % 100 + 1; //tal is the correct value that the code is thinking of
do {
repeat = talfunktion(tal);
}while((tolower(repeat) == 'y'));
return 0;
}
char talfunktion(int tal)//do all relevant work in function and return
{ //only what is necessary
int guess = 0;
char repeat = 'n';
printf("Im thinking of a number between 1 and 100, guess which!");
printf("\nEnter a number from 1 to 100: ");
scanf("%d", &guess);
if((guess < 1) || (guess > 100))
{
printf("Entered out of bounds guess...\n");
}
else if (guess != tal)
{
if(guess < tal) printf("guess too small\n");
else printf("guess too large\n");
printf("Try again? <'n' or 'y'>\n");
scanf(" %c", &repeat);//space in format specifier to consume newline character
if(tolower(repeat) != 'y') return 'n';//tolower() allows both upper and lower case
}
else
{
printf("Congratulations: You guessed right.\n");
printf("Play again? <'n' or 'y'>\n");
scanf(" %c", &repeat);
}
return repeat;
}
I have written this simple program, which is supposed to calculate the factorial of a number entered by the user. The program should ask the user to stop or continue the program in order to find the factorial of a new number.
since most of the time user don't pay attention to CapsLock the program should accept Y or y as an answer for yes. But every time I run this program and even though I enter Y/y , it gets terminated !
I googled and found out the problem could be due to new linecharacter getting accepted with my character input so, I modified the scanf code from scanf("%c", &choice); to scanf("%c ", &choice); in order to accommodate the new line character , but my program is still getting terminated after accepting Y/y as input.
Here is the code . Please if possible let me know the best practices and methods to deal with these kinds of issues along with the required correction.
#include<stdio.h>
#include"Disablewarning.h" // header file to disable s_secure warning in visual studio contains #pragma warning (disable : 4996)
void main() {
int factorial=1;//Stores the factorial value
int i; //Counter
char choice;//stores user choice to continue or terminte the program
do {//Makes sure the loop isn't terminated until the user decides
do{
printf("Enter the no whose factorial you want to calculate:\t");
scanf("%d", &i);
} while (i<0);
if (i == 0) //calculates 0!
factorial = 1;
else {//Calculates factorial for No greater than 1;
while (i > 0) {
factorial = factorial*i;
i--;
}
}
printf("\nThe factorialof entered no is :\t%d", factorial);//prints the final result
printf("\nDo you want to continue (Y/N)?");
scanf("%c ", &choice);
} while (choice =="y" || choice =="Y"); // Checks if user wants to continue
}
I'm a beginner in programming and I'm running this code in visual studio 2015.
Just modify your scanf like following:
printf("\nDo you want to continue (Y/N)? ");
scanf(" %c", &choice); //You should add the space before %c, not after
also you should use:
} while (choice == 'y' || choice == 'Y'); // Checks if user wants to continue
NOTE:
Simple quote ' is used for characters and double quote " is used for string
Your second-last line has a string literal "y", which should be a character literal i.e. 'y':
} while (choice =="y" || choice =="Y");
This should be:
} while (choice =='y' || choice =='Y');
Also, your scanf() doesn't consume whitespace. Add a space before %c to make it ignore newlines or other spaces:
scanf(" %c", &choice);
Try doing the following even after the correction there are still some bugs in the code
In your code if you type 'Y' and recalculate a factorial it gives wrong answer as
int factorial is already loaded with the previous value
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
using namespace System;
using namespace std;
int calculateFactorial(int i);
int main()
{
int i;
char choice;
do{
printf("Enter the no whose factorial you want to calculate:\t");
scanf("%d", &i);
printf("\n The factorial of entered no is :\t %d", calculateFactorial(i));
printf("\n Do you want to continue (Y/N)?");
scanf(" %c", &choice);
} while (choice == 'y' || choice == 'Y');
return 0;
}
int calculateFactorial(int i) {
int factorial = 1;
if (i == 0){
factorial = 1;
}else {
while (i > 0){
factorial = factorial*i;
i--;
}
}
return factorial;
}
I'm writing the simplest game in C - Number guessing game. The game itself works good. Yaay me. The problem is that I don't know how to start it over. See code below:
int main()
{
int number, innum, times = 0;
char playAgain;
srand((unsigned)time(NULL));
number = 5;//rand() % 1000;
for(;;)
{
while(innum != number)
{
printf("Enter a number: ");
scanf("%d", &innum);
if(innum > number)
printf("The entered number is too big!\n");
if(innum < number)
printf("The entered number is too small!\n");
times++;
if(innum == number)
{
printf("Congrats you guessed right!\n");
printf("It took you %d tries\n", times);
}
}
printf("Do you want to play again?");
scanf("%c", &playAgain);
if(playAgain == 'n')
break;
}
return 0;
}
The first problem is that it prints "Do you want to play again?" two times. Why is that? And the other problem is, how do I get the game to start again?
Thanks in advance.
This should work for you:
(What i did? Added a space by the scanf and put the declaration of number, times and innum in the for loop)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int number, innum, times;
char playAgain;
srand((unsigned)time(NULL));
for(;;) {
/*Declare the variables here*/
number = 5; //rand() % 1000;
innum = 0;
times = 0;
while(innum != number) {
printf("Enter a number: ");
scanf("%d", &innum);
if(innum > number)
printf("The entered number is too big!\n");
if(innum < number)
printf("The entered number is too small!\n");
times++;
if(innum == number) {
printf("Congrats you guessed right!\n");
printf("It took you %d tries\n", times);
}
}
printf("Do you want to play again?");
scanf(" %c", &playAgain);
//^Added space here to 'eat' any new line in the buffer
if(playAgain == 'n')
break;
}
return 0;
}
possible output:
Enter a number: 2
The entered number is too small!
Enter a number: 6
The entered number is too big!
Enter a number: 5
Congrats you guessed right!
It took you 3 tries
Do you want to play again?y
Enter a number: 3
The entered number is too small!
Enter a number: 5
Congrats you guessed right!
It took you 2 tries
Do you want to play again?n
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.
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.