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
ifstatement evaluates the conditionnumber % 2 == 0. - The modulus operator (
%) calculates the remainder whennumberis divided by2. - If the remainder is
0, the condition evaluates totrue, and theifblock is executed. - If the condition evaluates to
false, theelseblock is executed. - The
elsestatement 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-elsestatement. - Curly braces (
{}) define the statements belonging to each branch. return 0;terminates the program successfully.