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;
}
Related
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.
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.
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
you enter a number and the program will find if the number is prime or not
so when I enter the number 7 for the first time it will show you 'the number is prime'
then I enter 8 and it will show you 'the number is not prime'
after that I re_enter the number 7 and it will show you 'the number is not prime'
I don't know where is the problem
please help me
an example photo from here
and my code is :
#include <stdio.h>
#include <stdlib.h>
int main (void){
int n;
int t;
int isPrime=0;
char var;
while(var!='q'){
printf("q=quit p=prime :");
fflush(stdin);
scanf("%c",&var);
if(var=='p'){
printf("plz put the number value :");
scanf(" %d",&n);
for(t=2;t<=n/2;t++){
if (n%t==0){
isPrime=1;
break;
}
}
if(isPrime==0){
printf("%d is a prime number\n",n);
}
else{
printf("%d is not a prime number\n",n);
}
}
else if(var=='q'){
printf("thank you bye\n");
break;
}
else{
printf("a wrong letter\n");
}
}
return 0;
}
You need to set isPrime to 0 each time the user enters a number. Otherwise, it still holds the value from the previous number.
Move the variable declaration
int isPrime = 0;
inside the while loop.
BTW, isn't that variable name backwards? You set it to 1 (i.e. true) when you discover that there's a number that divides it equally. But that's when the number is not prime.
You forgot to reset isPrime back to zero inside the "while" loop.
By they way, looks like you are doing this as a learning exercise. That's good, there's no better way to learn than to try things out.
Here's a tip in C, any non-zero value is treated as "true", and zero is treated as "false". So instead of this:
if (myFlag==1) { ... do something }
Just write this:
if (myFlag) { ... do something }
Write a program to continue to read in positive integers
till a prime is encountered. Assume at least one number will be entered.
Eg.
Please enter #: 8
Please enter #: 9
Please enter #: 10
Please enter #: 11
Thanks you entered a prime, bye.
The main problem that I am having is the continuation until the prime occurs. The code I have to test if the number is prime is here:
// PRIME NUMBER TEST
#include <stdio.h>
int main () {
int number, n, is_prime = 0;
printf("Enter number: ");
scanf("%d", &number);
for (n=2; n<=number/2; n++) {
if (number%n==0)
is_prime = 1;
while(is_prime == 1) {
printf("Enter #: ");
scanf("%d", &number);
}
}
if (is_prime == 0)
printf("%d is a prime number.\n", number);
system("PAUSE");
return 0;
}
I know that it would be a for loop to keep it going and just initializing a counter until the prime occurs, but for whatever reason I just can't get it right. Thanks for the help.
You need to walk though your code and check your invariant for each loop, that is what I mean by my comment of that your for-while loops are inside out....
// PRIME NUMBER TEST
#include <stdio.h>
int main () {
bool is_prime = false;
while(is_prime == false) {
int number, n;
printf("Enter #: ");
scanf("%d", &number); // scanf is not recommended, but use it here anyway
is_prime = true; // we assume so for now, also test for numbers < 2
for (n=2; n<=number/2; n++) // this can be optimized, but leave as is anyway
if (number%n==0)
is_prime = false; // sorry it was not prime
}
printf("%d is a prime number.\n", number);
return 0;
}