if-else

Home / C Programming / if-else

if-else


C programming, the `if-else` statement allows you to execute different blocks of code based on whether a condition is true or false. It provides an alternative execution path when the condition specified in the `if` statement evaluates to false.

The basic syntax of the `if-else` statement in C is as follows:

if (condition) {

    // code to execute if condition is true

} else {

    // code to execute if condition is false

}

The `condition` is an expression that evaluates to either true or false. If the condition is true, the code block within the first set of curly braces will be executed. If the condition is false, the code block within the second set of curly braces (the `else` block) will be executed.

Here's an example to illustrate the usage of `if-else` statement:

#include <stdio.h>

int main() {

    int num = 10;

    if (num % 2 == 0) {

        printf("The number is even.\n");

    } else {

        printf("The number is odd.\n");

    }

    printf("Program complete.\n");

    return 0;

}

In this example, the program checks if `num` is divisible by 2 (i.e., the remainder of `num` divided by 2 is 0). If the condition is true, it prints "The number is even." Otherwise, it prints "The number is odd."

You can also use multiple `else if` clauses to test additional conditions.

Here's an example:

#include <stdio.h>

int main() {

    int score = 85;

    if (score >= 90) {

        printf("Excellent!\n");

    } else if (score >= 80) {

        printf("Good job!\n");

    } else if (score >= 70) {

        printf("Keep it up!\n");

    } else {

        printf("You can do better.\n");

    }

printf("Program complete.\n");

    return 0;

}