Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вкладені оператори If | Вступ до Умовних Операторів
C++ Умовні оператори
course content

Зміст курсу

C++ Умовні оператори

C++ Умовні оператори

1. Вступ до Умовних Операторів
2. Практика умовного потоку управління
3. Поглиблені теми

Вкладені оператори If

Вкладений оператор if - це просто оператор if всередині іншого оператора if. Така структура дозволяє обчислювати декілька умов, одну за одною, і виконувати певні блоки коду. Зовнішній оператор if виконує роль воріт, і на основі отриманих даних ворота можуть відкритись для іншого оператора if всередині або ні.

Consider a scenario where we want to determine a worker salary based on their performance.

cpp

main

12345678910111213141516171819202122232425
#include <iostream> int main() { int current_salary = 1000; int completed_tasks = 17; int hours_worked = 37; // If the number of completed tasks is greater than 15, if (completed_tasks > 15) { // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; // And if the number of hours worked is more than 40 if (hours_worked > 40) { // add an additional 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; } } std::cout << current_salary << std::endl; }

Цей код розраховує нову заробітну плату працівника на основі кількості виконаних завдань та відпрацьованих годин, зі збільшенням на 20%, якщо завдань більше 15, та додатковим збільшенням на 20%, якщо відпрацьованих годин більше 40. Як бачите, поточний розрахунок становить 1200. І цього можна досягти лише за допомогою вкладених операторів if, ось деякі спроби отримати ту саму логіку без них.

cpp

main

12345678910111213141516171819202122232425
#include <iostream> int main() { int current_salary = 1000; int completed_tasks = 9; int hours_worked = 41; // If the number of completed tasks is greater than 15, if (completed_tasks > 15) { // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; } // If the number of hours worked is more than 40 if (hours_worked > 40) { // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; } std::cout << current_salary << std::endl; }

Спочатку може здатися, що все працює так само, але в цьому випадку працівник отримає додаткову надбавку 20%, незалежно від того, чи він виконав більше ніж 15 завдань. Запустіть код і подивіться на результат, він покаже значення 1200, хоча цього разу працівник не виконав більше ніж 15 завдань.

cpp

main

1234567891011121314151617181920212223
#include <iostream> int main() { int current_salary = 1000; int completed_tasks = 19; int hours_worked = 39; // If the number of completed tasks is greater than 15 // AND the number of of hours worked is more than 40 if (completed_tasks > 15 && hours_worked > 40) { // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; std::cout << current_salary << std::endl; } std::cout << current_salary << std::endl; }

У такому випадку може здатися, що все працюватиме як треба, але, на жаль, це також невірно, результат буде 1000. Це тому, що якщо працівник виконав більше ніж 15 завдань, але не пропрацював понад 40 годин, він нічого не отримає. Тому нам доведеться використовувати вкладені if оператори, щоб забезпечити правильну реалізацію.

У цьому випадку може здатися, що він повинен працювати як задумано, але, на жаль, це також неправильно, результат буде 1000. Це тому, що якщо працівник виконає більше 15 завдань, але не відпрацює більше 40 годин, він нічого не отримає. Отже, нам необхідно використовувати вкладені оператори if, щоб отримати правильну реалізацію.

Note

Nested if statements are necessary in some cases but not always. In the third section, we'll discuss when, why and how to avoid them.

Завдання

We have an excess of pink phones in our inventory that we need to sell.

  • Make a 20% discount on pink phones.
  • If a phone's price exceeds $1,000, the discount will be reduced to 10%.
  • For all other phones, increase the price by 10%.

Завдання

We have an excess of pink phones in our inventory that we need to sell.

  • Make a 20% discount on pink phones.
  • If a phone's price exceeds $1,000, the discount will be reduced to 10%.
  • For all other phones, increase the price by 10%.

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

Секція 1. Розділ 5
toggle bottom row

Вкладені оператори If

Вкладений оператор if - це просто оператор if всередині іншого оператора if. Така структура дозволяє обчислювати декілька умов, одну за одною, і виконувати певні блоки коду. Зовнішній оператор if виконує роль воріт, і на основі отриманих даних ворота можуть відкритись для іншого оператора if всередині або ні.

Consider a scenario where we want to determine a worker salary based on their performance.

cpp

main

12345678910111213141516171819202122232425
#include <iostream> int main() { int current_salary = 1000; int completed_tasks = 17; int hours_worked = 37; // If the number of completed tasks is greater than 15, if (completed_tasks > 15) { // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; // And if the number of hours worked is more than 40 if (hours_worked > 40) { // add an additional 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; } } std::cout << current_salary << std::endl; }

Цей код розраховує нову заробітну плату працівника на основі кількості виконаних завдань та відпрацьованих годин, зі збільшенням на 20%, якщо завдань більше 15, та додатковим збільшенням на 20%, якщо відпрацьованих годин більше 40. Як бачите, поточний розрахунок становить 1200. І цього можна досягти лише за допомогою вкладених операторів if, ось деякі спроби отримати ту саму логіку без них.

cpp

main

12345678910111213141516171819202122232425
#include <iostream> int main() { int current_salary = 1000; int completed_tasks = 9; int hours_worked = 41; // If the number of completed tasks is greater than 15, if (completed_tasks > 15) { // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; } // If the number of hours worked is more than 40 if (hours_worked > 40) { // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; } std::cout << current_salary << std::endl; }

Спочатку може здатися, що все працює так само, але в цьому випадку працівник отримає додаткову надбавку 20%, незалежно від того, чи він виконав більше ніж 15 завдань. Запустіть код і подивіться на результат, він покаже значення 1200, хоча цього разу працівник не виконав більше ніж 15 завдань.

cpp

main

1234567891011121314151617181920212223
#include <iostream> int main() { int current_salary = 1000; int completed_tasks = 19; int hours_worked = 39; // If the number of completed tasks is greater than 15 // AND the number of of hours worked is more than 40 if (completed_tasks > 15 && hours_worked > 40) { // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; std::cout << current_salary << std::endl; } std::cout << current_salary << std::endl; }

У такому випадку може здатися, що все працюватиме як треба, але, на жаль, це також невірно, результат буде 1000. Це тому, що якщо працівник виконав більше ніж 15 завдань, але не пропрацював понад 40 годин, він нічого не отримає. Тому нам доведеться використовувати вкладені if оператори, щоб забезпечити правильну реалізацію.

У цьому випадку може здатися, що він повинен працювати як задумано, але, на жаль, це також неправильно, результат буде 1000. Це тому, що якщо працівник виконає більше 15 завдань, але не відпрацює більше 40 годин, він нічого не отримає. Отже, нам необхідно використовувати вкладені оператори if, щоб отримати правильну реалізацію.

Note

Nested if statements are necessary in some cases but not always. In the third section, we'll discuss when, why and how to avoid them.

Завдання

We have an excess of pink phones in our inventory that we need to sell.

  • Make a 20% discount on pink phones.
  • If a phone's price exceeds $1,000, the discount will be reduced to 10%.
  • For all other phones, increase the price by 10%.

Завдання

We have an excess of pink phones in our inventory that we need to sell.

  • Make a 20% discount on pink phones.
  • If a phone's price exceeds $1,000, the discount will be reduced to 10%.
  • For all other phones, increase the price by 10%.

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

Секція 1. Розділ 5
toggle bottom row

Вкладені оператори If

Вкладений оператор if - це просто оператор if всередині іншого оператора if. Така структура дозволяє обчислювати декілька умов, одну за одною, і виконувати певні блоки коду. Зовнішній оператор if виконує роль воріт, і на основі отриманих даних ворота можуть відкритись для іншого оператора if всередині або ні.

Consider a scenario where we want to determine a worker salary based on their performance.

cpp

main

12345678910111213141516171819202122232425
#include <iostream> int main() { int current_salary = 1000; int completed_tasks = 17; int hours_worked = 37; // If the number of completed tasks is greater than 15, if (completed_tasks > 15) { // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; // And if the number of hours worked is more than 40 if (hours_worked > 40) { // add an additional 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; } } std::cout << current_salary << std::endl; }

Цей код розраховує нову заробітну плату працівника на основі кількості виконаних завдань та відпрацьованих годин, зі збільшенням на 20%, якщо завдань більше 15, та додатковим збільшенням на 20%, якщо відпрацьованих годин більше 40. Як бачите, поточний розрахунок становить 1200. І цього можна досягти лише за допомогою вкладених операторів if, ось деякі спроби отримати ту саму логіку без них.

cpp

main

12345678910111213141516171819202122232425
#include <iostream> int main() { int current_salary = 1000; int completed_tasks = 9; int hours_worked = 41; // If the number of completed tasks is greater than 15, if (completed_tasks > 15) { // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; } // If the number of hours worked is more than 40 if (hours_worked > 40) { // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; } std::cout << current_salary << std::endl; }

Спочатку може здатися, що все працює так само, але в цьому випадку працівник отримає додаткову надбавку 20%, незалежно від того, чи він виконав більше ніж 15 завдань. Запустіть код і подивіться на результат, він покаже значення 1200, хоча цього разу працівник не виконав більше ніж 15 завдань.

cpp

main

1234567891011121314151617181920212223
#include <iostream> int main() { int current_salary = 1000; int completed_tasks = 19; int hours_worked = 39; // If the number of completed tasks is greater than 15 // AND the number of of hours worked is more than 40 if (completed_tasks > 15 && hours_worked > 40) { // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; std::cout << current_salary << std::endl; } std::cout << current_salary << std::endl; }

У такому випадку може здатися, що все працюватиме як треба, але, на жаль, це також невірно, результат буде 1000. Це тому, що якщо працівник виконав більше ніж 15 завдань, але не пропрацював понад 40 годин, він нічого не отримає. Тому нам доведеться використовувати вкладені if оператори, щоб забезпечити правильну реалізацію.

У цьому випадку може здатися, що він повинен працювати як задумано, але, на жаль, це також неправильно, результат буде 1000. Це тому, що якщо працівник виконає більше 15 завдань, але не відпрацює більше 40 годин, він нічого не отримає. Отже, нам необхідно використовувати вкладені оператори if, щоб отримати правильну реалізацію.

Note

Nested if statements are necessary in some cases but not always. In the third section, we'll discuss when, why and how to avoid them.

Завдання

We have an excess of pink phones in our inventory that we need to sell.

  • Make a 20% discount on pink phones.
  • If a phone's price exceeds $1,000, the discount will be reduced to 10%.
  • For all other phones, increase the price by 10%.

Завдання

We have an excess of pink phones in our inventory that we need to sell.

  • Make a 20% discount on pink phones.
  • If a phone's price exceeds $1,000, the discount will be reduced to 10%.
  • For all other phones, increase the price by 10%.

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

Вкладений оператор if - це просто оператор if всередині іншого оператора if. Така структура дозволяє обчислювати декілька умов, одну за одною, і виконувати певні блоки коду. Зовнішній оператор if виконує роль воріт, і на основі отриманих даних ворота можуть відкритись для іншого оператора if всередині або ні.

Consider a scenario where we want to determine a worker salary based on their performance.

cpp

main

12345678910111213141516171819202122232425
#include <iostream> int main() { int current_salary = 1000; int completed_tasks = 17; int hours_worked = 37; // If the number of completed tasks is greater than 15, if (completed_tasks > 15) { // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; // And if the number of hours worked is more than 40 if (hours_worked > 40) { // add an additional 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; } } std::cout << current_salary << std::endl; }

Цей код розраховує нову заробітну плату працівника на основі кількості виконаних завдань та відпрацьованих годин, зі збільшенням на 20%, якщо завдань більше 15, та додатковим збільшенням на 20%, якщо відпрацьованих годин більше 40. Як бачите, поточний розрахунок становить 1200. І цього можна досягти лише за допомогою вкладених операторів if, ось деякі спроби отримати ту саму логіку без них.

cpp

main

12345678910111213141516171819202122232425
#include <iostream> int main() { int current_salary = 1000; int completed_tasks = 9; int hours_worked = 41; // If the number of completed tasks is greater than 15, if (completed_tasks > 15) { // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; } // If the number of hours worked is more than 40 if (hours_worked > 40) { // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; } std::cout << current_salary << std::endl; }

Спочатку може здатися, що все працює так само, але в цьому випадку працівник отримає додаткову надбавку 20%, незалежно від того, чи він виконав більше ніж 15 завдань. Запустіть код і подивіться на результат, він покаже значення 1200, хоча цього разу працівник не виконав більше ніж 15 завдань.

cpp

main

1234567891011121314151617181920212223
#include <iostream> int main() { int current_salary = 1000; int completed_tasks = 19; int hours_worked = 39; // If the number of completed tasks is greater than 15 // AND the number of of hours worked is more than 40 if (completed_tasks > 15 && hours_worked > 40) { // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; std::cout << current_salary << std::endl; } std::cout << current_salary << std::endl; }

У такому випадку може здатися, що все працюватиме як треба, але, на жаль, це також невірно, результат буде 1000. Це тому, що якщо працівник виконав більше ніж 15 завдань, але не пропрацював понад 40 годин, він нічого не отримає. Тому нам доведеться використовувати вкладені if оператори, щоб забезпечити правильну реалізацію.

У цьому випадку може здатися, що він повинен працювати як задумано, але, на жаль, це також неправильно, результат буде 1000. Це тому, що якщо працівник виконає більше 15 завдань, але не відпрацює більше 40 годин, він нічого не отримає. Отже, нам необхідно використовувати вкладені оператори if, щоб отримати правильну реалізацію.

Note

Nested if statements are necessary in some cases but not always. In the third section, we'll discuss when, why and how to avoid them.

Завдання

We have an excess of pink phones in our inventory that we need to sell.

  • Make a 20% discount on pink phones.
  • If a phone's price exceeds $1,000, the discount will be reduced to 10%.
  • For all other phones, increase the price by 10%.
Секція 1. Розділ 5
Перейдіть на комп'ютер для реальної практикиПродовжуйте з того місця, де ви зупинились, використовуючи один з наведених нижче варіантів
We're sorry to hear that something went wrong. What happened?
some-alt