×

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 true, then none of the other else if or else will be executed. It allows a program to check many expressions consecutively and run the first block when the condition evaluates to true. If none of the conditions are met, an optional else block is run.

Syntax:

It has the following syntax:

if (condition1) {

    // Code block executed if condition1 is true

}

else if (condition2) {

    // Code block executed if condition2 is true

}

else if (condition3) {

    // Code block executed if condition3 is true

}

else {

    // Code block executed if none of the above conditions are true

}

Explanation:

  • We start by examining the if block. The code for condition 1 runs and the subsequent ladder stages are omitted if it is true.
  • If condition 1 is not true, the program moves on to else if (condition 2). If condition 2 is true, then its block is run and the others are ignored.
  • Until a condition is judged to be actual, this process keeps going.
  • The else block (if provided) runs if any of the conditions are untrue.

Algorithm:

Start

Declare a variable to store input

Accept input from the user

Check conditions using If-Else-If:

If condition1 is true → execute block 1

Else if condition2 is true → execute block 2

Else if condition3 is true → execute block 3

Else → execute the default block

End

Pseudo code:

BEGIN

    DECLARE variable

    PRINT "Enter a value: "

    READ variable

    IF condition1 THEN

        PRINT "Condition 1 is True"

    ELSE IF condition2 THEN

        PRINT "Condition 2 is True"

    ELSE IF condition3 THEN

        PRINT "Condition 3 is True"

    ELSE

        PRINT "None of the conditions are True"

    ENDIF


END

Key Features:

Several key features of if-else-if statement in C++ are as follows:

  • Order Matters: From top to bottom, conditions are examined in order. The others are disregarded as soon as a real condition is identified.
  • Utilize Else for Default Execution: The else block makes sure that some code runs even in the event that none of the conditions are satisfied.
  • Although if statements can be stacked within one another, the if-else-if form is typically more readable and effective.
  • Avoid Redundant Conditions: In order to prevent needless checks, conditions should be logically ordered.

Example 1:

Let us take an example to illustrate the if-else-if statement in C++.

#include <iostream> 

using namespace std; 

int main() 

{ 

    int x = 50; 

    int y = 35; 

    if (x > y) 

    { 

        cout << "x is greater than y" << endl; 

    } 

    else if (y > x) 

    { 

        cout << "y is greater than x" << endl;    

    } 

    else 

    { 

        cout << "Both numbers are equal" << endl;  

    } 

    cout << "Value of x: " << x << ", Value of y: " << y; 

    return 0; 

}

Output:

x is greater than y

Value of x: 50, Value of y: 35

Example2:

In this example code, we determine the grade of the student basing upon the marks student scored:

#include <iostream>

using namespace std;

int main() {

    int marks;


    // Taking input from user

    cout << "Enter your marks: ";

    cin >> marks;


    // If-else-if ladder to determine grade

    if (marks >= 90) {

        cout << "Grade: A+" << endl;

    }

    else if (marks >= 80) {

        cout << "Grade: A" << endl;

    }

    else if (marks >= 70) {

        cout << "Grade: B" << endl;

    }

    else if (marks >= 60) {

        cout << "Grade: C" << endl;

    }

    else if (marks >= 50) {

        cout << "Grade: D" << endl;

    }

    else {

        cout << "Grade: F (Fail)" << endl;

    }

    return 0;

}

Output:

Enter your marks: 85

Grade: A

Enter your marks: 45

Grade: F (Fail)

Example 3:

In this example, we determine the temperature whether it is hot or cold:

#include <iostream>

using namespace std;

int main() {

    int temperature;

    cout << "Enter the temperature: ";

    cin >> temperature;

    if (temperature >= 35) {

        cout << "It's very hot!" << endl;

    }

    else if (temperature >= 25) {

        cout << "The weather is warm." << endl;

    }

    else if (temperature >= 15) {

        cout << "It's cool outside." << endl;

    }

    else {

        cout << "It's cold outside!" << endl;

    }

    return 0;

}

Output:

Enter the temperature: 30

The weather is warm.

Enter the temperature: 10

It's cold outside!

Conclusion:

In conclusion, the if-else-if statement in C++ is a fundamental decision-making structure that allows a computer to examine many conditions sequentially and, when a condition is met, run the corresponding block of code. When multiple possibilities need to be confirmed, such defining temperature levels, determining grades based on marks, or assessing user input, it is very useful. The structure makes the code more efficient and readable by restricting the amount of code blocks that run. Writing logical and structured programs that enable developers to properly build conditional processes requires an understanding of the if-else-if ladder. By using proper syntax and logical ordering, programmers can enhance the decision-making capabilities of their applications.


Related Topics

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.

Array of sets in C++

Instead of defining distinct variables for each item, arrays are used to hold numerous values in a single variable. A collection of data objects stored in a continuous way is...

6 minutes read.

External merge sort in C++

External merge sort in C++ External sorting is a concept for a group of sorting algorithms capable of handling large data volumes. External sorting is needed if the information getting sorted...

9 minutes read.

C++ Queue

C++ queue: Queue in C++ is also a container adapter with the functionality of a queue. Queue is just the opposite of the stack in C++ because stack works on...

4 minutes read.

C++ Exception Handling

Exception is an unexpected problem that occurs at program run time. This problem might include condition such as division by zero, running out of memory space, array out of bonds, etc....

2 minutes read.

C++ Bidirectional Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

Vector in C++

Vector in C++ In today’s article, we will be learning all the things about vector in C++ and how vector is different form an array in C++. So basically, vector is very...

3 minutes read.

Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++

Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++ 1/2 decimal equal is 0.555555555555555555555 .... An indefinite number of lengths will require the storage...

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.

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.

Converting string into integer in C++

When programming in C++, we'll frequently need to change one data type to another. When we use C++ to create apps, we must transform data from one type to another. When...

7 minutes read.

Implementation of a Falling Matrix in C++

In many Hollywood and Bollywood movies, we might have seen a programmer who will be referred to as a hacker all the time for some random reason which the writer...

3 minutes read.

How the value is passed in C++

Introduction: The call-by-value method of giving arguments to a function duplicates the real value of an argument into the formal parameter of the function. In this instance, modifications to the parameter...

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

C++ Features

C++ is a general-purpose programming language that evolved from the C language to include an object-oriented paradigm. It is a compiled and imperative language. Object-Oriented Programming Object-oriented programming language concepts: ClassObjectsEncapsulationPolymorphismInheritanceAbstraction Class: A Class...

4 minutes read.

Virtual base class in C++

Consider in a C++ program, there are 4 classes named class A, class B, class C, and class D. If class B and class c inherit properties from class A....

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

Differences between Local and Global Variable

Define Global Variable Global variables are those that may be accessible worldwide across a programme and are defined outside of any functions or blocks. It may be accessed by any function in...

3 minutes read.

Tensorflow in C++

With cppflow, you can execute TensorFlow models in C++ without Bazel, TensorFlow installation, or TensorFlow compilation. Tensor manipulation, eager execution, and running stored models straight from C++ are all possible. Knowing...

7 minutes read.

Star pattern in C++ using For Loops

Star patterns are one of the most extensively utilized patterns in any programming language since they help to increase logical thinking and flow control understanding.In the C++ programming language, you...

3 minutes read.