Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Switch Statement | Conditional Statements
Introduction to C++
course content

Зміст курсу

Introduction to C++

Introduction to C++

1. Basics
2. Variables
3. Conditional Statements
4. Loops
5. Intro to Arrays

bookSwitch Statement

If we have a lot of conditions it’s quite difficult to combine all of them using only if and else statements. For this reason, in C++ you can use the switch statement to define as many cases as you want. Use the following syntax:

We are evaluating here expression using switch statement. If expression is equal to one of the possible cases (a or b), we execute code in the correspending block. The keyword break at the end of case blocks means that when code in this block is executed we go out of the switch block.

You can use as many cases as you want.

Let’s take a look at the example:

123456789
int weekendDay = 1; switch (weekendDay) { &nbsp;&nbsp;&nbsp;&nbsp;case 1: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cout << "It's Saturday"; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break; &nbsp;&nbsp;&nbsp;&nbsp;case 2: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cout << "It's Sunday"; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break; }
copy

The code above prints the day of the weekend by its number. If it’s the first day (1) the code prints "It's Saturday", if it’s the second day - "It's Sunday".

The keyword break is optional and we will describe it more later.

question-icon

Let’s write a calculator which accepts the variable `a` and `b` type of double, `sign` type of char, and makes calculations.

// Declare variables
double a, b;
char sign;

// User input
cin >> a;
cin >> b;
cin >> sign;

// Write calculator
{
    case '-':
        cout << a - b;
        break;
    case '+':
        cout << a + b;
        
;
    case '*':
        
a * b;
        break;
    
:
        cout <<
;
        break;
}

Натисніть або перетягніть елементи та заповніть пропуски

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 3. Розділ 8
some-alt