C++ If Else - C++ Programming Tutorial
C++ Course / Control Flow / C++ If Else

C++ If Else

BLUF: Mastering C++ If Else is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: C++ If Else

C++ is renowned for its efficiency. Learn how C++ If Else enables low-level control and high-performance computing in the tutorial below.

Programming languages utilize conditional statements to dictate the flow of execution based on certain conditions. C++ programming provides the if-else statement as a core conditional feature for decision-making processes.

The if statement evaluates a specified condition to determine which code block to execute depending on whether the condition is true or false.

C++ offers various versions of the if statement to effectively handle diverse program needs. In C++ coding, the if statement is employed to evaluate conditions.

Types of if Statements in C++

There are various types of if statements in C++. Some of them are as follows:

  • if statement
  • if-else statement
  • if-else-if ladder
  • nested if statement

Each selection structure in C++ offers specific functionalities that enhance programming flexibility by executing different tasks.

1. C++ if Statement:

The fundamental type of conditional statement in C++ involves solely an if statement. In C++, the if statement evaluates the condition and executes the associated block of code if the condition is true. If the condition is false, the program skips the following if block.

Syntax:

It has the following syntax:

Example

if(condition){  

//code to be executed  

}

Flowchart of if statement

C++ If Example:

Let's consider a scenario to demonstrate the if statement in C++.

Example

Example

#include <iostream>  

using namespace std;  

   

int main () {  

   int num = 10;    

            if (num % 2 == 0) //using if statement

            {    

                cout<<"It is even number";    

            }   

   return 0;  

}

Output:

Output

It is even number

Explanation:

  • Upon evaluation, the software verifies if the number is divisible by 2; in the affirmative scenario, the software outputs "It is an even number."
  • In case of negative outcomes, the software proceeds with its execution without alterations.
  • 2. C++ If-else Statement:

The C++ if-else statement assesses a condition and runs the specified block of code when the condition is true; otherwise, it executes the else block.

Syntax:

It has the following syntax:

Example

if(condition){  

//code if condition is true  

}else{  

//code if condition is false  

}

Flowchart of if-else statement

C++ If-else Example:

Let's consider a scenario to demonstrate the if-else statement in C++.

Example

Example

#include <iostream>  

using namespace std;  

int main () {  

   int num = 11;    

            if (num % 2 == 0)    

            {    

                cout<<"It is even number";    

            }   

            else  

            {    

                cout<<"It is odd number";    

            }  

   return 0;  

}

Output:

Output

It is odd number

Explanation:

  • The expression number % 2 == 0 functions to verify if a number exhibits evenness.
  • Under this condition, the program displays "It is an even number".
  • The else block runs when the previous conditions are false and prints "It is an odd number".
  • 3. C++ if-else-if ladder Statement:

The C++ if-else-if ladder statement allows the execution of a single condition from a series of statements. This structure efficiently manages multiple cases by using a sequence of if-else if conditions.

Syntax:

It has the following syntax:

Example

if(condition1){  

//code to be executed if condition1 is true  

}else if(condition2){  

//code to be executed if condition2 is true  

}  

else if(condition3){  

//code to be executed if condition3 is true  

}  

...  

else{  

//code to be executed if all the conditions are false  

}

Flowchart of if-else-if ladder statement

C++ if-else-if ladder Example:

Let's consider a scenario to demonstrate the if-else-if ladder construct in C++.

Example

Example

#include <iostream>  

using namespace std;  

int main () {  

       int num;  

       cout<<"Enter a number to check grade:";    

       cin>>num;  

            if (num <0 || num >100)    

            {    

                cout<<"wrong number";    

            }    

            else if(num >= 0 && num < 50){    

                cout<<"Fail";    

            }    

            else if (num >= 50 && num < 60)    

            {    

                cout<<"D Grade";    

            }    

            else if (num >= 60 && num < 70)    

            {    

                cout<<"C Grade";    

            }    

            else if (num >= 70 && num < 80)    

            {    

                cout<<"B Grade";    

            }    

            else if (num >= 80 && num < 90)    

            {    

                cout<<"A Grade";    

            }    

            else if (num >= 90 && num <= 100)    

            {    

                cout<<"A+ Grade";  

            }    

    }

Output:

Output

Enter a number to check grade:66

C Grade

Output:

Output

Enter a number to check grade:-2

wrong number
  • The software assesses conditions in a step-by-step manner.
  • It processes each condition in order, executing the corresponding block of code and bypassing any subsequent conditional blocks.
  • 4. Nested if Statement:

The if statement format involves nesting another if statement inside its block. This nesting is essential for implementing multiple layers of conditional evaluations.

Syntax:

It has the following syntax:

Example

if (condition1) {

    if (condition2) {

        // Code executes if both conditions are true

    }

}

Flowchart of nested if statement

Nested if Example:

Let's consider an example to demonstrate the nested if statement in C++.

Example

Example

#include <iostream>

using namespace std;

int main() {

    int age; //interger value

    bool hasID; //Boolean value

    cout << "Enter your age: ";

    cin >> age;

    cout << "Do you have an ID? (1 for Yes, 0 for No): ";

    cin >> hasID;

// using nested if statement

    if (age >= 18) {

        if (hasID) {

            cout << "You are allowed to enter." << endl;

        } else {

            cout << "You need an ID to enter." << endl;

        }

    } else {

        cout << "You are not old enough to enter." << endl;

    }

    return 0;

}

Output:

Output

Enter your age:

18

Do you have an ID? (1 for Yes, 0 for No):

1

You are allowed to enter.

Explanation:

  • The outer block first verifies the user's age whether it exceeds 18 years.
  • The internal if statement requires verification of user identity through ID possession.
  • The system permits entry when both conditions match but denies entry if any condition fails to be satisfied.
  • Conclusion

In summary, C++ code employs if statements as fundamental decision-making tools that activate specific responses depending on various situations. Various options include basic if statements, if-else statements, if-else-if ladder, nested if statements, and the ternary operator, offering flexibility to handle diverse conditions. The choice of if statement type by a programmer impacts the code's readability, efficiency, and maintainability.

Frequently Asked Questions:

1. What role do C++ if statements serve in programming?

C++ programming provides the if statement to facilitate making decisions in programs. Code blocks within the program are executed only when a particular condition evaluates to true using an if statement. If the condition turns out to be false, the subsequent code block will not be executed.

2. What distinguishes if from if-else statements in the C++ language?

The if statement executes the block of code within its scope when the condition provided is true; however, it does not execute anything if the condition evaluates to false.

The if-else construct provides two possible routes for program flow based on a condition. When the specified condition is true, the if statement executes its corresponding block of code; otherwise, the program proceeds to the else block.

3. How do consecutive if statements behave when there are no else conditions present in a C++ program?

If conditions are assessed individually in the absence of an else statement. This allows for the activation of one or more code blocks when multiple true conditions are met.

4. Explain the fundamental differences between an if-else-if ladder and a switch statement.

An if-else-if ladder comprises a series of conditional statements in C++ that are evaluated sequentially to check various conditions. The evaluation process halts upon encountering the initial true condition in the sequence. On the other hand, the switch statement proves to be a more effective approach for managing multiple scenarios based on a single variable's value, especially when dealing with distinct values.

5. How do you define a nested if statement in C++?

An if statement becomes nested when it is placed inside another if statement. This nesting allows for more intricate decision-making by checking extra conditions once the primary outer condition is met.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience