Reputation: 11
Guessing game that I got from a youtube video and wanted to ask a few questions that I didn't get. One what is the point of the else outofGuesses=1 part? Secondly when do you use one equal sign and when to use 2. Last but not least was there an easier way to do this like using a for statement?
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int secretNumber= 5;
int guess;
int guessCount=0;
int guessLimit=3;
int outofGuesses=0;
while(guess !=secretNumber && outofGuesses ==0)
{
if(guessCount< guessLimit)
{
printf("Enter a number between 1 and 10:");
scanf("%d", &guess);
guessCount++;
}
else
{
outofGuesses =1;
}
}
if(outofGuesses==1)
{
printf("You lost!");
}
else
{
printf("You win!");
return 0;
}
}
Upvotes: 1
Views: 133
Reputation: 941
As pointed out by @am121 in the other answer, use =
for assigning a value to a variable and ==
while checking if two values are equal
First off, the program has a bug. The variable guess
is not initialized and has undefined behavior. For example, if the guess
is same as secretNumber
, the person wins the game without playing. For this program, it should be assigned any value NOT equal to secret number
Same thing using for loop:
#include <stdio.h>
int main(void)
{
int secretNumber= 5;
int guess = 0; //Some value not equal to secretNumber
int guessLimit=3;
for(int guessCount=1; guess!=secretNumber && guessCount<=guessLimit; guessCount++){
printf("Enter a number between 1 and 10:");
scanf("%d", &guess);
}
if(guess == secretNumber)
{
printf("You win!");
}
else
{
printf("You lost!");
}
}
Upvotes: 1
Reputation: 31
All of that is extremely basic, and if you have to ask, then you should look for a better teacher/tutorial
= is used to assign a value to a variable.
== is used to compare two values.
outofguesses=1 assigns the value 1 to that variable when you run out of guesses; it causes the comparison inside the 'while' to fail and the program flow to skip it to the finishing portion.
Upvotes: 1