Open In App

C++ if else Statement

Improve
Improve
Like Article
Like
Save
Share
Report

Decision Making in C++ helps to write decision-driven statements and execute a particular set of code based on certain conditions.

The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the C++ else statement. We can use the else statement with if statement to execute a block of code when the condition is false.

Syntax

if (condition)
{
    // Executes this block if
    // condition is true
}
else
{
    // Executes this block if
    // condition is false
}

Working of if-else statement

  1. Control falls into the if block.
  2. The flow jumps to Condition.
  3. Condition is tested.
    1. If Condition yields true, goto Step 4.
    2. If Condition yields false, goto Step 5.
  4. The if-block or the body inside the if is executed.
  5. The else block or the body inside the else is executed.
  6. Flow exits the if-else block.

Flowchart if-else:

Examples of if else statement in C++

Example 1:

Below program demonstrates the use of if else statements in C++.

C++




// C++ program to illustrate if-else statement 
    
#include <iostream> 
using namespace std; 
    
int main() 
    int i = 20; 
    
    // Check if i is 10 
    if (i == 10) 
        cout << "i is 10"
    
    // Since is not 10 
    // Then execute the else statement 
    else
        cout << "i is 20\n"
    
    cout << "Outside if-else block"
    
    return 0; 


Output

i is 20
Outside if-else block

Explanation:

  • Program starts.
  • i is initialized to 20.
  • if-condition is checked. i == 10, yields false.
  • flow enters the else block.
  • “i is 20” is printed
  • “Outside if-else block” is printed.

Example 2:

Another program to illustrate the use of if else in C.

C++




// C++ program to illustrate if-else statement 
    
#include <iostream> 
using namespace std; 
    
int main() 
    int i = 25; 
    
    if (i > 15) 
        cout << "i is greater than 15"
    else
        cout << "i is smaller than 15"
    
    return 0; 
}


Output

i is greater than 15

Related Articles:

  1. Decision Making in C / C++
  2. C/C++ if statement with Examples
  3. C/C++ if else if ladder with Examples
  4. Switch Statement in C/C++
  5. Break Statement in C/C++
  6. Continue Statement in C/C++
  7. goto statement in C/C++
  8. return statement in C/C++ with Examples
  9. Program to Assign grades to a student using Nested If Else


Last Updated : 11 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads