Solution for Exercise 8-12
ex0812
#include <stdio.h>
#define SECRET 17
int main()
{
int guess;
printf("Can you guess the secret number: ");
scanf("%d",&guess);
if(guess==SECRET)
{
puts("You guessed it!");
return(0);
}
else
{
puts("Wrong!");
return(1);
}
}
Notes
* The "best solution" I referred to in the book is to change only Line 16. The change is from if(guess!=SECRET) to else.
* Both this solution and the solution for Exercise 8-6 are effectively the same, which may make you wonder why bother with the else statement at all. The reason is that by grouping if-else you create a single structure, which is designed to handle only one condition in an absolute way. While some code may contain two separate if statements back-to-back, that setup represents two different evaluations, not a single one. That distinction may be too subtle for you to appreciate at this point in your programming experience, but it's the reason why you use if-else instead of two if statements.
Copyright © 1997-2025 by QPBC.
All rights reserved
