Bỏ qua để đến nội dung

🔁 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.


  • while: Kiểm tra điều kiện trước khi thực thi
  • do-while: Thực thi ít nhất 1 lần, rồi mới kiểm tra điều kiện

while (condition) {
// code
}
var count = 0
while (count < 5) {
println("Count: $count")
count++
}
// 0, 1, 2, 3, 4

do {
// code (thực thi ít nhất 1 lần)
} while (condition)
var count = 0
do {
println("Count: $count")
count++
} while (count < 5)
// while - không thực thi nếu điều kiện sai từ đầu
var x = 10
while (x < 5) {
println("while: $x") // Không in gì
x++
}
// do-while - luôn thực thi ít nhất 1 lần
var y = 10
do {
println("do-while: $y") // In "do-while: 10"
y++
} while (y < 5)

var input: Int?
do {
print("Nhập số dương: ")
input = readln().toIntOrNull()
} while (input == null || input <= 0)
println("Bạn đã nhập: $input")
var playing = true
var 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
}
}
var seconds = 10
while (seconds > 0) {
println("$seconds...")
Thread.sleep(1000)
seconds--
}
println("🚀 Phóng!")

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$b:")
while (b != 0) {
val temp = b
b = a % b
a = temp
}
println("GCD = $a") // 6
}

// Polling for data
var retries = 0
val maxRetries = 3
var success = false
while (!success && retries < maxRetries) {
try {
val data = fetchData()
success = true
} catch (e: Exception) {
retries++
delay(1000 * retries)
}
}
// Animation loop
do {
updateAnimation()
Thread.sleep(16) // ~60fps
} while (isAnimating)


Sau bài học này, bạn có thể:

  • Sử dụng while loop
  • Sử dụng do-while loop
  • Phân biệt khi nào dùng while vs do-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