Number guessing game in C - c

I had a problem at doing my number guessing game in C. While running the program it shows up return function when I put the char element in there. Can someone help me with this? Also how can I improve my code in order to make it workable? I'M really stuck with this issue.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
int main()
{
char s, n, q;
int b;
bool (1=true), (0=false);
int secret;
secret = rand();
int guess;
int seed;
srand(seed);
printf("Welcome to the guessing game!\n");
do{
printf("Menu: (s) to start a new game, (n) to set a new range, or (q) to quit:\n");
scanf("%s, %s, %s", s, n, q);
if((s==1))
{
printf("The secret number is Between 0 AND rand(). Guess\n");
scanf("%s", b);
}
else if((n ==1))
{
printf("Enter a new MAXIMUM\n");
scanf("%s", rand());
if(( s ==1))
{
printf("The secret number is Between 0 AND rand(). Guess\n");
scanf("%s", b);
printf("The secret number is between 0 and rand() Guess:");
scanf("%s", b);
if(guess = rand()){
printf("Congratulations you won, You took %d guesses!", b);
break;
}
else if(guess > rand())
{
printf("Too High, Guess again:");
}
else if(guess < rand()){
printf("Too Low, Guess Again:");
}
else{
printf("This number out of the number set!");
}
}
}
else{
printf("Unrecognized command");
}
}while(q == 1);
printf("You quited the game");
return 0;
}

This code has myriad issues to resolve. I'd suggest approaching your code writing process in small steps. It appears as though you wrote the entire program in one burst, ran it, and found it didn't work instead of incrementally adding small features and running each one to verify it works before moving on to the next step. Not doing this results in a difficult to debug program and a lack of understanding about how the program operates.
To be specific, try writing a three or four line program that collects and prints user input. Is the output working as you expect? Did you test its robustness on a variety of input? Can you write it to use a variety of data types? If something isn't working, did you research the problem and resolve it before steaming ahead?
Some areas of your program to investigate:
bool (1=true), (0=false); doesn't compile and isn't necessary for the program. If you #include <stdbool.h> you don't need to do this (you can simply write if (something == true)).
srand() is not properly called or seeded. Seed it once per program using the time() call from the header you included and call rand() once per game. Use the % operator to set the function output between 0 and max.
On each turn, compare guess against the value you previously stored rand() in rather than calling rand() during each comparison, which makes the game logic arbitrary.
%s input isn't appropriate; read chars %c and ints %d, passing appropriate variable references to scanf. scanf("%s, %s, %s", s, n, q); collects 3 whitespace separated strings for input instead of 1 char as the prompt suggests.
There is no game loop. Add an inner loop to run a game when the user chooses s and move your guess/response logic there.
Use more verbose variable names and correct brackets and indentation to improve readability.
Putting it all together, here's one possible working version. It could make better use of functions and implement secure user input (exercises for the reader):
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
char menu_choice;
int guess;
int guesses;
int secret;
int max = 100;
srand(time(NULL));
printf("Welcome to the guessing game!\n");
for (;;) {
printf("\nMenu: (s) to start a new game, (n) to set a new range, or (q) to quit: ");
scanf(" %c", &menu_choice);
if (menu_choice == 's') {
guesses = 0;
secret = rand() % max;
for (;;) {
printf("\nThe secret number is between 0 and %d. Enter a guess: ", max);
scanf("%d", &guess);
guesses++;
if (guess == secret) {
printf("\nCongratulations, you won! You guessed %d in %d guesses!\n", secret, guesses);
break;
}
else if (guess > secret) {
printf("Too high! Guess again.");
}
else if (guess < secret) {
printf("Too low! Guess again.");
}
else if (guess >= max) {
puts("Out of range");
}
}
}
else if (menu_choice == 'n') {
printf("\nEnter a new maximum: ");
scanf("%d", &max);
}
else if (menu_choice == 'q') {
puts("\nGoodbye!");
break;
}
else {
puts("\nUnrecognized command.");
}
}
return 0;
}
Sample run:
Welcome to the guessing game!
Menu: (s) to start a new game, (n) to set a new range, or (q) to quit: n
Enter a new maximum: 50
Menu: (s) to start a new game, (n) to set a new range, or (q) to quit: s
The secret number is between 0 and 50. Enter a guess: 25
Too low! Guess again.
The secret number is between 0 and 50. Enter a guess: 37
Too low! Guess again.
The secret number is between 0 and 50. Enter a guess: 43
Too low! Guess again.
The secret number is between 0 and 50. Enter a guess: 47
Congratulations, you won! You guessed 47 in 4 guesses!
Menu: (s) to start a new game, (n) to set a new range, or (q) to quit: q
Goodbye!

printf("Menu: (s) to start a new game, (n) to set a new range, or (q) to quit:\n");
scanf("%s, %s, %s", s, n, q);
you dont need to use three variables s,n,q. you should ask the user to enter a single choice. either to start a new game or to quit or aything else.
secondly, rand() returns a random number every time. you are supposed to store random number somewhere. like this
rand_num=rand()
also
if(guess = rand())
is a wrong way of comparison. this should be
if(guess==rand_num)
finally binary search is the solution for your problem. please refer it on internet

Related

Guessing Game in C programming

I built a guessing game in C programming using while loop, and I am having a problem with it during execution. So, when I print a number less than the guess number or greater than the guess number, I get the correct answer. But when the user enters the right answer, the screen shows the statement for the greater number "The number you entered is greater than the Secret Number." and then it shows the right statement below this "This is the secret Number." I think the problem could be because else statement does not define the condition for greater number but I am not sure how to solve this. Can somebody help me?
#include <stdio.h>
#include <stdlib.h>
int main()
{
//Guessing game
const int SecretNum = 4;
int guess;
while (guess != SecretNum){
printf("Enter a number: ");
scanf("%d", &guess);
if (guess < SecretNum){
printf("The number you entered is less than the Secret Number. \n");
} else printf("The number you entered is greater than the Secret Number.\n");
}
printf("This is the secret number.\n");
return 0;
}
You think the problem could be because else statement does not define the condition for greater number, so you should add that.
Also you have to initialize guess before using its value.
Formatting your code using indent properly is another important portion.
#include <stdio.h>
#include <stdlib.h>
int main()
{
//Guessing game
const int SecretNum = 4;
int guess = !SecretNum; /* initialize guess : guess will be different value from SecretNum using this */
while (guess != SecretNum){
printf("Enter a number: ");
scanf("%d", &guess);
if (guess < SecretNum){
printf("The number you entered is less than the Secret Number. \n");
} else if (guess > SecretNum) /* add condition */
printf("The number you entered is greater than the Secret Number.\n");
}
printf("This is the secret number.\n");
return 0;
}

taking the avg in C program

#include <stdio.h>
int main(int argc, char** argv)
{
int n;
int numbers;
int i=0;
int sum=0;
double average;
printf("\nPlease Enter the elements one by one\n");
while(i<n)
{
scanf("%d",&numbers);
sum = sum +numbers;
i++;
}
average = sum/n;
printf("\nSum of the %d Numbers = %d",n, sum);
printf("\nAverage of the %d Numbers = %.2f",n, average);
return 0;
}
i get the output "exited, floating point exception"
im not sure how to fix it.
i found online to add before the while loop
printf("\nPlease Enter How many Number you want?\n");
scanf("%d",&n);
but i dont want that there
Hint: you want the user to be able to signal to your application that they finished entering the elements. So you'd start with n=0 and then increment it each time the user provides a new element, and exit the loop when the user does "something" that you can detect.
For starters, let's say that the user closes the input by pressing Ctrl-Z on Windows, or Ctrl-D on Unix. The input will fail with EOF then - scanf() won't return 1 anymore. So you can check for this:
#include <stdio.h>
int main(int argc, char** argv)
{
int n = 0;
int sum = 0;
printf("\nPlease Enter the elements one by one. ");
#ifdef _WIN32
printf("Press Ctrl-Z to finish.\n");
#else
printf("Press Ctrl-D to finish.\n");
#endif
for (;;)
{
int number;
int result = scanf("%d", &number);
if (result == 1) break;
sum = sum + number;
n ++;
}
double average = (double)sum / n;
printf("\nSum of %d number(s) = %d\n",n, sum);
printf("Average of %d number(s) = %.2f\n",n, average);
return 0;
}
But this also ends the input when anything non-numeric is entered. Due to how scanf() is designed, you need to do something else to skip invalid input - usually by consuming input character-by-character until an end of line is reached. Thus, the variant that would not stop with invalid input, but allow the user another chance, needs to differentiate between scanf() returning EOF vs it returning 0 (invalid input):
#include <stdio.h>
void skip_input_till_next_line(void)
{
for (;;) {
char c;
if (scanf("%c", &c) != 1) break;
if (c == '\n') break;
}
}
int main(int argc, char** argv)
{
int n = 0;
int sum = 0;
printf("\nPlease Enter the elements one by one. ");
#ifdef _WIN32
printf("Press Ctrl-Z to finish.\n");
#else
printf("Press Ctrl-D to finish.\n");
#endif
for (;;)
{
int number;
int result = scanf(" %d", &number);
if (result == EOF) break;
if (result != 1) {
// We've got something that is not a number
fprintf(stderr, "Invalid input. Please try again.\n");
skip_input_till_next_line();
continue;
}
sum = sum + number;
n ++;
}
double average = (double)sum / n;
printf("\nSum of %d number(s) = %d\n",n, sum);
printf("Average of %d number(s) = %.2f\n",n, average);
return 0;
}
As a learner I'd recommend you to think about the pseudo code rather than the actual code.
Answers above are really good. I just want to add few things:
As a programmer you've to teach the hardware what you want it to do. Think:
Have you told your program how many numbers it takes as input? Is it limited or unlimited?
How will your program knows when to stop taking inputs?
I hope you agree that (sum n)/n would throw an error if user
doesn't enter anything or only enters 0?
What will happen if User enters characters instead?
Another important thing is that you need to clearly specify why you don't want to do certain thing in your code? This might help us understand better what are the limitations.
If you think about these things before and ask questions you'll learn better. Community is here to help you.

Program start-over function

I'm a beginner in C programming and i would appreciate if i could get some tips on how to set a program to restart? I'm currently building a guessing game, where the user has 10 attempts to guess the secret number which is provided randomly. I want the program to be able to offer the user a new round of game from start (Attempt number 1 Guess the number:), meaning re-run the program.
Here is the program:
#include <stdlib.h>
#include <time.h>
#define guessLimit 10
int main()
{
int secret_number;
int guess;
int guessCount = 0;
int outofGuesses = 0;
int i;
setbuf(stdout, NULL);
srand(time(0));
secret_number = rand() % 100;
printf("\n---GUESS THE SECRET NUMBER---\n");
for(i=1; i < 11; i++){
printf("Attempt number %d Guess a number: ", i);
scanf("%d", &guess);
if(guess == secret_number){
printf("Correct number!\n");
break;
}
if(guess < secret_number){
printf("sorry, number too small.\n");
}
else if(guess > secret_number){
printf("Sorry, number too big.\n");
}
if(i==10){
printf("Out of Attempts");
}
if(guess>99 || guess<0){
printf("Out of Range.\n");
}
}
return 0;
}
You could encapsulate your for loop in a while loop and have the conditional be an input from the console to indicate the user is done playing.
The best thing to do is to wrap the primary routine within a while loop and use a condition to determine if you want to either repeat or exit the loop. In this case, the do while construct works nicely. Simply ask the user if they would like to play again at the end of the loop. If not, then exit. Otherwise, repeat the code. Be mindful not to call srand(time(0)) within your loop or you reset the random sequence.
#include <stdlib.h>
#include <time.h>
#define guessLimit 10
int main()
{
int secret_number;
int guess;
int guessCount = 0;
int outofGuesses = 0;
int i;
char play;
srand(time(0));
do {
secret_number = rand() % 100;
printf("\n---GUESS THE SECRET NUMBER---\n");
for(i=1; i < 11; i++){
printf("Attempt number %d Guess a number: ", i);
scanf("%d", &guess);
if(guess == secret_number){
printf("Correct number!\n");
break;
}
if(guess < secret_number){
printf("sorry, number too small.\n");
}
else if(guess > secret_number){
printf("Sorry, number too big.\n");
}
if(i==10){
printf("Out of Attempts");
}
if(guess>99 || guess<0){
printf("Out of Range.\n");
}
}
printf("\nPlay again? (y/n): ");
scanf(" %c", &play);
} while (play == 'y');
return 0;
}
As a side note - giving the user 10 chances to guess a number in the range 1-100 is too generous if you're providing "higher/lower" feedback. If my calculations are correct, a binary search would find the answer in maximally log2(100)=6.64... attempts. In other words, you should be able to find the answer in no more than 7 attempts if you know what you're doing. A binary search works of course by guessing the number in between the bounds and then adjusting the bounds according to your feedback.

(C programming) while loop only works in a specific order

I'm writing a silly code as a joke, sort of a number guessing thing. I thought it was fine until I realized the correct things would only print if I put in the numbers in a specific order. I'm a bit of a beginner, so I'm not sure why it's only printing correctly if I type in the numbers in an order. Is this a condition of while loops in general? Is there a way I can fix this so that it doesn't matter what order the numbers go in? Any insight would be greatly appreciated.
Here is my code:
#include <stdio.h>
#include <math.h>
#include <unistd.h>
#include <string.h>
int number;
int main()
{
printf("Enter a number!\n");
scanf("%d", &number);
while ((number != 69) && (number != 420))
{
printf("hmmm, not the number i was looking for... Enter another number!\n");
scanf("%d", &number);
while (number == 666)
{
printf("what are you, emo? try again!\n");
scanf("%d", &number);
while (number == 420)
{
printf("lol close, try the other Funny Number\n");
scanf("%d", &number);
while ((number != 69) && (number != 420))
{
printf("hmmm, not the number i was looking for... Enter another number!\n");
scanf("%d", &number);
}
while (number == 69)
{
printf("haha nice\n");
return 0;
}
}
}
}
}
What you may be running into is you enter a number and then it gets stuck in an "inner" loop scanning and checking and failing an inner condition instead of all of them.
I'm not sure if you have yet to discover if/else if/else but this is normally how you might check conditional statements. I will write this in pseudo code to give you a chance to write it yourself in C.
number = 0
print "Enter a number"
while number != 69
number = get number
if number == 666
print "What are you..."
else if number == 420
print "lol close..."
else if number == 69
print "haha nice..."
else
print "hmmm..."
For extra fun check out switch statements.

For loop guessing game in C

a program to get the user to guess the number that the program has picked as the lucky number. It uses one for loop and plenty of if statements. The problem is that my code stops after 2 tries, but suppose to give user 3 tries. Here is what I have so far:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int iSecret, iGuess;
srand(time(NULL));
iSecret = rand() % 20 + 1;
int tries = 0;
printf("\nWelcome to the number guessing game!\nFor each game, you have at most 3 chances to guess a secret number from 1 to 20.\n");
for (tries = 0; tries < 3 || iSecret == iGuess; tries++)
{
printf("Please, enter a number between 1 and 20! ");
scanf("%d", &iGuess);
if (iGuess == iSecret)
{
printf("\nCongratulations! You won!");
return 0;
}
else if (iGuess > iSecret)
{
tries++;
printf("\nYour guess was too high.\n");
}
else if (iGuess < iSecret)
{
tries++;
printf("\nYour guess was too low.\n");
}
if (tries == 3)
break;
}
printf("\nYou have reached your third trials. The correct number is %d.\n",
iSecret);
return 0;
}
You are incrementing tries twice: once in the for definition, and also later in the body of the loop.
Remove the extra tries++ statements.
You increment tries inside the code, as well as in the for statement. Strip out the tries++ statements in the if-blocks.
You're incrementing the variable tries multiple times during loop execution,
once every turn and everytime you didn't guess your secret right
for loop already increments tries .. you don't need to do tries++ inside if statements
you don't need the || condition in for loop as you are already doing the check in if statements
here is the fixed code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
int iSecret, iGuess;
srand ( time(NULL) );
iSecret = rand() % 20 + 1;
int tries = 0;
printf("\nWelcome to the number guessing game!\nFor each game, you have at most 3 chances to guess a secret number from 1 to 20.\n");
for (tries = 0; tries < 3 ; tries++) {
printf ("Please, enter a number between 1 and 20! ");
scanf ("%d", &iGuess);
if(iGuess == iSecret){
printf ("\nCongratulations! You won!");
return 0;
}
else if (iGuess > iSecret){
printf ("\nYour guess was too high.\n");
}
else if (iGuess < iSecret){
printf ("\nYour guess was too low.\n");
}
}
printf ("\nYou have reached your third trials. The correct number is %d.\n", iSecret);
return 0;
}
Output:
$ ./test
Welcome to the number guessing game!
For each game, you have at most 3 chances to guess a secret number from 1 to 20.
Please, enter a number between 1 and 20! 2
Your guess was too low.
Please, enter a number between 1 and 20! 3
Your guess was too low.
Please, enter a number between 1 and 20! 4
Your guess was too low.
You have reached your third trials. The correct number is 10.
in addition to incrementing tries too many times, the code is overly complicated, you can simplify the logic like
int main ()
{
int iSecret, iGuess;
srand ( time(NULL) );
iSecret = rand() % 20 + 1;
int tries = 0;
printf("\nWelcome to the number guessing game!\nFor each game, you have at most 3 chances to guess a secret number from 1 to 20.\n");
for (tries = 0; tries < 3; tries++) {
printf ("Please, enter a number between 1 and 20! ");
scanf ("%d", &iGuess);
if(iGuess == iSecret) {
printf ("\nCongratulations! You won!");
return 0;
}
printf ( "\nYour guess was too %s.\n", iGuess>iSecret?"high":"low");
}
printf ("\nYou have reached your third trials. The correct number is %d.\n", iSecret);
return 0;
}

Resources