The decision making statements in C++ language are used to perform operations on the basis of condition and when program encounters the situation to choose a particular statement among many statements.
Decision making statements lets you evaluate one or more conditions and then take decision whether to execute a set of statements or not.
Following are the decision control statements available in C++ :-
a) if statement
b) if-else & else-if statement
c) switch-case statements
If statement: The code inside if body executes only when the condition defined by if statement is true. If the condition is false then compiler skips the statement enclosed in if’s body. We can have any number of if statements in a C++ program.
If-else statement: Here, we have two block of statements. If condition results true then if block gets execution otherwise statements in else block executes. else cannot exist without if statement.
Switch-case statement: This is very useful when we have several block of statements, which requires execution based on the output of an expression or condition. switch defines an expression (or condition) and case has a block of statements, based on the result of expression, corresponding case gets execution. A switch can have any number of cases, however there should be only default handler.
if statement consists of a boolean expression followed by one or more statements
Syntax:
if(boolean_expression) {
// statement(s) will execute if the boolean expression is true
}
// Program to print positive number entered by the user
// If user enters negative number, it is skipped
#include <iostream.h>
using namespace std;
int main()
{
int number;
cout << "Enter an integer: ";
cin >> number;
// checks if the number is positive
if ( number > 0)
{
cout << "You entered a positive integer: " << number << endl;
}
cout << "This statement is always executed.";
return 0;
}
Output 1
Enter an integer: 5
You entered a positive number: 5
This statement is always executed.
Output 2
Enter a number: -5
This statement is always executed.