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;
}
Related
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int num, rnum, times = 1;
srand(4383);
rnum=rand() % 300 + 1;
while(times <=8)
{
printf("Guess the numper random number between 1-300: ");
scanf("%d", &num);
if (num<rnum)
{
printf("The random number is biger\n");
}
if (num>rnum)
{
printf("The magic number is smaller\n");
}
if (num == rnum)
{
printf("RIGHT!");
break;
}
times++;
}
printf("FAILURE!");
return 0;
}
The point of the task is to make a program for a user to type and try to guess a numper from 1–300 with 8 attempts. If you find the number it shows RIGHT! and if not it guides you by telling that the number is biger/smaller. If you fail in your 8 atemts then it shows failure. The problem is that it shows failure when you fail to guess in your 8 atempts but when you find the number it prints both RIGHT & FAILURE. What should i correct for the program to print failure only when you cant’t find the number within your 8 tries?
My 2 cents, path of least resistance is to simply return rather than break when the user guesses correctly:
if (num == rnum)
{
printf("RIGHT!");
return 0; // program exits here, no FAILURE print
}
You should also seed the rand function with a changing number, like time. With a constant, you'll find your number to guess is the same every time.
srand(time(NULL)); // randomize seed
You should check if they exceeding the 8 try limit before executing the print statement:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int num, rnum, times = 1;
srand(4383);
rnum=rand() % 300 + 1;
while(times <=8)
{
printf("Guess the numper random number between 1-300: ");
scanf("%d", &num);
if (num<rnum)
{
printf("The random number is biger\n");
}
if (num>rnum)
{
printf("The magic number is smaller\n");
}
if (num == rnum)
{
printf("RIGHT!");
break;
}
times++;
}
if (times > 8)
{
printf("FAILURE!");
}
return 0;
}
I think you should write return 0; instead of break; after printing RIGHT. because if you guess the rnum it will print RIGHT and breaks out and after that it will print FAILURE too but if you write return 0; it will end the program.
When you break; out after having printed RIGHT! you end up where you print FAILURE! so you need to check this somehow.
Here's my take on it:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int num = 0, rnum;
// This game will get boring with a static seed.
// I'm assuming you use this seed for testing only.
srand(4383);
rnum = rand() % 300 + 1;
for(int times = 0; times < 8; ++times) { // simpler loop
printf("Guess the random number between 1-300: ");
// if the user fails to enter a number - make it print FAILURE
if(scanf("%d", &num) != 1) break;
if(num < rnum)
puts("The random number is bigger");
else if(num > rnum) // added "else"
puts("The magic number is smaller");
else
break; // neither less nor greater than rnum so it must be correct
}
if(num == rnum) // added check
printf("RIGHT!\n");
else
printf("FAILURE!\n");
}
Number guessing game which a user guess a number from 0-20 and i want it to display how many tries are left for the user for example the maximum tries is 5 and if the user got it wrong on the first try it will display something like "tries left : 4", how do i implement that in my code?
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main()
{
time_t t;
srand((unsigned)time(&t));
int randomNumber = rand() % 21;
int num;
int guess = 0;
printf("\nThis is a guessing game.");
printf("\nGuess 5 times only\n");
printf("\nEnter your guess:");
scanf("%d",&num);
while (num != randomNumber && guess < 5){ //checks if num is equal or not to randomnumber and count is less than 5 or limit 5
if(num > randomNumber){ // checks if num is greater than randomNumber
printf("Too high! try again:");
scanf("%d",&num);
guess++;
}
if(num < randomNumber){ //checks if num is less than randomNumber
printf("Too low! try again:");
scanf("%d",&num);
guess++;
}
if(num == randomNumber){ //checks if num is equal to randomNumber
printf("You got it right!\n");
return 0;
}
if(guess == 5) //checks if tries is 5 then exits program.
{
printf("your out guess of guesses!\n");
return 0;
}
}
return 0;
}
You can add this inside your while loop (at the end)
// For total no of guesses = 5, if that is n then n - 1 - guess
printf("tries left %d\n", 4 - guess);
If you’re trying to print a value in a loop something along the lines of printf(“You have %d guesses left\n”,5-guess); might work
You already have an answer, but I would advise you using symbolic constants #define GUESS_NUM 4 instead of actual numbers in your statements and your program in general, in programs like this it makes no difference, but you can get confused very easily in larger projects.
Also, your loop should end when guess reaches 4 because you already have one guess before the loop. You could write something like this:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define GUESS_NUM 4
int main()
{
time_t t;
srand((unsigned)time(&t));
int randomNumber = rand() % 21;
int num;
int guess = 0;
printf("\nThis is a guessing game.");
printf("\nGuess 5 times only\n");
printf("\nEnter your guess:");
scanf("%d",&num);
while (num != randomNumber && guess < GUESS_NUM){ //checks if num is equal or not to randomnumber and count is less than 5 or limit 5
if(num > randomNumber){ // checks if num is greater than randomNumber
printf("tries left : %d\n", GUESS_NUM-guess);
printf("Too high! try again:");
scanf("%d",&num);
guess++;
}
if(num < randomNumber){ //checks if num is less than randomNumber
printf("tries left : %d\n", GUESS_NUM-guess);
printf("Too low! try again:");
scanf("%d",&num);
guess++;
}
if(num == randomNumber){ //checks if num is equal to randomNumber
printf("You got it right!\n");
return 0;
}
if(guess == GUESS_NUM) //checks if tries is 5 then exits program.
{
printf("your out guess of guesses!\n");
return 0;
}
}
return 0;
}
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.
For the below code I created a RNG and ask the user to input a number from one to 20 until they guess the correct number. When they guess the correct number the printf prints the correct text so I know guesses[i] == randomNumber
I would think that the for loop would terminate since now guesses[i] != randomNumber no longer holds a true value. The loop is not terminating and continues to ask the user to guess.
Am I missing something here?
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
#include <stdlib.h>
int main(void) {
time_t t;
srand(time(&t));
int randomNumber = (rand() % 19) + 1;
int guesses[30] = {0};
int i;
for (i = 0; guesses[i] != randomNumber; i++)
{
printf("Hello master, I will grant you 3 wishes if you can guess what number I have selected between 1 and 20: ");
scanf("%d", &guesses[i]);
if (guesses[i] == randomNumber) {
printf("It took you %d guesses to guess correct but I lied I cannot grant you any wishes, have a nice day. \n\n", i + 1);
}
else if(guesses[i] < randomNumber) {
printf("You guessed too low, try a higher number. \n\n");
}
else if(guesses[i] > randomNumber) {
printf("You guessed too high, try a lower number. \n\n");
}
}
return 0;
}
When the user inputs its guess, i increases by the loop increment instruction, and now your condition is applied to guess[i] which is actually the next i not the input user.
Welcome to SO..
I believe that testing the condition (guesses[i] != randomNumber) happens before advancing i (i++), so you are actually testing against i that was already advanced by 1
You can either try to use ++i instead of i++
OR
You can use a while loop instead of a for loop:
i = 0;
while (guesses[i] != randomNumber && i < 30) {
i++;
printf("Hello master, I will grant you 3 wishes if you can guess what number I have selected between 1 and 20: ");
scanf("%d", &guesses[i]);
if (guesses[i] == randomNumber) {
printf("It took you %d guesses to guess correct but I lied I cannot grant you any wishes, have a nice day. \n\n", i + 1);
}
else if(guesses[i] < randomNumber) {
printf("You guessed too low, try a higher number. \n\n");
}
else if(guesses[i] > randomNumber) {
printf("You guessed too high, try a lower number. \n\n");
}
}
Note how I also added a test for i < 30 to not get out of the array index bounds
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;
}