×

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

How to Use Getline in C++

What is getline in C++? Similar to the cin function, which allows the programmer to take input from the user getline() function also takes input from the user. But in this...

4 minutes read.

Print Table Using Do while Loop in C++

Multiplication Table In mathematics, a table is created by multiplying a certain number by all of the counting numbers, i.e., 1, 2, 3, 4, 5, 6, and so on. It is...

4 minutes read.

C++ Deque

Definition: Deque or the Doubly ended queue is a data structure or operation performed under queue where insertion and deletion are allowed at both ends. A deque is an ordered collection of...

5 minutes read.

ATM machine program in C++ using functions

Automated Teller Machines (ATMs) carry out daily financial transactions. They are straightforward and simple, allowing customers to complete self-service transactions quickly. ATMs can then be used to withdraw cash, deposit...

3 minutes read.

C++ Pointer

Pointer is a derived data type that stores the address of a variable. A pointer is used for memory management and dynamic memory allocation. Pointer works on the address of data rather than...

2 minutes read.

C++ History

C++ is a middle-level programming language developed in 1980s by Bjarne Stroustrup at Bel Labs. C ++ development initially started in 1979, four years before its launch. It is started with...

1 minute read.

C++ Friend function

A friend function has the right to access all private and protected members of a class although it is defined outside that class' scope. Syntax class className{     ......     friend retyrn_type function_Name(argument);     .......   }   return_type function_Name(argument){     ......   } C++ friend function Example #include <iostream>   using namespace std;   class Length   {       private:           int meter;       public:           Length(): meter(5) { }           friend int addMethod(Length); //friend function declaration   };   int addMethod(Length l) // friend function definition   {       l.meter += 10; //accessing private data from non-member function       return l.meter;   }   int main()   {       Length L;       int totallength;       totallength=addMethod(L);       cout<<"Length: "<< totallength;       return 0;   } Output: Length: 15   C++ friend function...

1 minute read.

goto statement in C and C++

goto statement in C and C++ The goto statement is a jump statement, also sometimes referred to as an unconditional jump statement. Within a function, the goto statement can be used...

3 minutes read.

C++ Do while loop

In this article, we will discuss the C++ Do-While loop with its syntax, working, key features, algorithm, and examples. Do-While Loop: The do-while loop constitutes a specific style of looping construct in...

5 minutes read.

Pointer to Object in C++

What is a pointer? A pointer in C++ is used to point the variable by storing the address of the variable. In C++, to print the address of the variable, we...

4 minutes read.

Features and Use of Pointers in C/C++

What is a pointer? A pointer is mainly used to store the address of another variable. The * operator creates a pointer variable, which points to a data type (like an...

7 minutes read.

Abstract class in C++

In this article, you will get exposure to an abstract class in C++. We will discuss this topic using some practical examples too. To understand the abstract classes, you should...

6 minutes read.

C++ Installation

Let's install C++ setup to start programming in C++. C++ setup contains C++ compiler which is required in your system. There are lots of C++ compilers available, you must choose...

1 minute read.

Counting Frequencies of Array Elements in C++

We have an array of integer items with duplicate values, and our objective is to compute the frequencies of the different elements in the array. Methods: Methods that can be used to...

3 minutes read.

Backtracking Time Complexity in C++

Introduction to Backtracking Backtracking is an important part of programming languages, and with the help of backtracking, we can do many operations in an advanced data structure. For doing major operations,...

4 minutes read.

Decltype type Specifier in C++

The primary use of C++ decltype is to inspect the declaration type of an entity in an expression. The auto keyword can declare a particular type of variable, whereas the...

4 minutes read.

Containership in C++

In C++, it is possible to create an object in one class into another class, and that object is a member of another class. This relationship is known as a...

4 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.

C++ First Program

Let's write a simple basic program structure of C++, its compilation and its execution (how it runs). This program is compiled using GCC compiler. Open any editor to write C++ program. #include<iostream>   using namespace std;   int main(){       cout<<"Welcome to C++ program"<<endl;   } Output...

2 minutes read.

C++ Expressions

C ++ equations are made up of operators, constants and variables arranged according to language rules. It may also include function calls that give results. To calculate the value, the...

4 minutes read.