6.2.1: Conditional Execution - If-Else
- Page ID
- 29057
The if-else Statement
There is also an if statement that has 2 parts to it. The statements that execute when the condition is TRUE, and the statements that execute when the statements is FALSE. The syntax for the if-else control structure:
// C++ program to illustrate if-else statement #include<iostream> using namespace std; int main() { int myNum = 20; if (myNum < 15) cout << "myNum is smaller than 15" << endl; else cout << "myNum is greater than 15" << endl; return 0; }
Notice that we do NOT have the curly braces. This is allowed since we only have a single statement in the if portion and the else portion. You MAY include the brackets if you want to.
// C++ program to illustrate if-else statement #include<iostream> using namespace std; int main() { int myNum = 20; if (myNum < 15) { cout << "myNum is smaller than 15" << endl; myNum = 99; } else cout << "myNum is greater than 15" << endl; return 0; }
This again is valid, you only need the curly brackets if you want to include more than a single statement in your block of code. In this case if you left out the brackets you would get an error on the else statement.
Adapted from:
"If Then Else" by Kenneth Busbee, Download for free at http://cnx.org/contents/303800f3-07f...93e8948c5@22.2 is licensed under CC BY 4.0
"Decision Making in C / C++ (if , if..else, Nested if, if-else-if )" by Harsh Agarwal, Geeks for Geeks is licensed under CC BY-SA 4.0