If Statements

Programs become more interesting when different conditions change the output. This section will explain how to use the if, else if and else statements.

#include <stdio.h>

int main()
{
    int x = 5;
    int y = x % 2;
    
    if(x < 0)
    {
        printf("x is negative\n");
    }
    else if(x < 10)
    {
        printf("x is less than 10\n");
    }
    else
    {
        printf("x is 10 or greater\n");
    }

    if(y == 0)
    {
        printf("x is even\n");
    }
    else
    {
        printf("x is odd\n");
    }

    return 0;
}

In the first block of if/else if/else statements, the condition if(x < 0) is checked. If it is true then only the statement in that first block is executed (because of all the other statements being else if/else). Otherwise if the next statement is true, then the statements in that block are executed (in this case with x being positive and less than 10). The else statement is used like a reserve or backup, in that if the previous statements are false then the statement(s) in else are executed.

Then there is the second block of if/else if/else statements, this time to check for conditions with the y variable. Note else if and else statements are not required in a block of if statements.