×

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

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.

OOPs Concepts in C++

C++ Object-Oriented Programming Concepts C++ uses the concept of object-oriented programming. Object Oriented Programming has some prominent features: Object Class Data abstraction Encapsulation Polymorphism Inheritance Message passing Object An object is the basic unit...

2 minutes read.

C++ Program to find the largest number formed from an array

Given an array, write a program to find the largest number that will be formed from the elements of the array. Arrangement should be done in such a way that...

4 minutes read.

sort() function in C++

This tutorial covers the various built-in sort functions found in the C++ algorithm’s library.  What Does C++ Sort Mean? The concept of sorting in C++ entails rearranging an array's elements in a...

3 minutes read.

C++ Fibonacci Series

What is a Fibonacci series? A Fibonacci series or sequence is a very popular programming paradigm. The next element occurring in the N terms series is determined by the sum of...

2 minutes 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.

C++ Recursion Function

A programming method called recursion that uses a function to call itself to address lesser problems. The Fibonacci sequence, factorial computation, and tree traversal are just a few of the...

4 minutes read.

Reserved Keywords in C++

What are reserved keywords in C++? There are a few keywords that cannot be used as identifiers as those words are reserved for some other purposes, such keywords are called reserved...

15 minutes read.

Lambda Expression in C++

The lambda expression was introduced in C++ 11. It is used to write the inline function in C++. The code written in lambda expression cannot be reused further. The syntax...

3 minutes read.

Bitwise Operator vs Logical Operator

Bitwise Operator  Bitwise operators perform operations bit by bit on bits.The value is converted to abinary during operations like addition, subtraction, division, and so on. These operations are carried out at the...

3 minutes read.

Input Iterators in C++

What are input iterators? Input iterators are used in sequence for carrying out input operations where each value is read-only. It is pointed by the iterator and further incremented. All the iterators...

4 minutes read.

C++ Date and Time

The date and time formats in C++ will be covered in this article. Because C++ lacks a proper date and time format, we must rely on the c language. The...

7 minutes read.

Templates in C++ vs Generics in Java

As the title suggests, there is no rivalry or there is no cut comparison between generics and templates in Java and C++, respectively. The main aim of this article is...

4 minutes read.

Binary Search in C++

The binary search in the C++ programming language will be discussed. By continually halves the array and then seeking specified items from a half array; binary search is a technique...

8 minutes read.

C++ Range-based For Loop

In C++ language, the range-based for loop was added, which is far superior than the ordinary For loop. The implementation of a range-based for loop doesn't really need much code. It's a...

4 minutes read.

Armstrong Number using Do-While Loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

4 minutes read.

Difference between Two Sets in C++

The distinction between the two sets is made up of the components that are present in the first set but absent from the second set. The function consistently duplicates the...

3 minutes read.

Convex hull Algorithm in C++

The intersection of all convex sets containing a certain subset of a Euclidean space, or alternatively, the set of all convex combinations of points in the subset, defines the convex...

4 minutes read.

C++ Forward 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.

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.