The key is Logical OR operator (||) in logical operator.
A logical operator would :
- treats its operands as boolean values
- treats a non-zero value operand as
true
- treats a zero value operand as
false
- operates the boolean algebra on its operands
- returns the boolean algebra result
- returns
1 for true boolean result
- returns
0 for false boolean result
The Logical OR operator (||) :
lhs || rhs
- Here,
lhs and rhs are the 2 operands of OR(||) operator
- The OR operator returns
1 if any of the following conditions is true:
- only
lhs is true
- only
rhs is true
- both
lhs and rhs are true
- In other words, the boolean algebra OR result is true if either
lhs or rhs is true.
In your example, there are 2 conditions :
- height is less than 1
- height is larger than 8
if either of them is true, then the result is true (the loop will continue), so the expression in this example would be :
int height; /* move height outside the loop so it can be used in do-while condition */
do {
height = get_int();
if (height < 1)
printf("invalid\n");
else if (height > 8)
printf("invalid\n");
} while(height < 1 || height > 8);
printf("valid\n");
Furthermore, since we have already done the logical condition in the loop, we can just add a flag variable instead:
int flag; /* record the boolean result */
do {
int height = get_int();
if (height < 1) {
printf("invalid\n");
flag = 1;
} else if (height > 8) {
printf("invalid\n");
flag = 1;
} else {
flag = 0; /* !(height < 1 || height > 8) */
}
} while(flag);
printf("valid\n");
;at the end of all your statements.