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

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

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?

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?

Number guessing game always returns the same output

I'm making a simple number guessing game from 1 - 10 using an if...else statement, it worked the first time, but it seems it always outputs "You didn't guess it correctly." when I'm guessing or the other way around. Would be great for some help, so here are the solutions I made as of asking this question:
//This is the first solution I've come up with.
#include <stdio.h>
#include <stdbool.h>
int main() {
int guessingNumber = '5';
printf("Guess from 1-10: ");
scanf("%d", &guessingNumber);
if (guessingNumber == true) {
printf("You guessed it!\n");
}
else {
printf("You didn't guess it correctly.\n");
}
return 0;
}
//Here is the second one.
#include <stdio.h>
int main() {
int guessingNumber = '5';
int guess;
printf("Guess from 1-10: ");
scanf("%d", &guess);
if (guessingNumber == guess) {
printf("You guessed it!\n");
}
else {
printf("You didn't guess it correctly.\n");
}
return 0;
}
I'm sure that the problem causing this is in this lines from the first solution:
printf("Guess from 1-10: ");
scanf("%d", &guessingNumber);
if (guessingNumber == true) {
printf("You guessed it!\n");
and this from the second solution that I'm sure the problem (might also) came:
printf("Guess from 1-10: ");
scanf("%d", &guess);
if (guessingNumber == guess) {
printf("You guessed it!\n");
The comparison is unsafe int and a bool. Check the following.
int main()
{
int actualNumber, guessingNumber = 5;
printf("Guess from 1-10: ");
scanf_s("%d", &actualNumber);
if (guessingNumber == actualNumber) {
printf("You guessed it!\n");
}
else {
printf("You didn't guess it correctly.\n");
}
return 0;
}

C Programming Guessing Game

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", &currentGuess);
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", &currentGuess);
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;
}

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

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

Resources