×

C++ Nested if

C++'s nested if statements enable more complex decision-making when a section of code needs to execute only after a set of conditions is met. The nested if control statement refers to the if condition within the if condition. C++ compiler checks nested if control statement when its parent if condition returns true; the program is executed according to the nested if condition.

Syntax:

It has the following syntax:

if (condition1) {

    if (condition2) {

        // Code executes if both condition1 and condition2 are true

    }

}

Algorithm:

  • Start.
  • Declare an integer variable num.
  • Prompt the user to enter a number.
  • Read and store the value in num.
  • Check if num is greater than 0:
  • If true, print "The number is positive."
  • Then, check if num is even (num % 2 == 0):
  • If true, print "The number is even."
  • Then, check if num is greater than 10:
  • If true, print "The number is greater than 10."
  • End the program

Pseudo code:

Begin

    Declare num as Integer

    Print "Enter a number: "

    Input num    

    If num > 0 THEN

        Print "The number is positive."        

        If num MOD 2 == 0 then

            Print "The number is even."         

            If num > 10 then

                Print "The number is greater than 10."

            Endif           

        Endif        

    Endif

End

Key Features of Nested If Statement:

Several key features of Nested if Statement in C++ are as follows:

  • Numerous Condition Checking: This feature makes it possible to verify several conditions in a hierarchical manner.
  • The outside if determines the inner if. The inner if statement executes only in the event that the outer if condition is true.
  • It supports both else and otherwise if we can use nested if blocks to enclose else or else if statements in order to provide alternative results.
  • Enhances Decision-Making: It is helpful when existing circumstances depend on past ones.
  • A Variety of Levels Are Possible: It allows for multiple nesting levels, while excessive nesting could make the text harder to read.
  • Keeps Code Flow Control: It helps with the organization of intricate conditional logic.

Key Points:

  • The inner if is only executed if the outer if condition is true.
  • It makes handling complex decision-making scenarios easier.
  • Maintaining appropriate indentation and structure is crucial since overuse can make text more difficult to read.

Example 1: Basic Nested if statement Block:

In these codes, it checks whether the number is even and positive or not.

#include <iostream>

using namespace std;

int main() {

    int num = 10;

    if (num > 0) {  // Outer if: checks if the number is positive

        if (num % 2 == 0) {  // Inner if: checks if the number is even

            cout << "The number is positive and even." << endl;

        }

    }

    return 0;

}

Output:

The number is positive and even.

Example 2: Nested if containing Else:

In these codes, it checks whether the number is positive, negative even or odd:

#include <iostream>

using namespace std;

int main() {

    int num;

    cout << "Enter a number: ";

    cin >> num;

    if (num > 0) {

        cout << "The number is positive." << endl;

        if (num % 2 == 0) {

            cout << "It is even." << endl;

        } else {

            cout << "It is odd." << endl;

        }

    } else if (num < 0) {

        cout << "The number is negative." << endl;

    } else {

        cout << "The number is zero." << endl;

    }

    return 0;

}

Output:

Enter a number: 11

The number is positive.

It is odd.

Example 3: Multiple levels of Nested if:

In these, we determine the criteria for a person who is eligible to vote based on age and citizenship:

#include <iostream>

using namespace std;

int main() {

    int age;

    char citizenship;


    cout << "Enter your age: ";

    cin >> age;

    cout << "Are you a citizen? (y/n): ";

    cin >> citizenship;

    if (age >= 18) {  // First condition

        if (citizenship == 'y' || citizenship == 'Y') {  // Second condition

            cout << "You are eligible to vote." << endl;

        } else {

            cout << "You must be a citizen to vote." << endl;

        }

    } else {

        cout << "You must be at least 18 years old to vote." << endl;

    }

    return 0;

}

Output:

Enter your age: 20

Are you a citizen? (y/n): y

You are eligible to vote.

Conclusion:

In conclusion, the flexible control structure of C++'s nested if statements allow programmers to manage complex decision-making by hierarchically checking a variety of scenarios. The inner if only executes when the outer if condition is satisfied to guarantee logical flow and well-organized decision-making. When more than one level of verification is required, such as when verifying user inputs based on multiple criteria or figuring out a voter's age and citizenship, this functionality is useful. Appropriate indentation and structure are essential, while layering increases code flexibility, doing so too much can make the code less readable. When it comes to writing logical and efficient C++ applications, nested if statements are crucial.


Related Topics

Single level Inheritance

Inheritance is a fundamental element of C++’s Object-Oriented Programming (OOP). It allows a class (called the derived class) to inherit characteristics and attributes from another class (called the base class)....

5 minutes read.

C++ Continue in for loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the start...

4 minutes read.

C++ Infinite loop

The term "infinite loop" refers to a loop that does not terminate the loop according to the condition. In some cases, an infinite loop may be required in programming, or...

4 minutes read.

C++ Fork

A new process known as a "child process" is created with the fork system function and runs concurrently with the process that invoked fork() (parent process). Both processes will carry...

4 minutes read.

Diamond Pattern in C++ using For Loop

For Loop: A for loop is a repetitive control structure that allows you to create a loop for executing a specific number of times. The syntax of for loop: In C++, a for...

5 minutes read.

Functions in C++ with Types and Examples

A function is a collection of statements that work together to complete a certain goal. It could consist of statements that execute repetitive operations or statements that conduct specialized jobs...

10 minutes read.

How to create a table in C++

C++ is a programming language that has evolved as an improvement of c language. It includes an object-oriented archetype. C++ programming language is a compiled language that complies with the...

3 minutes read.

Constexpr in C++

Constexpr is a keyword in C++ that is used to declare variables or functions as compile-time constants. This means that the value of a constexpr variable or the return value...

3 minutes read.

The Stock Span Problem

It is necessary to determine the span of a stock's price throughout all n days in order to solve the stock span problem, which involves a set of n daily...

5 minutes read.

C++ Void Pointer

A void pointer is a general purpose pointer that can have an address of any data type but is not related to any data type. Void Pointer Syntax: void *ptr;  We can't...

2 minutes read.

System() function in C++

As a part of the c/c+ standard library, the system() function passes commands to be executed by the operating system’s command processor or terminal and returns the completed command. We...

2 minutes read.

Priority Queue in C++

Priority Queue in C++ Introduction: We have already come across Queues by concluding that they are linear data structures that follow FIFO (First-In-First-Out) approach. We had also discussed the syntax of queues...

4 minutes read.

C++ Program to move all zeros to the end of the array

Write a program to move all the zeros in the arr[] to the end. The order of the non-zero elements should not be altered and all the zeros should be...

3 minutes read.

How to improve programming skills in C++

Before getting started, one should know why to improve their programming skills. To become a good software developer or programmer, one must be skilled in at least one programming language. Many...

4 minutes read.

C++ String Class and its Applications

The String class is available in C++. The character array is represented by the C string. The string class in C++ has a few different attributes. It contains several functions...

4 minutes read.

Roadmap to C++ Programming

Introduction There are so many programming languages available in the market, but among them, C++ is something that never lost its charm. It has a powerful impact on the programming world....

4 minutes read.

C++ If-else-if

Introduction: If-else-if control statement is an if statement used with an optional else if control statement to check multiple conditions. In this control statement, when any one of the condition returns...

4 minutes read.

Features of OOPS in C++

What is OOPs? The main reason programmers prefer C ++ language over C is because of the support of object-oriented programing in C++. As the name suggests, object-oriented programming or OOPs...

3 minutes read.

How to Reverse a String in C++ using For Loop

For Loop: We may loop through a certain section of C++ code repeatedly using the for loop. A for loop is carried out if the test expression yields a true result. The...

4 minutes read.

Ascending order in C++

In C++, the term "ascending order" refers to a specific order in which a list of elements is arranged. When a list of elements is arranged in ascending order, the...

3 minutes read.