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