CodeMIRAI
0 XP

if and else

2 min read 4 runnable examples Quiz included
C
#include <stdio.h>

int main() {
    int score;
    scanf("%d", &score);

    if (score >= 90) {
        printf("Grade A\n");
    } else if (score >= 75) {
        printf("Grade B\n");
    } else if (score >= 50) {
        printf("Grade C\n");
    } else {
        printf("Try again\n");
    }
    return 0;
}

The condition goes in brackets; the block in braces. C checks conditions top to bottom and runs the first one that's true.

True and false in C

C has no separate boolean type in its oldest form: 0 is false and any other number is true. Comparisons produce 1 (true) or 0 (false):

C
#include <stdio.h>

int main() {
    printf("%d\n", 5 > 3);
    printf("%d\n", 5 == 3);
    if (42) {
        printf("Any non-zero value counts as true\n");
    }
    return 0;
}

Operators

RelationalMeaningLogicalMeaning
==equal&&and
!=not equal||or
< > <= >=comparisons!not
C
#include <stdio.h>

int main() {
    int age = 20;
    int has_ticket = 1;

    if (age >= 18 && has_ticket) {
        printf("Enjoy the show\n");
    }
    if (!has_ticket || age < 18) {
        printf("Entry refused\n");
    }
    return 0;
}

The ternary operator

C
#include <stdio.h>

int main() {
    int n = 7;
    printf("%d is %s\n", n, n % 2 == 0 ? "even" : "odd");
    int bigger = (n > 10) ? n : 10;
    printf("bigger = %d\n", bigger);
    return 0;
}
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.