Conditional Statements
Conditional Statements
• if(condition){
• Statement(s);
• }
• The statements inside if parenthesis (usually referred as if body) gets executed only when the
given condition is true. If the condition is false then the statements inside if body are
completely ignored.
Flow diagram of If statement
• #include <iostream>
Example of if statement
• using namespace std;
• int main(){
• int num=70;
• if( num < 100 ){
• /* This cout statement will only execute,
• * if the above condition is true
• */
• cout<<"number is less than 100";
• }
• if(condition_2) {
• Statement2(s);
• }
• }
……
• Statement1 would execute if the condition_1 is true. Statement2 would
only execute if both the conditions( condition_1 and condition_2) are true.
Example of Nested if statement
• #include <iostream>
• using namespace std;
• int main(){
• int num=90;
• /* Nested if statement. An if statement
• * inside another if body
• */
• if( num < 100 )
• {
• cout<<"number is less than 100"<<endl;
• if(num > 50)
• {
• cout<<"number is greater than 50";
• }
• }
• return 0;
• }
• Output:
• Sometimes you have a condition and you want to execute a block of code if condition is true and
execute another piece of code if the same condition is false. This can be achieved in C++ using
if-else statement.
• if(condition) {
• Statement(s);
• }
• else {
• Statement(s);
• }
Flow diagram of if-else
Example of if-else statement
• #include <iostream>
• using namespace std;
• int main(){
• int num=66;
• if( num < 50 ){
• //This would run if above condition is true
• cout<<"num is less than 50";
• }
• else {
• //This would run if above condition is false
• cout<<"num is greater than or equal 50";
• }
• return 0;
• }
• Output: