if-else in C++
The if-else decision-making statement allows us to make a decision based on the evaluation of a given condition. If the given condition evaluates to true then the code inside the ‘if’ block is executed and in case the condition is false, the code inside the ‘else’ block is executed.
Syntax of if-else in C++
if (condition) {
// Code to be executed if the condition is true
}
else {
// Code to be executed if the condition is false
}
Flowchart of if-else in C++
Example of if-else in C
The below example demonstrates the use of an if-else statement to find if the given number is positive or nonpositive.
C++
// C++ program to find if the given number is positive or // non positive #include <iostream> using namespace std; int main() { int num = 5; // Using if-else to determine if the number is positive // or non positive if (num > 0) { cout << "number is positive." << endl; } else { cout << "number is non-positive." << endl; } return 0; } |
number is positive.
Decision Making in C++
Decision-making in C++ involves the usage of conditional statements (also called decision control statements) to execute specific blocks of code primarily based on given situations and their results.
So basically, in decision-making, we evaluate the conditions and make a decision about which part of the code should be executed or not. It allows selective code execution which is crucial for controlling the flow of a program and making it more dynamic.