×

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 Declare Unordered Sets in C++

The implementation of an unordered set using a hash table ensures that the insertion is always randomised by hashing the keys into hash table indices. When we define keys of...

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.

Pthreads or POSIX Threads in C++

The thread API for C/C++ is implemented by pthreads or POSIX threads. It enables the multithreading system, which enables parallel and distributed processing, and the creation of new concurrent process...

3 minutes read.

C++ Friend Functions

In C++, friends are special functions that are not a part of a class yet have access to its private and protected members. The friend keyword is used to declare...

4 minutes read.

New Operator in C++

Dynamic memory allocation in C++ means manually allocating the memory by the developer duing run-time. The dynamic memory is allocated in the heap section of the RAM, whereas the static...

3 minutes read.

Random Number Generator in C++

In programming, we need to frequently create the randomly. For example, a dice game, handing out cards to players, apps for rearranging tunes, etc. T There are two tools available in...

4 minutes read.

C++ Program For FCFS (First Come First Serve)

The most basic scheduling technique is FCFS, often known as "FIFO (First In, First Out)". In this procedure, the first one is utilized and executed first, while the second one...

4 minutes read.

Print Table Using 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.

Copy constructor

Let's start by learning what a constructor is before diving into the copy constructor in C++. What is a constructor? A constructor is a particular type of class member function that configures the objects of...

7 minutes read.

C ++ Program: Alphabet Triangle and Number Triangle

Alphabet Triangle and Number Triangle An alphabet triangle is a triangle that typically looks like a pyramid or other triangles like an isosceles triangle, a right-angled triangle consisting of similar or...

4 minutes read.

Octal to Decimal in C++

We need to write a system that converts octal number into equal decimal number when octal number is given as input. Let us look at an example of a program in...

2 minutes read.

C++ Type Casting

The type casting of variables in the C++ programming language will be covered in this section. The term "type casting" describes how software converts one data type to another. There...

9 minutes read.

Palindrome using Do-while loop in C++

What is Palindrome? A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++...

5 minutes read.

C++ Call by Value

In this article, we will discuss C++ Call by Value with their syntax, examples, use cases, advantages, and disadvantages. C++ Function A function is a set of statements that executes a task....

5 minutes read.

C++ If

C++ Control Statement C++ control statement or decision-making statement is used to control the flow of program statement according to condition applied. C++ if Control Statement An if control statement in C++ is used to...

2 minutes read.

C++ vs C#

What exactly is C++ programming? Bjorne Stroustrup is the creator of the C++ programming language. His goal was to create a powerful object-oriented programming language with the capabilities of C. It...

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

Add two numbers represented by two arrays in C++

The array stores a number in such a way that each digit of the number is represented by an array element. As an example, The array number 147 is 1,4,7. To add...

3 minutes read.

C++ Overriding

C++ Function Overriding When the base and derive class both contain the same function name and calling the function through derived object invokes derived class function called function overriding. Function overloading is...

1 minute read.

Dynamic Binding in C++

The notion of dynamic binding solved the challenges associated with static binding. Static binding refers to bindings that can be resolved by the compiler at runtime. All storage, stationary, and...

3 minutes read.