Need help looping magic-number program - c

I have written the below code and need help understanding why it's not working the way it should. It compiles, however, it isn't running the if-else in my loops. For example, if I were to take out the while loop in my code everything would work fine, however, I want to know how many tries it takes for someone to guess the "magic number" or random number in this case.
#include <stdio.h>
int main()
{
int magicnum = 1234;
int userguess;
int totalguess = 0;
printf("Try to guess a number between 1 and 10000!: ");
scanf("%d", &userguess);
while(totalguess <= 7 && magicnum != userguess);{
if(magicnum == userguess){
printf("Congratulations, You Win!!\n");
if(totalguess = 1){
printf("Wow you did it on your first try!!\n");
}
else(totalguess >= 2); {
printf("Nice one!! It only took you %d tries!\n", totalguess);
}
}
else if(magicnum > userguess){
printf("Too Low try again!!\n");
}
else{
printf("Too High try again!!\n");
}
totalguess++;
}
return 0;
}
I am looking for an output of either someone answering the correct number which is "1234" if they score too high they should see the response of "Too High try again!!", and if they score too low they should see the response of "Too low try again!!. Also, it is supposed to show how many attempts it took them, and if they got it on the first try or not. The max number of attempts a person should be able to do this should be 7.

Problem #1 problem lies in the line
while(totalguess <= 7 && magicnum != userguess);{
Specifically at the semicolon. The above evaluates to the following
// Sit on this line until a condition is met
while(totalguess <= 7 && magicnum != userguess);
// Some block of code which is unrelated to the while loop
{
...
}
The answer is to remove the extraneous semicolon at the end of the while loop:
while(totalguess <= 7 && magicnum != userguess) {
// No semicolon ^
Problem #2 is in the line
if (totalguess = 1){
Where you are actually assigning totalguess to 1. Fix this by changing = (assignment) to == (comparison).
Problem #3 and #4 are in the line
else(totalguess >= 2); {
Not sure how this is even compiling, but you should have an else if rather than an else. And as with the while loop, you have another extraneous semicolon. Remove it.
Lastly, you are only asking for user input once, so the program will loop 7 times without asking for input. Put your scanf inside the main while loop

According to Levi's findings, a solution:
const int magic_num = 1234;
const uint max_num_guess = 7;
uint num_guess = 1 + max_num_guess;
int user_guess;
printf( "Try to guess a number between 1 and 10000!\n" );
for( uint idx = 0; idx < max_num_guess; ++idx )
{
scanf( "%d", &user_guess );
if( magic_num == user_guess ) { num_guess = 1 + idx; idx = max_num_guess; }
else
{
if( magic_num < user_guess ) { printf( "Too High try again!!\n" ); }
else { printf( "Too Low try again!!\n" ); }
}
}
if( num_guess <= max_num_guess )
{
printf( "Congratulations, You Win!!\n" );
if( 1 == num_guess ) { printf( "Wow did it on your first try!!\n" ); }
else { printf( "Nice one!! %d tries!\n", num_guess ); }
}
To #3 it is valid. Consider:
if(false){}
else(printf("Branch!\n"));
{ printf("Done.\n"); }

Related

How do I end a While Loop with 3 conditions

while( num != 101 && num != 102 && num != 103 ){
printf( "Enter number: " );
scanf( "%d", &num );
}
I'm making a C program using Loops that accepts numbers from the user until the user inputs the numbers 101, 102, and 103. The above three conditions in while loop is working as an OR operator. If one of the three conditions is met, the while loop stops. What I need is that while loop should be stopped when the three conditions are met. I already tried to use || instead of && but the program just keeps looping. Thank you in advance!!
while( num == 101 && num == 102 && num == 103 ){
printf( "Enter number: " );
scanf( "%d", &num );
}
This is an infintive loop, because that is what you want. It "should be stopped when the three conditions are met".
Num could only justify one condidition. Num couln't be all three values (101 AND 102 AND 103) at the same time. Except you have a quantum computer.
The actual purpose of your program is unclear.
It appears that all three numbers (101, 102 and 103) must be entered by the user before the program will continue.
Typically you would use three separate variables. Are you attempting to simulate a combination lock? If that is the case then the following code seems to work. (Interestingly it is, indeed, a combination lock since the numbers can be entered in any order.)
/* enter the numbers 101, 102 and 103 to exit the while loop
*/
#include <stdio.h>
#include <stdbool.h>
int main (void)
{
printf("\n");
bool flag101 = false;
bool flag102 = false;
bool flag103 = false;
do {
printf("enter number: ");
int num;
scanf("%d", &num);
if (num == 101) {
printf("101 entered\n");
flag101 = true;
}
if (num == 102) {
printf("102 entered\n");
flag102 = true;
}
if (num == 103) {
printf("103 entered\n");
flag103 = true;
}
} while (! (flag101 && flag102 && flag103));
printf("\n");
printf("all three numbers have been entered\n");
return 0;
}

How to access return value of scanf when used in a while loop?

The intention of this code is to wait for the user to input two integers and then to do something with them. However I don't want my program to stop when the 2 values are read, instead, I want it to follow the directions that are inside the while loop and when it's done, ask the user for some more integers.
int main (void){
while(scanf("%d %d", &order, &system) != EOF){
if(order < 0 || system < 2 || system > 36){
printf("Invalid input!\n");
return 1;
}
// Do something with the numbers
}
return 0;
}
The problem I am facing here is that I can't figure out how to store the return value of scanf, so that I could check if it did indeed obtain two integers. Normally I would just write if( scanf ( ... ) != 2 ) { return 1; }.
Thanks!
while (1) {
int rv = scanf("%d %d", &order, &system);
if (rv == EOF) {
...
}
...
}

How to make an array accept only numbers in c programming?

So my task is to make an array that accepts 10 characters. If the characters entered by the user are greater than 10, then an error is dispayed. If the 10 characters entered contain a letter, it displays another error.
Therefore, the array can only have 10 numbers and nothing else, if the numbers entered are less or more than 10, error is displayed as well as if there are letters in the array.
My code accepts both numbers and letters, as i cannot figure out how to display error when letters are entered.
void getTenDigitPhone(char telNum[])
{
int i;
int z = 1;
do
{
scanf("%s", telNum);
if (strlen(telNum) != 10)
{
printf("Enter a 10-digit phone number: ");
z = 1;
}
else if (strlen(telNum) == 10)
{
return telNum;
}
} while (z == 1);
}
You just need to check that telNum contains only digits:
for (int i = 0; i < 10; i++)
if (!isdigit(telNum[i])) {
// handle error because a non-digit was found.
}
I'm not going to do your homework for you but this should give you the idea.
You can use the function isdigit(x).
This returns true (non-zero) if x is a digit and returns false (zero) if not.
You have to check digit by digit.
I'm going to give an answer because you have posted your current code as your effort. As other answers you should use isdigit(x) function.
...
else if (strlen(telNum) == 10)
{
int i;
char err = 0;
for (i = 0; i < 10; i++) {
if (!isdigit(telNum[i])) {
// Your error here
printf("Non-digit character found");
err = 1;
break;
}
}
if (err == 0) {
return telNum;
}
}
...

How do I store (scanf) a randomly generated number? ( Code inside)

This is the code i used to generate the number:
printf("%d\n", rand()%10);
I am creating a card game HiLo. I want to know how to store the number generated from that and then make the user guess wether the next number is going to be higher or lower than the previous. After that, another number is generated and not stored just yet. I want to compare the new number with the old number too see if the user is correct (alot points) and then store the new number.
You just want to use a variable. All variables may include alphabetic characters, as well as numeric characters, however the first character must be alphabetic. The concept of creating a variable is that you are creating an area of temporary storage for the successful operation of your program. Any areas of code using a particular variable are considered to be dependent on it, and variables work in "scopes". Scopes are started using the { character and are ended using the } character. Any variables declared between these characters are usable only within those characters, and not outside of them, as they do not exist except within those characters.
I have created an example of the program I believe you are trying to write in order to demonstrate the software programming practices involved in such a task.
The example is shown below:
#include <stdio.h>
#include <string.h>
#define LENGTH_OF_BUFFER 100
int main( int argc, char **argv )
{
int prevRandomNumber = rand() % 10;
int continuePlaying = 1;
while( continuePlaying == 1 )
{
int randomNumber = rand() % 10;
int userSelection = 0;
char lineBuffer[LENGTH_OF_BUFFER];
printf( "Previous random number %d\n", prevRandomNumber );
while( userSelection == 0 )
{
printf( "higher or lower?" );
gets( lineBuffer );
if ( strcmp( "higher", lineBuffer ) == 0 )
{
userSelection = 1;
printf( "You selected higher!\n" );
}
else if ( strcmp( "lower", lineBuffer ) == 0 )
{
userSelection = -1;
printf( "You selected lower!\n" );
}
else
{
printf( "Sorry, I didn't understand you, please check your input and try again!\n" );
}
}
if ( userSelection == 1 )
{
if ( randomNumber > prevRandomNumber )
{
printf( "Correct, you really are a marvel!\n" );
}
else
{
printf( "Incorrect, I pity you!\n" );
}
}
else if ( userSelection == -1 )
{
if ( randomNumber < prevRandomNumber )
{
printf( "Correct, you really are a marvel!\n" );
}
else
{
printf( "Incorrect, I pity you!\n" );
}
}
printf( "Number was %d\n", randomNumber );
printf( "Care to play again?\n" );
gets( lineBuffer );
prevRandomNumber = randomNumber;
if ( strcmp( "yes", lineBuffer ) != 0 )
{
continuePlaying = 0;
}
}
}
I hope this helps...
int number = rand()%10;
int nextNumber;
char choice;
while(choice != 'Q' && choice != 'q')
{
printf("Current Number is : %d",number);
printf("\nYou want to guess the next number : ");
printf("\nPress L if number will be greater than current number ");
printf("\nPress S if number will be smaller than current number ");
printf("\nPress Q if you want to quit playing : ");
Printf("\n\nEnter your choice : ")
scanf("%c",&choice);
nextNumber = rand()%10;
if(choice == 'L' || choice == 'l')
{
if(nextNumber > number)
{
printf("\nYour Guess is Right...");
}
else
{
printf("\nYour Guess is wrong...");
}
}
else if(choice == 'L' || choice == 'l')
{
if(nextNumber < number)
{
printf("\nYour Guess is Right...");
}
else
{
printf("\nYour Guess is wrong...");
}
}
else
{
printf("\nYour choice is invalid. Try Again...");
}
number = nextNumber;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main(){
char* bet, cmd;
long random_number, new_random_number;
while (1)
{
srand(time(NULL));
random_number = rand();
printf("%d\n", random_number);
printf("bet if the next number is bigger (+) or lower (-): ");
scanf("%s",bet);
srand(time(NULL));
new_random_number = rand();
printf("%d\n", new_random_number);
/* TODO - you might want to put that into a function some how */
if ( bet[0] == '+')
{
if ( new_random_number >= random_number ) /* user is correct */
{
printf("yeah! you are right\n");
printf("\nlet's play again!!\n");
continue;
}
else
{
printf("trololol :P That was wrong\n");
printf("\nlet's play again!!\n");
continue;
}
}
if ( bet[0] == '-')
{
if ( new_random_number < random_number ) /* user is correct */
{
printf("yeah! you are right\n");
printf("\nlet's play again!!\n");
continue;
}
else
{
printf("trololol :P That was wrong\n");
printf("\nlet's play again!!\n");
continue;
}
}
}
}
/* vim: set et sw=4 ts=4: */

Comparison with multiple == (Fruit machine task)

I'm struggling with my "IF" comparison between 3 variables.
The program is supposed to comapare wheels 1, 2 and 3, and reward the player with £5 if all 3 are the same, and £2 if 2 of the 3 are the same.
However sometimes it doesn't work ( gives me £5 even though none are the same)
Please could someone take a look and tell me how to fix it?
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
const char *symbol[4] = {" bell ", " orange ", " cherry ", "horseshoe"};
int main ()
{
srand(time(NULL));
int playagain =1;
int wheel_1,wheel_2,wheel_3;
int i;
int money=10;
int j = (rand()%30)+10;
int start=1;
int k;
printf("you have £%d. Press any key to gamble £1\n", money);
getchar();
while(playagain == 1)
{
for (i=0; i<j; i++)
{
printf("\033[2J\033[0;0f");
printf("\033[%d;%df", 0, 0);
wheel_1 = (rand()%4);
wheel_2 = (rand()%4);
wheel_3 = (rand()%4);
printf("%s ", symbol[wheel_1]);
printf("%s ", symbol[wheel_2]);
printf("%s \n", symbol[wheel_3]);
for (k=0; k<10000000; k++)
{
}
}
printf("%d, %d, %d\n", wheel_1, wheel_2, wheel_3);
if (wheel_1 == wheel_2 == wheel_3)
{
printf("Congrats! You win £5\n");
money = (money+5)-1;
}
else if (wheel_1 == wheel_2 ||
wheel_1 == wheel_3 ||
wheel_2 == wheel_3 )
{
printf("Congrats! You win £2\n");
money = (money+2)-1;
}
else
{
printf("Unlucky, you have lost your £1\n");
money--;
}
printf ("You now have £%d\n", money);
char *replay;
printf ("would you like to play again?");
scanf ("%s", &replay);
if (strcmp(&replay, "yes") == 0)
{
playagain = 1;
}
else
{
playagain = 0;
}
}
}
The way you are using if to compare wheels is wrong
if (wheel_1 == wheel_2 == wheel_3)// Wrong
You should be using
if ((wheel_1 == wheel_2 ) && (wheel_2 == wheel_3))
Almost everything in C returns a value. The expression wheel_2 == wheel_3 also returns a value. The value returned by this expression compares equal to zero if the condition is false else it is non zero(will be 1).
When you do wheel_2 == wheel_3 and suppose the expression is true then it will return 1. This is again compared with wheel_1 like wheel_1 == 1.
As above, it looks like you need:
if((wheel_1 == wheel_2) && (wheel_2 == wheel_3))
Let us know if it works like this :-).
Yes, in here you would have to keep the comparison values differently,
beacuse that x=y=z would return a value and that would be true even though they are not.
Hence you keep them as in associate property if(x==y) && if(y==z) so you naturally get x=z.

Resources