Simple random numbers game program - c

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.

Related

calling scanf inside do while loop is breaking the loop

I have a do while loop. When I run it without scanf(), it runs properly. But if I enter a scanf() it breaks the loop! Why???
The code:
With scanf()
void main(){
int num = prng() % 100, guessed, guesses = 0;
bool win = false;
printf("The Game Begins. You Have To Guess A Number\n");
do{ //A do while loop untill the user guesses the correct number
printf("Guess a number\n");
scanf("%d", guessed);
guesses++;
}while (!check(guessed, num));
printf("Yayy!!! You won the game in %d guesses!!", guesses); //Message after guessing the correct number
return;
}
This breaks the loop instantly:
> .\a.exe
The Game Begins. You Have To Guess A Number
Guess a number
5
>
But when I run it without the scanf()
void main(){
int num = prng() % 100, guessed, guesses = 0;
bool win = false;
printf("The Game Begins. You Have To Guess A Number\n");
do{ //A do while loop untill the user guesses the correct number
printf("Guess a number\n");
guessed = num;
// scanf("%d", guessed);
guesses++;
}while (!check(guessed, num));
printf("Yayy!!! You won the game in %d guesses!!", guesses); //Message after guessing the correct number
return;
}
It works fine!!
> .\a.exe
The Game Begins. You Have To Guess A Number
Guess a number
Hurrayyy!!!! You got the number!!!!!!!!!Yayy!!! You won the game in 1 guesses!!
>
Can you explain what is the actual problem?
You need to add & in front of guessed variable within the scanf function.
scanf("%d", &guessed);
An explanation of how scanf works can be seen here.

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

Do while loop with Character input

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

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.

C Programming Logic Error?

The following code compiles fine, but does not allow the user to choose whether or not the program is to run again. After giving the user the answer, the program automatically terminates. I placed the main code in a "do while" loop to have the ability to convert more than one time if I wanted too. I have tried to run the program in the command line (Mac and Ubuntu machines) and within XCode with the exact same results. Any assistance would be greatly appreciated.
C Beginner
P.S. Compiling on MacBookPro running Snow Leopard.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char anotherIteration = 'Y';
do
{
const float Centimeter = 2.54f;
float inches = 0.0f;
float result = 0.0f;
// user prompt
printf("\nEnter inches: ");
scanf("%f", &inches);
if (inches < 0) {
printf("\nTry again. Enter a positive number.\n");
break;
} else {
// calculate result
result = inches * Centimeter;
}
printf("%0.2f inches is %0.2f centimeters.\n", inches, result);
// flush input
fflush(stdin);
// user prompt
printf("\nWould you like to run the program again? (Y/N): ");
scanf("%c", &anotherIteration);
if ((anotherIteration != 'Y') || (anotherIteration != 'N'))
{
printf("\nEnter a Y or a N.");
break;
}
} while(toupper(anotherIteration == 'Y'));
printf("Program terminated.\n");
return 0;
}
You probably meant...
} while(toupper(anotherIteration) == 'Y');
since you want to convert the character, and then compare it with 'Y'.
Condition
if ((anotherIteration != 'Y') || (anotherIteration != 'N'))
is always true, so your program will terminate regardless of user input.
Moreover, you put break into virtually every if in your code intended to handle incorrect input. break will terminate the cycle and the program. This is a rather strange logic: ask user to try again and then immediately terminate the program without giving the user opportunity to actually try again. Why are you terminating the program instead of allowing the user to reenter the input?
Well,
while(toupper(anotherIteration == 'Y'));
looks like you meant to say
while(toupper(anotherIteration) == 'Y');
.. but there may be other issues.
This works.
/* convert inches to centimeters */
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char anotherIteration = 'Y';
do
{
const float Centimeter = 2.54f;
float inches = 0.0f;
float result = 0.0f;
// user prompt
printf("\nEnter inches: ");
scanf("%f", &inches);
if (inches < 0)
{
printf("\nTry again. Enter a positive number.\n");
break;
}
else
// calculate result
result = inches * Centimeter;
printf("%0.2f inches is %0.2f centimeters.\n", inches, result);
// flush input
fflush(stdin);
// user prompt
printf("\nWould you like to run the program again? (Y/N): ");
scanf("%c", &anotherIteration);
} while(toupper(anotherIteration) != 'N');
printf("Program terminated.\n");
return 0;
}
You have two big bugs here. The first one is what you have asked for in your
question:
} while(toupper(anotherIteration == 'Y'));
anotherIteration == 'Y' will return either 1 or 0, which both equal 0 after
being passed through toupper.
What you want instead is:
} while(toupper(anotherIteration) == 'Y');
The other bug lies here:
printf("\nWould you like to run the program again? (Y/N): ");
scanf("%c", &anotherIteration);
if ((anotherIteration != 'Y') || (anotherIteration != 'N'))
{
printf("\nEnter a Y or a N.");
break; // This breaks out of hte main program loop!
}
What you really want to do is ask the user again if they enter something wrong,
like this:
do
{
printf("\nWould you like to run the program again? (Y/N): ");
scanf("%c", &anotherIteration);
if ((anotherIteration != 'Y') && (anotherIteration != 'N'))
printf("\nEnter a Y or a N.");
} while ((anotherIteration != 'Y') && (anotherIteration != 'N'));
You have a few bugs, but since you're learning, you should probably figure them out. The answer to your specific question on this program is that you probably want to be using fpurge() for stdin, not fflush().
One error:
while(toupper(anotherIteration == 'Y'))
should be
while(toupper(anotherIteration) == 'Y')

Resources