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++ | Mobile-Friendly

book
Switch 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:

python
switch (expression) {
case a:
// code expression is equal to a
break;
case b:
// code expression is equal to b
break;
}

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:

int weekendDay = 1;
switch (weekendDay) {
    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;
}
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 variables 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;
}

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

dots
if (sign)
dots
case '/'
dots
a // b
dots
break
dots
cout >>
dots
a / b
dots
cout <<
dots
switch (sign)
dots
case '%'

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

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

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

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