The Wayback Machine - https://web.archive.org/web/20240930203522/https://www.geeksforgeeks.org/c-c-if-else-if-ladder-with-examples/
Open In App

C++ if else if Ladder

Last Updated : 11 Jan, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Decision-making in C++ helps to write decision-driven statements and execute a particular set of code based on certain conditions.

In C++, the if-else-if ladder helps the user decide from among multiple options. The C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C++ else-if ladder is bypassed. If none of the conditions is true, then the final statement will be executed.

Syntax

if (condition)
statement 1;
else if (condition)
statement 2;
.
.
else
statement;

Working of the if-else-if ladder

  1. Control falls into the if block.
  2. The flow jumps to Condition 1.
  3. Condition is tested.
    1. If Condition yields true, goto Step 4.
    2. If Condition yields false, goto Step 5.
  4. The present block is executed. Goto Step 7.
  5. The flow jumps to Condition 2.
    1. If Condition yields true, goto step 4.
    2. If Condition yields false, goto Step 6.
  6. The flow jumps to Condition 3.
    1. If Condition yields true, goto step 4.
    2. If Condition yields false, execute else block. Goto Step 7.
  7. Exits the if-else-if ladder.

Flowchart if-else-if ladder

if-else-if-ladder

Examples of if else if the ladder

Example 1:

Below program illustrates the use if else if ladder in C++.

C++




// C++ program to illustrate if-else-if ladder 
#include <iostream> 
using namespace std; 
    
int main() 
{ 
    int i = 20; 
    
    // Check if i is 10 
    if (i == 10) 
        cout << "i is 10"; 
    
    // Since i is not 10 
    // Check if i is 15 
    else if (i == 15) 
        cout << "i is 15"; 
    
    // Since i is not 15 
    // Check if i is 20 
    else if (i == 20) 
        cout << "i is 20"; 
    
    // If none of the above conditions is true 
    // Then execute the else statement 
    else
        cout << "i is not present"; 
    
    return 0; 
}


Output

i is 20

Explanation:

  • Program starts.
  • i is initialized to 20.
  • condition 1 is checked. 20 == 10, yields false.
  • condition 2 is checked. 20 == 15, yields false.
  • condition 3 is checked. 20 == 20, yields true. “i is 20” gets printed.
  • “Outside if-else-if” gets printed.
  • Program ends.

Example 2:

Another example to illustrate the use of if else if ladder in C++.

C++




// C++ program to illustrate if-else-if ladder
  
#include <iostream>
using namespace std;
  
int main()
{
    int i = 25;
  
    // Check if i is between 0 and 10
    if (i >= 0 && i <= 10)
        cout << "i is between 0 and 10" << endl;
  
    // Since i is not between 0 and 10
    // Check if i is between 11 and 15
    else if (i >= 11 && i <= 15)
        cout << "i is between 11 and 15" << endl;
  
    // Since i is not between 11 and 15
    // Check if i is between 16 and 20
    else if (i >= 16 && i <= 20)
        cout << "i is between 16 and 20" << endl;
  
    // Since i is not between 0 and 20
    // It means i is greater than 20
    else
        cout << "i is greater than 20" << endl;
}


Output

i is greater than 20


Previous Article
Next Article

Similar Reads

Decision Making in C (if , if..else, Nested if, if-else-if )
The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a set of statements or not. These decision-making sta
11 min read
C++17 new feature : If Else and Switch Statements with initializers
In many cases, we need to check the value of something returned by a function and perform conditional operations based on this value. So our code looks something like this // Some function return_type foo(params) // Call function with params and // store return in var auto var = foo(params); if (var == /* some value */) { //Do Something } else { //
3 min read
Execute both if and else statements in C/C++ simultaneously
Write a C/C++ program that executes both if-else block statements simultaneously. Syntax of if-else statement in C/C++ language is: if (Boolean expression) { // Statement will execute only // if Boolean expression is true } else { // Statement will execute only if // the Boolean expression is false } Hence we can conclude that only one of the block
2 min read
switch vs if else
Prerequisite - Switch Statement, Decision making(if else) A switch statement is usually more efficient than a set of nested ifs. Deciding whether to use if-then-else statements or a switch statement is based on readability and the expression that the statement is testing. Check the Testing Expression: An if-then-else statement can test expressions
3 min read
C++ if else Statement
Decision Making in C++ helps to write decision-driven statements and execute a particular set of code based on certain conditions. The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes th
2 min read
Difference Between if-else and switch in C
In C programming both switch statements and if-else statements are used to perform decision-making and control the flow of the program according to predefined conditions. In this article, we will discuss the differences between the if-else and switch statements. switch StatementA control flow statement called a switch statement enables a program to
4 min read
C++ Nested if-else Statement
In C++, there are various types of conditional statements such as if, if-else, nested if, nested if-else, and switch. In this article, we will learn about the nested if-else statement. What are Nested if-else Statements?Nested if-else statements are those statements in which there is an if statement inside another if else. We use nested if-else sta
3 min read
C++ Programming Language
C++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr
9 min read
30 OOPs Interview Questions and Answers (2024) Updated
Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
C++ Programming Examples
Writing C++ programs yourself is the best way to learn the C++ language. C++ programs are also asked in the interviews. This article covers the top practice problems for basic C++ programs on topics like control flow, patterns, and functions to complex ones like pointers, arrays, and strings. C++ Tutorial C++ Recent Articles Topics: Basic Programs
9 min read
map erase() Function in C++ STL
In C++, std::map::erase() is a built-in function of std::map container that is used to remove elements from the map. It can be used to erase the key-value pair at any specified position or in a given range. In this article, we will explore how to use the map::erase() function in different ways within a C++ program. The map::erase() function offers
4 min read
Left Shift and Right Shift Operators in C/C++
In C/C++, left shift (<<) and right shift (>>) operators are binary bitwise operators that are used to shift the bits either left or right of the first operand by the number of positions specified by the second operand allowing efficient data manipulation. In this article, we will learn about the left shift and right shift operators. Le
6 min read
vector erase() and clear() in C++
Prerequisite: Vector in C++ Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::clear() The clear() function is used to remove all the elements of the vector container, thus making it size 0. Syntax
6 min read
Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is <string>. The substring function takes two values pos and len as an argument
8 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the information about how it affects different properties of the
15+ min read
C++ Polymorphism
The word "polymorphism" means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. A real-life example of polymorphism is a person who at the same time can have different characteristics. A man at the same time is a father, a husband, and an employee. So the same person ex
7 min read
C++ Classes and Objects
In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. In this article, we will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program. What is a Class in C++?A class is a user-defined data type, which holds its own data members and member functions, w
9 min read
C++ Data Types
All variables use data type during declaration to restrict the type of data to be stored. Therefore, we can say that data types are used to tell the variables the type of data they can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared. Every data type
10 min read
std::sort() in C++ STL
std::sort() is an STL function that is used to sort the given range in desired order. It provides a simple and efficient way to sort the data in C++ but it only works on data structure which have random access to its elements such as vectors and arrays. It is defined inside <algorithm> header file. Syntaxstd::sort (first, last, comp);Paramete
4 min read
unordered_map in C++ STL
unordered_map is an associated container that stores elements formed by the combination of a key value and a mapped value. The key value is used to uniquely identify the element and the mapped value is the content associated with the key. Both key and value can be of any type predefined or user-defined. In simple terms, an unordered_map is like a d
7 min read
Priority Queue in C++ Standard Template Library (STL)
A C++ priority queue is a type of container adapter, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue, and elements are in non-increasing or non-decreasing order (hence we can see that each element of the queue has a priority {fixed order}). In C++ STL, the top elemen
11 min read
Vector in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inse
11 min read
Set in C++ Standard Template Library (STL)
Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The values are stored in a specific sorted order i.e. either ascending or descending. The std::set class is the part of C++ Standard Template Library (STL) and it is defined inside the <set> header file. Syntax: std:
7 min read
Map in C++ Standard Template Library (STL)
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. std::map is the class template for map containers and it is defined inside the <map> header file. Basic std::map Member FunctionsSome basic functions associated with std::
8 min read
Object Oriented Programming in C++
Object-oriented programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data
10 min read
Operator Overloading in C++
in C++, Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning. In this article, we will further discuss about operator overloading in C++ with examples and see which operators we can or cannot overload in C++. C++ Operator OverloadingC++ has
8 min read
Templates in C++ with Examples
A template is a simple yet very powerful tool in C++. The simple idea is to pass the data type as a parameter so that we don't need to write the same code for different data types. For example, a software company may need to sort() for different data types. Rather than writing and maintaining multiple codes, we can write one sort() and pass the dat
10 min read
Friend Class and Function in C++
A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private and protected members of other classes. For example, a LinkedList class may be allowed to access private members of Node. We can declare a friend class in C++ by using the
6 min read
Constructors in C++
Constructor in C++ is a special method that is invoked automatically at the time an object of a class is created. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. It constructs the values i.e. provides data for the object which is why it is known as a constructor
7 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
Article Tags :
Practice Tags :