Оператор If-Else
Свайпніть щоб показати меню
Оператор if-else є основним елементом у програмуванні. Він дозволяє керувати виконанням програми залежно від певних умов. Структура if-else досить проста:
main.c
123456if (condition) { // Execute this block of code if condition is `true` } else { // Execute this block of code if condition is `false` }
Наприклад, припустимо, що змінна temperature отримує значення з датчика, і потрібно створити програму, яка сповіщає, коли температура перевищує встановлений ліміт.
Main.c
1234567891011121314#include <stdio.h> int main() { int temperature = 200; // In celsius if (temperature > 80) { printf("Temperature is so high: %d degrees Celsius\n", temperature); } else { printf("Temperature is normal: %d degrees Celsius\n", temperature); } return 0; }
У програмі можна використовувати декілька операторів if, особливо коли потрібно перевірити різні умови. Оператор if-else можна додатково розширити за допомогою else-if:
Main.c
123456789101112131415161718192021#include <stdio.h> int main() { int tempereture = 50; // In celsius if (tempereture > 50) { printf("Temperature is high: %d degrees Celsius\n", tempereture); // First instruction } else if (tempereture > 100) { printf("Temperature is so high: %d degrees Celsius\n", tempereture);// Second instruction } else if (tempereture > 150) { printf("Temperature is critically high: %d degrees Celsius\n", tempereture);// Third instruction } else { printf("Temperature is normal: %d degrees Celsius\n", tempereture); // Fourth instruction } return 0; }
1. Яке призначення оператора if-else у програмуванні?
2. Яка базова структура оператора if-else у C, включаючи синтаксис для блоків коду.
Все було зрозуміло?
Дякуємо за ваш відгук!
Секція 4. Розділ 1
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат
Секція 4. Розділ 1