Khái niệm
Rẽ nhánh là cơ chế cho phép chương trình chọn một hướng xử lý dựa trên kết quả của điều kiện. Đây là nền tảng của việc ra quyết định trong chương trình.
Ví dụ tổng quan
temperature = 32
if temperature >= 30:
print("Troi nong")
else:
print("Nhiet do vua phai")
program ConditionIntro;
var
temperature: Integer;
begin
temperature := 32;
if temperature >= 30 then
Writeln('Troi nong')
else
Writeln('Nhiet do vua phai');
end.
#include <stdio.h>
int main(void) {
int temperature = 32;
if (temperature >= 30) {
printf("Troi nong\n");
} else {
printf("Nhiet do vua phai\n");
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
int temperature = 32;
if (temperature >= 30) {
cout << "Troi nong" << endl;
} else {
cout << "Nhiet do vua phai" << endl;
}
return 0;
}
int temperature = 32;
if (temperature >= 30) {
Console.WriteLine("Troi nong");
} else {
Console.WriteLine("Nhiet do vua phai");
}
const temperature = 32;
if (temperature >= 30) {
console.log("Troi nong");
} else {
console.log("Nhiet do vua phai");
}
const temperature: number = 32;
if (temperature >= 30) {
console.log("Troi nong");
} else {
console.log("Nhiet do vua phai");
}
package main
import "fmt"
func main() {
temperature := 32
if temperature >= 30 {
fmt.Println("Troi nong")
} else {
fmt.Println("Nhiet do vua phai")
}
}
fn main() {
let temperature = 32;
if temperature >= 30 {
println!("Troi nong");
} else {
println!("Nhiet do vua phai");
}
}
Các dạng thường gặp
- Chọn thực hiện hoặc bỏ qua một khối lệnh.
- Chọn giữa hai hướng xử lý loại trừ nhau.
- Chọn giữa nhiều trường hợp theo thứ tự ưu tiên.
- Kết hợp nhiều điều kiện để mô tả quy tắc phức tạp hơn.
Bình luận