Search⌘ K

Nested else-if Statement

Explore how nested else-if statements allow you to check multiple conditions sequentially in C++. This lesson helps you understand the flow and syntax of else-if chaining, enabling you to write programs that choose actions based on different criteria, demonstrated through a gift-buying example.

Introduction

Suppose you want to buy a present for your friend’s birthday. Below is a list of things, along with their costs, that you can buy for them:

Wrist-watch: $20

Comic book: $10

Chocolate: $5

Pen: $0

Based on available money, we have multiple choices to buy a present. How can we translate this example into a C++ program?


In C++, we can use the else-if statement to check multiple conditions in a program.


Syntax

The basic syntax for the else-if statement is given below:

...