How can I restart the program in C? - c

Hi I'm new to C and I wrote a simple program. I want to restart the program if the user picked the wrong choice, here is the code:
#include <stdio.h>
#include <cs50.h>
int main(void){
char choices;
float math, pc, svt, eng, philo;
do {
do {
printf("Enter your math score: ");
math = GetFloat();
}
while( math>20 || math<0);
do {
printf("Enter your pc score: ");
pc = GetFloat();
}
while(pc>20 || pc<0);
do {
printf("Enter your svt score: ");
svt = GetFloat();
}
while(svt>20 || svt<0);
do {
printf("Enter your eng score: ");
eng = GetFloat();
}
while(eng>20 || eng<0);
do {
printf("Enter your philo score: ");
philo = GetFloat();
}
while(philo>20 || philo<0);
printf("Are you pc or sm?\n");
printf("Write 1 for pc. 2 for sm\n");
int choice = GetInt();
if(choice == 1){
float score = (math*7 + pc*7 + svt*7 + eng*2 + philo*2)/25;
printf("Your score is %.2f\n", score);
}
else if(choice == 2){
float score = (math*9 + pc*7 + svt*3+ eng*2 + philo*2)/23;
printf("Your score is %.2f\n", score);
}
else{
printf("You've picked the wrong choice \n");
}
printf("Do you want to try it again? (Y/N) ");
choices = getchar();
while (choices != '\n' && getchar() != '\n') {};
} while (choices == 'Y' || choices == 'y');
}
So what I mean here, I want to insert the code in the else block to restart the program and give the user another time. It would be very nice if I can just make him choose again between 1 or 2.
If you have any suggestions or improvement please don't hesitate to comment.
Thanks :)

What you need is do while loop surrounding choice code:
int choice;
do {
choice = GetInt();
if (choice == 1) {
float score = (math*7 + pc*7 + svt*7 + eng*2 + philo*2)/25;
printf("Your score is %.2f\n", score);
}
else if (choice == 2) {
float score = (math*9 + pc*7 + svt*3+ eng*2 + philo*2)/23;
printf("Your score is %.2f\n", score);
}
else {
printf("You've picked the wrong choice, try again.\n");
}
} while(choice < 1 || choice > 2)

You already have a loop to try again, you can reuse that loop to get the user input again for choice. So, if the user enters choice other than 1 or 2, you can set choices = Y and redo the loop. without asking for user input.
Code is below.
#include <stdio.h>
#include <cs50.h>
int main(void)
{
char choices;
float math, pc, svt, eng, philo;
do
{
// Other code here
int choice = GetInt();
if(choice == 1){
float score = (math*7 + pc*7 + svt*7 + eng*2 + philo*2)/25;
printf("Your score is %.2f\n", score);
}
else if(choice == 2){
float score = (math*9 + pc*7 + svt*3+ eng*2 + philo*2)/23;
printf("Your score is %.2f\n", score);
}
else{
printf("You've picked the wrong choice \n");
choices = 'Y';
}
if ((choice == 1) || (choice == 2))
{
printf("Do you want to try it again? (Y/N) ");
choices = getchar();
while (choices != '\n' && getchar() != '\n') {};
}
} while (choices == 'Y' || choices == 'y');
}

Well, if somebody reading this has to actually restart their program for a more nontrivial reason (e.g. an exception handler, like me a couple of minutes ago), there is a portable way to to so in C, like so:
#include <setjmp.h> //from C standard library
jmp_buf restart_env;
int main() {
//some initialization you don't want to repeat
if(setjmp(restart_env)) {
//restarted, do whatever
}
//the code
}
void evenFromAnotherFunction() {
//...
if(something_that_justifies_this_approach) {
longjmp(restart_env, 1); //this restarts the program
//unreachable
}
//...
}
Note that you had better not use this if there's a better way. Using setjmp is bound to produce extremely annoying bugs. If you have no choice, remember that some data may preserve the value it had before calling setjmp for the first time, and some may not, so don't assume anything.

Related

C code stops after if statement inside while loop

I am trying to create a program that assigns the user one of three questions at random. I figured out that part however I want to make it so that after they correctly answer their assigned question that they are asked if they want to take another one.
int main(void) {
srand(time(0));
int luckyNumber;
int quizNumber;
int score;
int totalScore;
int averageScore;
int attempts;
char answer1;
char answer2;
char answer3;
char opt1;
char loop = 'y';
printf("Welcome to the quiz program!\n");
while(loop == 'y') {
printf("Please enter a lucky number between 1 and 9: ");
scanf("%d", &luckyNumber);
quizNumber = rand() % 3 + 1;
printf("Your quiz number is %d\n", quizNumber);
if (quizNumber == quizNumber) {
while (score != 5) {
printf("Quiz 1\n");
printf("A. True\n");
printf("B. False\n");
printf("Enter your answer: ");
scanf(" %c", &answer1);
if (answer1 == 'B' || answer1 == 'b') {
printf("Correct!\n");
score = score + 5;
break;
}
else {
printf("Incorrect!, Try again.\n");
printf("\n");
}
break;
}
break;
}
printf("Would you like to go again y/n?");
scanf("%c", &loop);
if (loop != 'y')
loop = 'n';
}
return 0;
}
The problem I am having is after I compile the code, it stops when the correct answer is input rather than going on to ask if the user would like to do another quiz.

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?

I don't understand why a part of my code isn't connecting to the rest

I have an assignment for a coding class where I have to create a code for the rock, paper scissors game, with different functions, calling rock 1 and paper 2 and scissors 3.
I also have to create a menu, then have the person chose, save that, then have the computer generate a random number and then print what they played, what the computer played and who won.
However, the last part isn't connecting, and I don't understand where I went wrong, so I'm really really lost and I would really appreciate any help.
For reference here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
float response, choice;
int playerInput() {
printf(" For rock press 1\n ");
printf("For paper press 2\n ");
printf("For scissors press 3\n ");
printf("What would you like to play? ");
scanf("%f", &response);
return response;
}
int computerChoice() {
int lower = 1, upper = 3, count = 1;
srand(time(0));
printf("The random number that: ");
for (int i = 0; i < count; i++) {
int choice = (rand() % (upper - lower + 1)) + lower;
printf("the computer chose is %d ", choice);
}
return choice;
}
void displayWinner() {
if (response == choice) {
printf("You tied, lets play again");
}
if (choice == 1 && response == 2) {
printf("you won");
}
if (choice == 1 && response == 3) {
printf("computer won");
}
if (choice == 2 && response == 1) {
printf("computer won");
}
if (choice == 2 && response == 3) {
printf("you won");
}
if (choice == 3 && response == 1) {
printf("you won");
}
if (choice == 3 && response == 2) {
printf("computer won");
}
}
int main(void) {
int pinput, cinput, dinput;
pinput = playerInput();
cinput = computerChoice();
displayWinner();
return 0;
}
int choice =
But why declare a local with the same name as a global. I suggest that's your first mistake.
On fixing it you'll find the next line prints garbage because it's now printing a %d from a float (that got widened to a double).

Random number game 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.

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