🔁 Vòng lặp while
🎯 Mục tiêu: Hiểu cách sử dụng while loop khi không biết trước số lần lặp.
💡 Khái niệm
Phần tiêu đề “💡 Khái niệm”while: Kiểm tra điều kiện trước khi thực thido-while: Thực thi ít nhất 1 lần, rồi mới kiểm tra điều kiện
📝 while loop
Phần tiêu đề “📝 while loop”Cú pháp
Phần tiêu đề “Cú pháp”while (condition) { // code}Ví dụ
Phần tiêu đề “Ví dụ”var count = 0
while (count < 5) { println("Count: $count") count++}// 0, 1, 2, 3, 4🔄 do-while loop
Phần tiêu đề “🔄 do-while loop”Cú pháp
Phần tiêu đề “Cú pháp”do { // code (thực thi ít nhất 1 lần)} while (condition)Ví dụ
Phần tiêu đề “Ví dụ”var count = 0
do { println("Count: $count") count++} while (count < 5)Khác biệt với while
Phần tiêu đề “Khác biệt với while”// while - không thực thi nếu điều kiện sai từ đầuvar x = 10while (x < 5) { println("while: $x") // Không in gì x++}
// do-while - luôn thực thi ít nhất 1 lầnvar y = 10do { println("do-while: $y") // In "do-while: 10" y++} while (y < 5)🎯 Use Cases phổ biến
Phần tiêu đề “🎯 Use Cases phổ biến”Đọc input cho đến khi hợp lệ
Phần tiêu đề “Đọc input cho đến khi hợp lệ”var input: Int?
do { print("Nhập số dương: ") input = readln().toIntOrNull()} while (input == null || input <= 0)
println("Bạn đã nhập: $input")Game loop
Phần tiêu đề “Game loop”var playing = truevar lives = 3
while (playing && lives > 0) { println("Đang chơi... Lives: $lives")
// Simulate game logic if (kotlin.random.Random.nextBoolean()) { lives-- println("Mất mạng!") }
if (lives == 0) { println("Game Over!") playing = false }}Countdown
Phần tiêu đề “Countdown”var seconds = 10
while (seconds > 0) { println("$seconds...") Thread.sleep(1000) seconds--}println("🚀 Phóng!")🛠️ Thực hành
Phần tiêu đề “🛠️ Thực hành”Bài tập 1: Đoán số
import kotlin.random.Random
fun main() { val secret = Random.nextInt(1, 101) // 1-100
// TODO: Cho người dùng đoán cho đến khi đúng // Gợi ý: "Lớn hơn" hoặc "Nhỏ hơn"}Lời giải:
import kotlin.random.Random
fun main() { val secret = Random.nextInt(1, 101) var guess: Int? var attempts = 0
println("Đoán số từ 1-100!")
do { print("Nhập số: ") guess = readln().toIntOrNull() attempts++
when { guess == null -> println("Vui lòng nhập số!") guess < secret -> println("Lớn hơn!") guess > secret -> println("Nhỏ hơn!") else -> println("🎉 Chính xác! Bạn đoán $attempts lần") } } while (guess != secret)}Bài tập 2: Tính tổng cho đến khi nhập 0
fun main() { // TODO: Nhập số liên tục và tính tổng // Dừng khi nhập 0}Lời giải:
fun main() { var sum = 0 var input: Int
println("Nhập các số (0 để dừng):")
do { print("> ") input = readln().toIntOrNull() ?: 0 sum += input } while (input != 0)
println("Tổng: $sum")}Bài tập 3: Tìm ước chung lớn nhất (GCD)
fun main() { var a = 48 var b = 18
// TODO: Tìm GCD sử dụng thuật toán Euclid}Lời giải:
fun main() { var a = 48 var b = 18
println("GCD của $a và $b:")
while (b != 0) { val temp = b b = a % b a = temp }
println("GCD = $a") // 6}📱 Trong Android
Phần tiêu đề “📱 Trong Android”// Polling for datavar retries = 0val maxRetries = 3var success = false
while (!success && retries < maxRetries) { try { val data = fetchData() success = true } catch (e: Exception) { retries++ delay(1000 * retries) }}
// Animation loopdo { updateAnimation() Thread.sleep(16) // ~60fps} while (isAnimating)⚠️ Lưu ý quan trọng
Phần tiêu đề “⚠️ Lưu ý quan trọng”✅ Checklist - Tự kiểm tra
Phần tiêu đề “✅ Checklist - Tự kiểm tra”Sau bài học này, bạn có thể:
- Sử dụng
whileloop - Sử dụng
do-whileloop - Phân biệt khi nào dùng
whilevsdo-while - Tránh tạo vòng lặp vô hạn
- Áp dụng cho input validation và game logic
Tiếp theo: Break và Continue