• Home
  • 2.2 if-else Statement

2.2 if-else Statement

View Categories

2.2 if-else Statement

< 1 min read

Table of Contents

The if-else statement selects between two blocks of code. The if block executes when the condition is non-zero; otherwise, the else block executes.

#include <stdio.h>

int main()
{
    int number = -5;

    if (number > 0)
    {
        printf("The number is positive.\n");
    }
    else
    {
        printf("The number is not positive.\n");
    }

    return 0;
}

Example Output #

The number is not positive.

Explanation #

The condition is evaluated first:

if (number > 0)

Since number is -5, the condition evaluates to 0. Therefore, the if block is skipped and the else block executes:

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

Only one of the two blocks is executed for a single evaluation of the if-else statement.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *