Combining more than one condition
These allow the testing of more than one condition as part of
selection statements. The symbols are
LOGICAL AND &&
Logical and requires all conditions to evaluate as TRUE (non-zero).
LOGICAL OR ||
Logical or will be executed if any ONE of the conditions is TRUE (non-zero).
LOGICAL NOT !
logical not negates (changes from TRUE to FALSE, vsvs) a condition.
LOGICAL EOR ^
Logical eor will be excuted if either condition is TRUE, but NOT if they are all true.
The following program uses an if statement with logical OR to validate the users input to be in the range 1-10.
#include <stdio.h> main() { int number; int valid = 0; while( valid == 0 ) { printf("Enter a number between 1 and 10 -->"); scanf("%d", &number); if( (number < 1 ) || (number > 10) ){ printf("Number is outside range 1-10. Please re-enter\n"); valid = 0; } else valid = 1; } printf("The number is %d\n", number ); } Sample Program Output Enter a number between 1 and 10 --> 56 Number is outside range 1-10. Please re-enter Enter a number between 1 and 10 --> 6 The number is 6
This program is slightly different from the previous example in that a LOGICAL OR eliminates one of the else clauses.