Skip to main content

Section 9.7 Combining Multiple Logic Statements

The way to write the logical AND in C is with two ampersand signs: &&

Compile and run the code below in your own C environment.

#include <stdio.h>
int main(void) {
    int sunny = 8; /* on a scale of 1 to 10 */
    int vacation = 1;
    
    if ( (sunny>5) && vacation) {
        printf("It\'s super sunny and I am on vacation! What could be better?\n");
    } else {
        printf("Ugh!\n");
    }
    
    return(0);
}
The way to write the logical OR in C is with two vertical bars: ||

Compile and run the code below in your own C environment.

#include <stdio.h>
int main(void) {
    int month = 8; /* month of the year*/
    
    if ( (month<6) || (month>9)) {
        printf("It\'s not summer unfortunately.\n");
    } else {
        printf("Look\'s like summer to me!\n");
    }
    
    return(0);
}
The way to negate a condition in C is to put an exclamation mark in front of it: !(...)

Compile and run the code below in your own C environment.

#include <stdio.h>
int main(void) {
    int month = 8; /* month of the year*/
    
    if ( !((month>=6) && (month<=9)) ) {
        printf("It's not summer unfortunately.\n");
    } else {
        printf("Look's like summer to me!\n");
    }
    
    return(0);
}

Investigate 9.4.

Zero is the value which C interprets as false. How could you use a logical operator so that C would interpret anything except zero as false, such as in an if statement?