C++ If Else Statement

The if statement in C++ programming language is used to execute a block of code only if a condition is true. It is used to check the truthness of the expression (In C++, all non-zero values are considered as true and zero is considered as false).

Syntax of If Statement
if (boolean_expression) {
    // Code to be executed if the condition is true
}
C++ If Statement Program Control flow Diagram
  • Condition written inside If statement parenthesis must be a boolean expression.
  • The if statement first evaluates the boolean expression inside parenthesis.
  • If the boolean_expression evaluated to true, then the block of code inside the if statement is executed.
  • If boolean_expression evaluated to false, then the block of code inside the if statement is ignored and the next statement after if block is executed.

C++ If statement Example Program

#include <iostream>
using namespace std;

int main(){
 
    int score;
    cout << "Enter your score : ";
    cin >> score;
    /* Using if statement to check whether 
       a student failed in examination or not*/
    if(score < 30){
     // if condition is true then print the following
        cout << "You Failed :(\n";
    }
    // This line always gets printed
 cout << "Your score : " << score;
 
    return 0;
}

Output
Enter your score : 45
Your score : 45
Enter your score : 25
You Failed :(
Your score : 25

If-Else Statement

The if else statement in C++ programming language execute if block statements if condition is true and execute else block statements when condition is false.

Syntax of if else statement
if (condition_expression) {
    // Code to be executed if the condition is true
} else {
    // Code to be executed if the condition is false
}
  • Condition written inside If statement parenthesis must be a boolean expression.
  • Either if block or else block gets executed(not both) depending on the outcome of conditional expression. Both if and else block of statements can never execute at a time.
  • If the condition_expression evaluated to true, then the if block of code gets executed.
  • If condition_expression evaluated to false, then the block of code inside the if body is ignored and block of code inside the else body is executed.
C++ If Else statement control flow diagram

C++ If Else Statement Example Program

#include <iostream>
using namespace std;

int main() {
    int score;
    cout << "Enter your score : ";
    cin >> score;
    /* Using if else statement to decide whether 
       a student passed or failed in examination */
    if(score < 35){
        // if condition is true then print the following
        cout << "You Failed :(\n";
    } else {
        // if condition is false then print the following
        cout << "Congrats You Passed :)\n";
    }
    // This line always gets printed
 cout << "Your score : " << score;
    return 0;
}

Output
Enter your score : 25
You Failed :(
Your score : 25
Enter your score : 60
Congrats You Passed :)
Your score : 60

C++ If Else Ladder Statement

  • The if else ladder statement in C++ programming language is used to check set of conditions in sequence.
  • This is useful when we want to selectively executes one code block(out of many) based on certain conditions.
  • It allows us to check for multiple condition expressions and execute different code blocks for more than two conditions.
  • A condition expression is tested only when all previous if conditions in if-else ladder is false.
  • If any of the conditional expression evaluates to true, then it will execute the corresponding code block and exits whole if-else ladder.

Syntax of if else ladder statement

if (condition1) {
    // Code to be executed if condition1 is true
} else if (condition2) {
    // Code to be executed if condition2 is true
} else {
    // Code to be executed if all conditions are false
}
  • First condition_expression_One is tested and if it is true then following code block will execute and control comes out out of whole if else ladder.
  • If condition_expression_One is false then only condition_expression_Two is tested. Control will keep on flowing downward, If none of the conditional expression is true.
  • The last else is the default block of code which will gets executed if none of the conditional expression is true.
  • If none of the conditional expressions evaluates to true then last else block will executes.
C++ If Else Ladder Statement Control Flow Diagram

C++ If Else Ladder Statement Example Program

#include <iostream>
using namespace std;
 
int main(){
    int score;
     
    cout << "Enter your score between 0-100\n";
    cin >> score;
    /* Using if else ladder statement to print
       Grade of a Student */
    if(score >= 90){
        // Marks between 90-100 
        cout << "YOUR GRADE : A\n";
    } else if (score >= 70 && score < 90){
        // Marks between 70-89 
        cout << "YOUR GRADE : B\n";
    } else if (score >= 50 && score < 70){
        // Marks between 50-69 
        cout << "YOUR GRADE : C\n";
    } else {
        // Marks less than 50 
        // if none of the conditions is true
       cout << "YOUR GRADE : Failed\n";
    }

    return 0;
}

Output
Enter your score between 0-100
72
YOUR GRADE : B
Enter your score between 0-100
10
YOUR GRADE : Failed

Points to Remember about If Else Statement
  • If else statement allows the program to select one of the two action based upon the user's input or the result of an expression. It gives us flexibility to change the logic of a program in different situations.
  • The condition_expression must be a boolean expression. It must evaluate to true or false value(In C++, all non-zero values are considered as true and zero is considered as false).
  • We may use more than one condition inside if else statement. We can use relational and logical operators like >, <, ==, && etc to create compound boolean expressions.
    For Example:
    if(condition_one && condition_two) {
        /* if code block */
    } else {
        /* else code block */
    }
  • Opening and Closing Braces are optional, If the block of code of if else statement contains only one statement.
    For Example:
    if(condition_one && condition_two) 
        statement1;
     else 
        statement2
    In above example only statement1 will gets executed if condition_expression is true otherwise statement2.

Best Practices for Using If-Else Statements

Now that you've mastered the art of if-else statements in C++, it's time to delve into some best practices that will enhance the readability, maintainability, and efficiency of your code.
  • Clarity Over Cleverness : While it might be tempting to condense your code into a single line using clever tricks, clarity should always take precedence. Choose readability over brevity to make your code easily understandable, especially by others who may need to maintain or collaborate on it.

  • Consistent Formatting : Maintain a consistent formatting style for your if-else statements. Consistency improves code readability and reduces cognitive load. Whether you choose the Allman, Stroustrup, or any other style, stick to it throughout your codebase.

  • Brace Usage : While it's optional to use braces for single-line if-else statements, adopting a consistent approach enhances code maintainability. Explicitly using braces can prevent subtle bugs and makes it easier to add more statements later without introducing errors.

  • Logical Parentheses : When dealing with complex conditions, use parentheses to make the logic explicit. This not only clarifies your intent but also avoids any potential misunderstandings due to operator precedence.

  • Avoid Nested Ternary Operators : While the ternary operator (? :) can be a concise way to express simple conditions, avoid nesting them excessively. Nesting ternary operators can quickly become unreadable and lead to maintenance challenges.

Conclusion

You've journeyed through the intricate world of the if statement in C++. You now possess the knowledge to make your code dynamically respond to conditions, creating programs that make decisions, evaluate expressions, and execute actions based on logical criteria.

As you continue your coding adventure, remember that the if statement is not just a tool; it's a versatile instrument that allows you to sculpt the flow of your code with precision. Whether you're dealing with simple conditions or nested decision trees, the if statement empowers you to bring your code to life.