How to make the program restart if I press a certain button - c

I've recently written this "guess the number" program. My problem is that I want the program to restart when I press "y" after the "Play again" question comes. Any ideas? :)
srand( time(NULL) );
int secretNumber = rand()%100 + 1;
int guess = 0;
int counter = 0;
printf("I'm thinking of a number between 1 and 100\n");
printf("What is your guess?\n");
while(1)
{
counter++;
scanf("%d", &guess);
if (guess == secretNumber)
{
printf("It took you %d tries\n", counter);
printf("Play again (y/n)?\n");
break;
}
if (guess < secretNumber)
{
printf("Too low!\n");
}
if (guess > secretNumber)
{
printf("Too high!\n");
}

Put the entire code snippet you have inside another while(1) statement:
srand(time(NULL));
while(1)
{
int secretNumber = rand()%100 + 1;
int guess = 0;
int counter = 0;
printf("I'm thinking of a number between 1 and 100\n");
printf("What is your guess?\n");
while(1)
{
//code for guessing number
}
printf("Play again? ");
if (getchar() != 'y')
{
break;
}
}

This
printf("I'm thinking of a number between 1 and 100\n");
printf("What is your guess?\n");
needs to be inside your loop, unless you only want to give them one guess.
The easiest way to do what you want is to create a new secret number when they guess right, and bail out of your loop if they answer "No" to "do you want to play again?"

You can use another variable. like below.
char userinput = 'y';
while(input == 'y')
{
//your logic here
//And at the end use one scanf
printf("Play again (y/n)?\n");
scanf("%c", &userinput);
}
You need to add one new variable, In above case it's userinput.

use a while loop, with a loop variable of type bool say dec initially True. Put your code and initialize all the variables inside the loop, so that they can have a local scope and gets destroyed each time the loop is complete. Ask user for the dec variable if it presses "y" set it to True else set it to False. so that the loop may be skipped this time
code may be like :
char cha;
bool dec=True;
while(dec){
srand( time(NULL) );
int secretNumber = rand()%100 + 1;
int guess = 0;
int counter = 0;
printf("I'm thinking of a number between 1 and 100\n");
printf("What is your guess?\n");
while(1)
{
//code for guessing number
}
printf("Play again? ");
scanf("%c",&cha);
if (char== 'y')
bool=True;
else bool=False;
}

Related

Fixing do-while loop problem and how to add do you want to play again?

I started C courses today and teacher assigned to do:
Guess the number and if the number is higher say it is higher but if it is lower say it is lower and count every time you guess AND if you guess it ten times already then say do you want to try again?
I don't know why my code is stop when I just play it only 1 time and how to do the "do you want to play again?"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int x;
char name[20], result;
int count = 0;
int number;
srand(time(NULL));
x = rand() % 100 + 1;
printf("What's your name :");
scanf("%s", &name);
printf("Hello!! %s\n", name);
printf("Guess the number : ");
scanf(" %d", &number);
do {
count++;
if (x > number) {
printf("This is your count : %d\n",count);
printf("The number is higher\n");
} else
if (x < number) {
printf("This is your count : %d\n",count);
printf("The number is lower\n");
} else
if (x == number) {
printf("\nYou're right!!, the number is %d",x);
}
} while (count == 10);
}
The code allows only 1 try because the test while (count == 10) is false at the end of the first iteration. You should have while (count < 10).
You should move the input call scanf(" %d", &number); inside the loop.
Also note that you should break from the loop if the number was found.
For the Do you want to play again? part, you could wrap this code in another loop.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
char name[20] = "", ch;
srand(time(NULL));
printf("What's your name: ");
scanf("%19s", &name);
printf("Hello!! %s\n", name);
for (;;) {
int x = rand() % 100 + 1;
int number;
for (int count = 1; count <= 10; count++) {
printf("Enter your guess: ");
if (scanf(" %d", &number) != 1)
break;
if (x > number) {
printf("This is your count: %d\n",count);
printf("The number is higher\n");
} else
if (x < number) {
printf("This is your count: %d\n",count);
printf("The number is lower\n");
} else
if (x == number) {
printf("You're right!!, the number is %d\n",x);
break;
}
}
printf("Do you want to play again? ");
if (scanf(" %c", &ch) != 1)
break;
if (ch != 'y' && ch != 'Y')
break;
}
return 0;
}
The loop condition in the line
} while (count == 10);
is wrong, because it will be false after the first loop iteration. It would be more meaningful to write
} while (count < 10);
Also, you probably want to put the lines
printf("Guess the number : ");
scanf(" %d", &number);
inside the loop, so that they get executed more than once. Otherwise, you will be processing the same user guess 10 times, which is not what you want.
Another issue is that you don't want the loop to always run 10 times. You only want it to run 10 times if the user hasn't guessed the number. If the user has guessed the number, you want to break out of the loop immediately, without waiting for count to reach 10. For this, you can use the break statement.
I'm a VB guy mostly but can you use while count <= 10?
Perhaps Do Until?

C for loop, How do I continuously prompt the user?

I am learning about loops such as for and while loops, so I decided to put myself to the test and write a program which you can see the code for below. The program gives the user a range of options to enter an option, but the problem I have is that i want to be able to continuously ask the user to "Enter a command" after an operation has completed.
For example, if I entered 1, the necessary code would be executed but then the whole program just ends. How can I enhance this program so it continuously asks the user to enter new commands until the user forcibly exits by entering 0?
#include <stdio.h>
int main()
{
int n;
int credit = 0;
int YN;
printf("Welcome to Cash booking software Version 2.145\n");
printf("--------------------------------------------------------\n");
printf("Use the following options:\n");
printf("0 -- Exit\n");
printf("1 -- Display Credit\n");
printf("2 -- Change Credit\n");
printf("3 -- Remove Credit\n");
printf("\n");
for ( ; ; )
{
printf("Enter a command: ");
scanf("%d", &n);
if (n == 0)
{
return 0;
}
else if (n == 1)
{
printf("Your credit is £%d", credit);
}
else if (n == 2)
{
printf("Enter a new credit value: \n");
scanf("%d", &credit);
printf("Your new credit value is %d", credit);
}
else if (n == 3)
{
printf("Are you sure you want to remove your Credit value? (Y=1/N=2)");
scanf("%d", &YN);
if (YN == 1)
{
credit = 0;
}
else
;
}
return 0;
}
}
As other users explained return 0; inside of the loop is what is causing the problem and moving it out would solve it, But since you're learning about loops I think this is a great example to teach you something.
Usually you should only use a for loop when you have some parameter that defines de number of times the loop will be executed. The fact that you just used for( ; ; ) is a huge red flag for ther is a betther way to do this.
For example the proper way to write an infinite loop in c is while(1){//code in the loop}. So you could change your for loop with this and it will work fine (relocating return 0; in the correct location).
But since in this code you dont really want an infinite loop (usually they're a bad idea), but you want the loop to run until is pressed 0, the best solution is to use a do{} while(); loop where inside of do you check if either 1, 2 or 3 is pressed and perform their functionality, and then in the while condition you check if 0 has been pressed, and only in that case the program exits.
This is how the code would look like:
do{
printf("Enter a command: ");
scanf("%d", &n);
if (n == 1){
printf("Your credit is £%d\n", credit); // \n added
}
else if (n == 2){
printf("Enter a new credit value: \n");
scanf("%d", &credit);
printf("Your new credit value is %d\n", credit); // \n added
}
else if (n == 3){
printf("Are you sure you want to remove your Credit value? (Y=1/N=2):");
scanf("%d", &YN);
if (YN == 1){
credit = 0;
}
}
} while(n != 0);
return 0;
Also note that I added \n in some printf() commands for better visualization.
use continue statement at the end of each condition , and you can use break statement instead of return 0, so the code will be :
if (n == 0)
{
break;
}
else if (n == 1)
{
printf("Your credit is £%d ", credit);
continue;
}
else if (n == 2)
{
printf("Enter a new credit value: \n");
scanf("%d", &credit);
printf("Your new credit value is %d ", credit);
continue;
}
else if (n == 3)
{
printf("Are you sure you want to remove your Credit value? (Y=1/N=2) : ");
scanf("%d", &YN);
if (YN == 1)
{
credit = 0;
continue;
}
else {
continue;
}

Is my do while loop not working due to this function?

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;
}

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;
}

Is there any way to avoid using exit(0)?

I wanted to practice a little with separating logic into functions and using basic recursion in a primitive "Guess my number game", just as a sort of way to see where I'm at in my C programming.
Here's the code:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
char playAgain()
{
printf("\nDo you wanna play again? ");
char resp = 0;
while (TRUE) {
scanf("%c", &resp);
if (resp == 'y') break;
if (resp == 'n') break;
}
return resp;
}
void play()
{
srand((int)time(NULL));
int num = rand() % 10 + 1;
int guess = 0;
int flag = 0;
int attempts = 0;
printf("\nGuess the number: \n");
while (TRUE) {
scanf("%d", &guess);
if (num > guess)
{
printf("Too low! ");
attempts++;
}
else if (num < guess)
{
printf("Too high! ");
attempts++;
}
else if (num == guess)
{
attempts++;
printf("You won! You did it in %d attempts", attempts);
char yo = playAgain();
if (yo == 'y') play();
else if (yo == 'n') exit(0);
else {
printf("Error!");
exit(1);
}
}
}
}
int main()
{
return play();
}
Everything works but I've only managed to make it quit when the user says 'n', by using exit(0) and I've heard it's bad practice. But having spent a couple of hours just noodling around and trying all the other ways I could think of (using flags, for example), I just couldn't make it work. It works for 'y', but as soon as I enter 'n', it doesn't quit and just calls the playAgain() function one more time, or freezes altogether (nothing happens).
I feel ashamed for not being able to solve this, but I'm out of ideas. Is there any other way, other than exit(0), to make it jump out of play() straight to return 0 in main()? The problem seems to be that I have an infinite game loop, so when the answer is 'n', I need to break out of the loop AND out of the play() function, and that has proven to be problematic. I remember being able to do this easily when I had no functions, but just all the relevant code in main(), but the whole point of this is to use functions. For example, I can't figure out how to make use of a return type of play(), so that it knows when to quit.
P.S. As always, seeing how often people get accused of this, I assure you this is not homework because I am, and always have been, doing programming strictly as a hobby. There's no professor I answer to, apart from you :-) And trust me that I did try to figure out a solution, but nothing seems to work. It's a question of good vs. bad design, so it's especially important for my self-teaching. exit(0) seems to be a hackish solution and serves no educational purpose.
P.P.S. By the way, I'm using xCode, and the program runs in its output window. Probably not, but maybe that's the reason quitting with 'n' doesn't work?
SUMMARY: The code works fine except when the answer is 'n', in which case it just asks "Do you wanna play?" again, or doesn't do anything at all.
Make your play function return a result:- int play( void ) {
then instead of exit(1) and exit(0); use return 1; and return 0;
at the end of play put return 0;
then in main
{
return play();
}
instead of recursion, just make a loop
int play( void)
{
srand((int)time(NULL));
int num;
int guess;
int flag;
while(1)
{
num = rand() % 10 + 1;
guess = 0;
flag = 0;
printf("\nGuess the number %d: \n", num);
while (1) {
scanf("%d", &guess);
if (num > guess)
{
printf("Too low! ");
}
else if (num < guess)
{
printf("Too high! ");
}
else if (num == guess)
{
printf("You won!");
char yo = playAgain();
if (yo == 'y') break;
else if (yo == 'n') return 0;
else {
printf("Error!");
return 1;
}
}
}
}
}
and if you want more of a game engine type approach
enum {
GUESS,
GAMEOVER,
QUIT,
} GAME_STATES;
typedef struct
{
enum GAME_STATES state;
int num;
int game_over;
} guessing_game_t;
void init_game(guessing_game_t* g)
{
g->state = GUESS;
g->game_over = 0;
g->num = rand() % 10 + 1;
}
void evaluate_guess(guessing_game_t* g, int guess)
{
if(g->num == guess)
{
printf("You won!");
g->state = GAMEOVER;
}
else if (g->num > guess)
{
printf("Too low! ");
}
else if (g->num < guess)
{
printf("Too high! ");
}
}
int input_guess( void )
{
int guess;
scanf("%d", &guess);
return guess;
}
void play_again( guessing_game_t* g)
{
char resp = 0;
printf("\nDo you wanna play again? ");
scanf("%c", &resp);
if (resp == 'y') init_game(g);
if (resp == 'n') g->state = QUIT;
}
void play( guessing_game_t* g)
{
while(g->state != QUIT)
{
switch(g->state)
{
case GUESS:
evaluate_guess(g, input_guess());
break;
case GAMEOVER:
play_again(g);
break;
}
}
}
int main()
{
guessing_game_t game;
init_game(&game);
play(&game);
}
You can put a flag before going on with the loop
Change the while(true) to while (continue_play), continue_play is the name of flag for an example
Then,
if (yo == 'n') exit(0);
can be change to
if (yo == 'n') continue_play=false;
and do the similar for the exit(1) case
continue_play then will be a flag to exit from the function.
You have one more thing that the program will end: the logic of your code is made like that u can also use break; instead of exit(0) and exit(1) because you use while loop and you will break it and the program will end.
Since you may recursive call you play() function, I think exit it with exit(0) is a proper choose.
Acutall, I do not think using recursion to implement play() is a good idea at all, two infinite loops are enough. You could implemet it like this:
void play(void)
{
srand((int)time(NULL));
int num;
int guess = 0;
int attempts = 0;
int try_again = 1;
while (try_again) {
num = rand() % 10 + 1;
printf("\nGuess the number: \n");
while (TRUE) {
scanf("%d", &guess);
if (num > guess)
{
printf("Too low! ");
attempts++;
}
else if (num < guess)
{
printf("Too high! ");
attempts++;
}
else if (num == guess)
{
attempts++;
printf("You won! You did it in %d attempts", attempts);
char yo = playAgain();
if (yo == 'n') try_again = 0;
break;
}
}
}
}

Resources