Ranges क्या हैं
In this page:
val range = start..end // inclusive
for (i in start until end) { } // excludes end
for (i in start downTo end) { } // descending
for (i in start..end step 2) { }
Inclusive Ranges with ..
.. operator एक range बनाता है जो अपने start और end values दोनों को शामिल करता है, जो आमतौर पर सीधे for loops या in checks के अंदर उपयोग होता है।
उदाहरण: Inclusive Ranges with ..
// Entry point: execution of the program starts here
fun main() {
// Declare a read-only variable `range`, set to `1..5`
val range = 1..5
// Loop over `range`, binding each item to `n`
for (n in range) {
// Print "Value: $n" to the console, with a trailing newline
println("Value: $n")
}
}
Login to try C/C++/Java/PHP code in the editor
Excluding the End with until
until एक range बनाता है जो अपनी upper bound को बाहर रखता है, जो zero से शुरू करके ठीक n बार loop करने का idiomatic तरीका है।
उदाहरण: Excluding the End with until
// Entry point: execution of the program starts here
fun main() {
// Loop over `0 until 5`, binding each item to `i`
for (i in 0 until 5) {
// Print "Index: $i" to the console, with a trailing newline
println("Index: $i")
}
}
Login to try C/C++/Java/PHP code in the editor
Counting Down with downTo
downTo एक descending range बनाता है, किसी for loop को एक बड़े number से एक छोटे number तक पीछे की ओर गिनने देते हुए।
उदाहरण: Counting Down with downTo
// Entry point: execution of the program starts here
fun main() {
// Loop over `5 downTo 1`, binding each item to `i`
for (i in 5 downTo 1) {
// Print "Countdown: $i" to the console, with a trailing newline
println("Countdown: $i")
}
// Print "Liftoff!" to the console, with a trailing newline
println("Liftoff!")
}
Login to try C/C++/Java/PHP code in the editor
Custom Increments with step
किसी range पर .step(n) chain करना बदल देता है कि हर iteration में value कितनी बढ़े (या घटे), आपको values को skip करने देते हुए।
उदाहरण: Custom Increments with step
// Entry point: execution of the program starts here
fun main() {
// Loop over `0..10 step 2`, binding each item to `i`
for (i in 0..10 step 2) {
// Print "Even step: $i" to the console, with a trailing newline
println("Even step: $i")
}
}
Login to try C/C++/Java/PHP code in the editor
..उपयोग करना जब upper bound को exclude करना चाहिए, off-by-one errors आम हैं;until(या..<) end value को exclude करता है।- पीछे की ओर गिनने के लिए
downToभूल जाना; एक साधारण..range हमेशा बढ़ते order में जाता है। - जब non-1 increment चाहिए तब
stepfunction को नज़रअंदाज़ करना, और इसके बजाय loop body के अंदर manually values skip करना।
a..baसेbतक एक inclusive range बनाता है।a until b(याa..<b) एक ऐसा range बनाता है जो upper boundbको exclude करता है।a downTo baसेbतक एक descending range बनाता है।.step(n)किसी भी range का increment बदल देता है, आपको values skip करने देते हुए।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: