Table of Contents

We can use these operators to define the conditions under which conditional and iterative constructs are executed. Logical operators are not(!), and(&&) and or(||) and relational operators are greater than(>), less than(<), greater than or equal to(>=), less than or equal to(<=), equal to(==) and not equal to(!=).

Logical AND example

Martha wants a program to check if her students are between a certain height - students who are too short or too tall cannot be placed on the carnival ride. She comes up with the following code:

#include <stdio.h>

int main(){
    float height;
    printf("Please enter your height: ");
    scanf("%f",&height);

    if (height<180 && height>120){
        printf("You can enter the ride!\n");
    }else{
        printf("Please do not enter the ride\n");
    }

    return 0;
}
too-short-too-tall.c
Copy

The condition height<180 && height>120 only evaluates to true when both of the comparisons evaluate to true, that is, when the height of the student is both greater than 120(height>120) and less than 180(height<180).

Logical OR example

Consider a scenario where we want to check which of a list of numbers is a multiple of 2 OR 3:

#include <stdio.h>

int main(void){
    for (int number=0;number<=20;number++){
        if (!(number%2==0 || number%3==0)){
            printf("\033[0;41m %d - NOT DIVISIBLE by 2 or 3\n",number);
        }else{
            printf("\033[0;32m %d - DIVISIBLE by 2 or 3\n",number);
        }
    }

    return 0;
}
divisible-by-2-or-3.c
Copy

Recall that %(the modulo operator) is used to get the remainder of a division and a number is divisible by another if the remainder is 0.

Coloring text using color codes in the terminal

Read more about coloring the text in the terminal from this C for dummies article.

Support us via BuyMeACoffee