I have a few questions regarding this code. I have tried all these scenarios, and not sure how or why the code is behaving in certain ways.
Q1. Lines 5-6. Given both the ‘guess’ and ‘tries’ variables are of the same type (if type has an impact to begin with), why are we assigning a ‘0’ value to tries variable but nothing to guess variable?
Q2a. What happens if we assign a ‘0’ value to guess variable? (no effect in result, but why)?
Q2b. What happens if we assign any other number to guess variable, except for 8?
Q2c. What happens if we assign an ‘8’ value to guess variable?
Q3. When we assign a ‘0’ to tries variable, does that mean it’s already occupying the 0th term? And can now take only 1, 2, 3 and 4th attempts before the code stops working? If so, then why do we get 6 attempts in total? Even if we are counting in the 0th attempt, should it still not ignore the 6th attempt (tries =5) given the code states ‘tries < 5’?
Q4. When we assign tries = 4 in line 6, we get two attempts, tries = 5 leads to one attempt… However, I can still have an attempt even when tries = 6 or any higher number. Why?
Q5. If we want to add a message such as “You Failed” after all the attempts are exhausted, how do we do that?
#include <stdio.h>
int main() {
int guess;
int tries = 0;
printf(“I’m thinking of a number in the range 1-10.\n”);
printf(“Try to guess it: “);
scanf(”%d”, &guess);
while (guess != 8 && tries < 5) {
printf(“Wrong guess, try again: “);
scanf(”%d”, &guess);
tries++;
}
if (guess == 8) {
printf(“You got it!\n”);
}
}
2 posts - 2 participants