• Home
  • 4.2 if-else Statement

4.2 if-else Statement

View Categories

4.2 if-else Statement

< 1 min read

Table of Contents

The if-else statement provides two alternative execution paths. The if block is executed when its condition evaluates to true; otherwise, the else block is executed.

This allows a program to perform one action when a condition is satisfied and a different action when it is not.

Source Code #

#include <iostream>

int main()
{
    int number = 7;

    if (number % 2 == 0)
    {
        std::cout << "Number is even.\n";
    }
    else
    {
        std::cout << "Number is odd.\n";
    }

    return 0;
}

Output #

Number is odd.

Explanation #

  • The if statement evaluates the condition number % 2 == 0.
  • The modulus operator (%) calculates the remainder when number is divided by 2.
  • If the remainder is 0, the condition evaluates to true, and the if block is executed.
  • If the condition evaluates to false, the else block is executed.
  • The else statement does not have a condition of its own; it represents the alternative execution path.
  • Only one of the two blocks is executed for a given evaluation of the if-else statement.
  • Curly braces ({}) define the statements belonging to each branch.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

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