ZetCode

C if & else

last modified February 25, 2021

C if else tutorial shows how to create conditions and branches in C with if/else statements.

C if else

The if statement specifies the conditional execution of a block. If the expression evaluates to true, the block is executed. If the else statement is present and the if statement evaluates to false, the block following else is executed.

There can be multiple if/else statements.

C if else example

The following examples demonstrate conditional execution of blocks with if/else.

if_stm.c
#include <stdio.h>

int main() {
    
    int num = 4;
    
    if (num > 0) {

        printf("The number is positive\n");
    }

    return 0;
}

In the example we have a simple condition; if the num variable is positive, the message "The number is positive" is printed to the console. Otherwise; nothing is printed.

$ ./if_stm 
The number is positive
if_else.c
#include <stdio.h>

int main() {
    
    int num = -4;
    
    if (num > 4){

        printf("The number is positive\n");
    } else {

        printf("The number is negative\n");
    }

    return 0;
}

Now we have added the second branch. The else statement specifies the block that is executed if the if condition fails.

$ ./if_else 
The number is negative

C multiple conditions with else if

We can have multiple branches of conditions with additional else if statements.

if_else_if.c
#include <time.h>
#include <stdio.h>
#include <stdlib.h>

int main() {

    srand(time(NULL));

    int r = rand() % 10 - 5;

    printf("%d\n", r);
    
    if (r > 0){

        printf("The number is positive\n");
    } else if (r == 0) {

        printf("The number is zero\n");
    } else {

        printf("The number is negative\n");
    }
}

In this example, we add additional branch with if else. We generate random values between -5 and 4. With the help of the if & else statement we print a message for all three options.

$ ./if_else_if 
-3
The number is negative
$ ./if_else_if 
0
The number is zero
$ ./if_else_if 
0
The number is zero
$ ./if_else_if 
1
The number is positive
$ ./if_else_if 

We run the example a few times.

In this tutorial, we have covered if else conditions in C.