• Home
  • 4.1 if Statement

4.1 if Statement

View Categories

4.1 if Statement

< 1 min read

Table of Contents

The if statement is the simplest decision-making statement in C++. It evaluates a Boolean expression and executes a block of code only when the expression evaluates to true. If the condition evaluates to false, the controlled statement is skipped.

The if statement is commonly used to perform actions based on user input, comparison results, or the state of a program.

Source Code #

#include <iostream>

int main()
{
    int number = 15;

    if (number > 10)
    {
        std::cout << "Number is greater than 10.\n";
    }

    std::cout << "Program completed.\n";

    return 0;
}

Output #

Number is greater than 10.
Program completed.

Explanation #

  • The if statement evaluates a condition enclosed within parentheses.
  • The condition number > 10 compares the value of number with 10.
  • If the condition evaluates to true, the statements enclosed within the braces are executed.
  • If the condition evaluates to false, the statements inside the if block are skipped.
  • Curly braces ({}) define the block of statements controlled by the if statement.
  • Execution continues with the statement following the if block regardless of whether the condition is true or false.
  • The if statement is used when an action should be performed only if a specific condition is satisfied.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

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