Unable to validate input in C programming - c

I just started learning C and I'm trying to create a simple "Guess the Number" game.
Player 1 will enter a number that is between 1 and 1000.
Player 2 will be given 10 chances to guess the number entered by Player 1.
If Player 2's guess is beyond the range (1 to 1000), the system should display "Invalid. Out of range." instead of "Too high" or "Too low".
Currently, my program does not validate whether Player 2's guess is within the range (1 to 1000). Instead, it will just display "Too high" even if Player 2's guess is 2000 which is beyond the range (1 to 1000)
Here is my code:
#include <stdio.h>
int main()
{
int number, guess, count = 10;
printf("Enter a number between 1 and 1000:\n");
scanf("%d",&number);
while(number < 1 || number > 1000)
{
printf("Number is out of range.\n");
printf("Enter a number between 1 and 1000:\n");
scanf("%d",&number);
}
while(count >= 1 && count <= 10)
{
printf("Player 2, you have %d guesses remaining.\n", count);
printf("Enter your guess:\n");
scanf("%d", &guess);
count = count - 1;
if (guess >= 1 || guess <= 1000)
{
if (guess > number)
{
printf("Too high.\n");
}
else if (guess < number)
{
printf("Too low.\n");
}
else if (guess == number)
{
printf("Player 2 wins.\n");
}
}
else
{
printf("Invalid. Out of range.");
}
}
if (count == 0)
{
printf("Player 1 wins.");
}
return 0;
}

You need to change
if (guess >= 1 || guess <= 1000)
to
if (guess >= 1 && guess <= 1000)
to avoid values outside 1 and 1000. Otherwise, an input of 2000, will match the condition guess >= 1 and as per the short circuit property, it'll evaluate the if condition as truthy and control will never go to else block.

guess >= 1 || guess <= 1000 should be guess >= 1 && guess <= 1000

Related

Is there a way to make two while loop condition

#include <stdio.h>
#define MAXLIMIT 1000
#define MINLIMIT 1
int main()
{int number = 0, valid=0;
do {
printf("Player 1, enter a number between 1 and 1000:\n");
scanf("%d", &number);
valid = number >= MINLIMIT || number <= MAXLIMIT;
if (!valid) {
printf("That number is out of range.\n");
}
} while (!valid);
int guess = 0, chance = 10;
// Allow player 2 to guess and check
do {
printf("Player 2, you have %d guesses remaining\n", chance);
printf("Enter your guess:\n");
scanf("%d", &guess);
if (guess < number){
printf("Too low.\n");
} else if (guess > number) {
printf("Too high.\n");
} else if (guess == number){
printf("Player 2 wins.\n");
}
else if (guess != number && chance == 0)
printf("Player 1 wins.\n");
} while (guess != number && chance > 0);
}
This is currently my code. I'm stucked at the last where once the user has use up their 10 chances, Player 1 wins. Is there anyway for two while loop condition to happen?
SUGGESTION:
Refactor your code:
Store information about each player (e.g. "name" and "#/guesses") in a struct.
Create an array of players: struct player players[2];
Move your "make a guess" code into a function: void guess(int number, struct player * player).
Whenever you call "guess()", simply check if the #/guesses for that player has been exceeded.
For starters the logical expression
valid = number >= MINLIMIT || number <= MAXLIMIT;
is invalid. You need to use the logical AND operator instead of the logical OR operator
valid = number >= MINLIMIT && number <= MAXLIMIT;
This syntactically incorrect part with do statement
do {
while (guess != number && chance = 0)
printf("Player 1 wins. \n")
}
is redundant.
It is enough to write
if ( guess != number )
{
printf("Player 1 wins. \n");
}
EDIT: After you changed your code in the question then write the if statement within the do-while loop like
if (guess < number){
printf("Too low.\n");
} else if (guess > number) {
printf("Too high.\n");
} else
printf("Player 2 wins.\n");
}
And after the do-while loop write
if ( guess != number )
printf("Player 1 wins.\n");
I won't address the errors in the posted code(s) because the details of this question keeps changing.
Is there anyway for two while loop condition to happen?
Of course we can write suitable conditions to end the do while loops, but it seems to me that it would be more simple to break out when the second player guesses the number and print the winner only after.
int chance = 10;
do {
printf("Player 2, you have %d guesses remaining\n", chance);
printf("Enter your guess:\n");
int guess = 0;
scanf("%d", &guess);
if (guess < number){
printf("%d is too low.\n", guess);
} else if (guess > number) {
printf("%d is too high.\n", guess);
} else { // No need to check equality.
printf("%d is correct\n", guess);
break; // <-- Exit the loop.
}
--chance; // Don't forget to update this.
} while ( chance > 0 );
if ( chance == 0 ) {
printf("Player 1 wins.\n");
} else {
printf("Player 2 wins.\n");
}

Break; issue when correct options are not selected.

I am new and learning to program, I can't get it to "break" properly.
It'supposed to "break" (last if), it the coins are not 0,5,10, or 25. The program is supposed to act like a vending machine, only use dimes, nickels, quarters, and when someone enter "0" it's stops to count the coins.
#include <stdio.h>
#define NICKEL 5
#define DIME 10
#define QUARTER 25
int main(void)
{
int coins;
int sum = 0;
printf("Insert Coins: ");
scanf("%d",&coins);
while (coins != 0){
sum += coins;
if (coins == NICKEL){
printf("Insert coins: ");
scanf("%d",&coins);}
else {continue;}
if (coins == DIME){
printf("Insert Coins: ");
scanf("%d",&coins);}
else {continue;}
if (coins == QUARTER){
printf("Insert Coins: ");
scanf("%d",&coins);}
else {continue;}
if (coins != NICKEL || coins != DIME || coins != QUARTER || coins !=0){
break;
printf("wrong coin");}
printf("the amount you put in: %d",sum);
}
I think you are trying to do this,
#include <stdio.h>
#define NICKEL 5
#define DIME 10
#define QUARTER 25
int main(void)
{
int coins;
int sum = 0;
do {
printf("Insert Coins:");
scanf("%d", &coins);
if(coins == NICKEL || coins == DIME || coins == QUARTER) {
sum += coins;
} else if(coins == 0) {
break;
} else {
printf("Wrong Coin\n");
}
}while(1); // Infinite Loop.
printf("The amount you put in %d\n", sum);
}
The problem is in your in while statement not in break.
0 == 0 true 0 != 0 false
in a control statement (like if-else,for,while) in the condition checking it always evaluate the condition and based on the result, it takes the decision ,
you have written while (coins != 0) when some one enters 0 than it becomes while (0 != 0) after evaluating this while (0) and that causes the loop to terminate

If and if else statements working, but not else

I am making a number guessing game program and am having some trouble with my else statements. In the main block where the number is trying to be guessed, the if and if else statements work, but the else statement does nothing. I am trying to make it where a number outside of the range 0 < number < 100 trigger the else statement.
Furthermore, I am trying to make the game repeat itself if '1' is entered but no matter what is entered, the program crashes.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
/*Number guessing game: The number that needs to be guessed is 52*/
int guess;
int attempt = 6;
int playAgain = 1;
printf("Guess the integer that I am thinking of between 1 and 100\n");
printf("I will tell you if you guess too high or too low\n");
printf("You have 6 attempts\n");
printf("What is your first guess?\n");
if (playAgain == 1)
{
while (attempt > 0)
{
scanf_s("%d", &guess);
if (guess > 0)
{
if (guess < 52)
{
attempt--;
printf("Sorry! Too low! You have %d more tries:\n", attempt);
}
}
else if (guess <100)
{
if (guess > 52)
{
attempt--;
printf("Sorry! Too high! You have %d more tries:\n", attempt);
}
}
else if (guess == 52)
{
printf("Correct! You win!\n");
attempt = 0;
}
else
{
printf("Invalid input: Please enter an integer between 1 and 100:\n");
}
}
printf("Enter '1' to play again or anything else to terminate\n");
scanf_s("%d", playAgain);
attempt = 6;
}
else
{
printf("Thanks for playing!\n");
}
return 0;
}
When you use if else if without brackets, make sure it can't be ambigous.
When you do :
if (true)
if (true)
{
}
else if (false)
{
}
How to know if the else if correspond to the first or the second if ? That's why everyone yell at you to put brackets.
if (true)
{
if (true)
{
}
}
else if (false)
{
}
Corrected and simplified version :
Your program crashes because you forgot the & sign inscanf("%d", &playAgain);.
The logic in your program is wrong, you intermix the test if the number is lower, equal or higher than the input with the test if the input is lower than 0 or higher than 100.
In this corrected version the "invalid input" problem is separated from the actuel "number guessing" problem.
Furthermore the number to be guessed (52) is nor longer hard coded but a variable numbertobeguessed is used instead. Later you should enhance the program so that a random number is generated.
int main(void)
{
/*Number guessing game: The number that needs to be guessed is 52*/
int numbertobeguessed = 52 ;
int guess;
int attempt = 6;
int playAgain = 1;
printf("Guess the integer that I am thinking of between 1 and 100\n");
printf("I will tell you if you guess too high or too low\n");
printf("You have 6 attempts\n");
printf("What is your first guess?\n");
if (playAgain == 1)
{
while (attempt > 0)
{
scanf_s("%d", &guess);
if (guess < 0 || guess > 100)
{
printf("Invalid input: Please enter an integer between 1 and 100:\n");
}
else
{
if (guess < numbertobeguessed)
{
attempt--;
printf("Sorry! Too low! You have %d more tries:\n", attempt);
}
else if (guess > numbertobeguessed)
{
attempt--;
printf("Sorry! Too high! You have %d more tries:\n", attempt);
}
else
{
printf("Correct! You win!\n");
attempt = 0;
}
}
}
printf("Enter '1' to play again or anything else to terminate\n");
scanf_s("%d", &playAgain);
attempt = 6;
}
else
{
printf("Thanks for playing!\n");
}
return 0;
}
the else statement which gives message "Invalid input: Please enter an integer between 1 and 100:\n" is considered as the else part of inner most if-else-if statement. there fore that statement is never executed as the execution enters that if-else-if statement only if 0 < guess < 100. so use {} properly to make the proper combination of if-else statements.
Your nesting is wrong. Put brackets for each if and else to make your code work (quickfix), and use proper indentation to make it readable to humans (if you wish).
Here's an example of how things can go wrong (pseudo code):
a = 4
if (a > 0)
if (a < 3)
a = 2
else
a = 3
What do you expect is the end value of a?
Anyway, your:
if (guess > 0)
if (guess < 52)
should become this:
if (guess > 0 && guess < 52)
and your:
else if (guess <100) // this is where the problems start
if (guess > 52)
should become:
else if (guess < 100 && guess > 52)
and your code will work.
hope this helps
#include <stdio.h>
#include <stdlib.h>
int main()
{
int guess; //variable to hold the number from player
int attempts = 6;
char play = 'y';
do
{
while(attempts)
{
printf("\nEnter you guess: "); scanf("%d", &guess);
attempts--;
if(guess>0 && guess <100 )
{
if(guess>52)
printf("\nThat's not it. Try something lower than that.");
else if(guess<52)
printf("\nThat's not the number. Try something higher than that.");
else if(guess==52)
{ printf("\nYou got it!. You won the game.");
attempts = 0; //we're setting it to zero; we don't want the loop to run anymore
}
}
else
printf("\nNumber enter is not in range!");
}//end of while loop
printf("\nDo you want to play again? (y/n): "); scanf("%c", &play);
}while(play=='y' || play=='Y'); //run till player enter 'Y'
return 0;
}

Why won't my program stop looping?

My assignment is to use two different kinds of loops (For, While, do While). The task is to ask the user to enter a number between 1 and 10 and then the program will count from 0 to the users number. Also, the program must be able to display an error message and ask the user to enter a number again if the user enters a number outside of 1 through 10. The part of the code with the error message and the prompt to enter a number again is working just fine. However, when I enter a number within the range, it either does nothing or counts from 0 to their number an infinite amount of times and won't stop looping the count. Please help!
#include <stdio.h>
int main(void)
{
//Variables
int num;
int zero;
//Explains to the user what the program will do
printf("This program will count from 0 to a number you pick.\n\n");
//Asks the user to input a value
printf("Please enter a number (between 1 and 10): \n");
scanf("%d", &num);
//If the correct range was selected by the user
while ( num >= 1 && num <= 10 )
{
for ( zero = 0; zero <= num; zero++ )
{
printf("%d...", zero);
}
}
//If a value outside of the accepted range is entered
while ( num < 1 || num > 10)
{
printf("I'm sorry, that is incorrect.\n");
printf("Please enter a number (between 1 and 10): \n");
scanf("%d", &num);
}
printf("\n\n\n");
return 0;
}
while ( num >= 1 && num <= 10 )
{
for ( zero = 0; zero <= num; zero++ )
{
printf("%d...", zero);
}
}
will run forever if num is between 1 and 10, since num is not changed inside the loop - once you're in, you're in for good.
If you enter a "bad" value then you'll skip this and go into your second while loop. However once you get out of that while loop by entering a "good" value, all that's left to execute is
printf("\n\n\n");
return 0;
You need to get rid of the first while loop and move the second one above the for loop:
#include <stdio.h>
int main(void)
{
//Variables
int num;
int zero;
//Explains to the user what the program will do
printf("This program will count from 0 to a number you pick.\n\n");
//Asks the user to input a value
printf("Please enter a number (between 1 and 10): \n");
scanf("%d", &num);
//If a value outside of the accepted range is entered
while ( num < 1 || num > 10)
{
printf("I'm sorry, that is incorrect.\n");
printf("Please enter a number (between 1 and 10): \n");
scanf("%d", &num);
}
for ( zero = 0; zero <= num; zero++ )
{
printf("%d...", zero);
}
printf("\n\n\n");
return 0;
}
Change two of your while loops to if guards,
num=1;
while(num>0)
{
//Asks the user to input a value
printf("Please enter a number (between 1 and 10): \n");
scanf("%d", &num);
//If the correct range was selected by the user
if ( num >= 1 && num <= 10 )
{
for ( zero = 0; zero <= num; zero++ )
{
printf("%d...", zero);
}
}
//If a value outside of the accepted range is entered
if ( num < 1 || num > 10)
{
printf("I'm sorry, that is incorrect.\n");
printf("Please enter a number (between 1 and 10): \n");
//scanf("%d", &num);
}
while(0); while(0); while(0); while(0); //gratuitous loops
do ; while(0); for(;0;);
}
Really Simple!
You may use a break inside the while loop:
#include <stdio.h>
int main(void)
{
//Variables
int num;
int zero;
//Explains to the user what the program will do
printf("This program will count from 0 to a number you pick.\n\n");
//Asks the user to input a value
printf("Please enter a number (between 1 and 10): \n");
scanf("%d", &num);
//If the correct range was selected by the user
while ( num >= 1 && num <= 10 )
{
for ( zero = 0; zero <= num; zero++ )
{
printf("%d...", zero);
}
break; // !!! Here !!!
}
//If a value outside of the accepted range is entered
while ( num < 1 || num > 10)
{
printf("I'm sorry, that is incorrect.\n");
printf("Please enter a number (between 1 and 10): \n");
scanf("%d", &num);
}
printf("\n\n\n");
return 0;
}

Unexpected result c while

Hi im trying to understand why if 9 or above is entered for judge it passes but it shouldnt cause the if says >= 4 and <= 8
Thanks
while(!(judge >= 4) && (judge <= 8))
{
printf("How many judges are there ? Enter a number between 4 - 8 \n");
scanf("%d", &judge);
while(!(judge >= 4) && (judge <= 8))
{
printf("You entered %d Enter a number between 4 - 8 \n", judge);
scanf("%d", &judge);
if((judge >= 4) && (judge <= 8))
{
break;
}
}
}
It looks like you are missing a pair of parentheses in
while(!((judge >= 4) && (judge <= 8)))
^ ^
(This mistake appears in two places.)
By the way, you can avoid a lot of the repetition by restructuring your code like so:
printf("How many judges are there ? Enter a number between 4 - 8 \n");
for (;;) {
scanf("%d", &judge);
if (judge >= 4 && judge <= 8) {
break;
}
printf("You entered %d Enter a number between 4 - 8 \n", judge);
}

Resources