- Kotlin for Enterprise Applications using Java EE
- Raghavendra Rao K
- 289字
- 2021-06-10 18:49:20
The for loop
Let's write a for loop to print numbers. Consider the code for 8a_ForLoop.kts:
for(num in 1 .. 5){
println(num)
}
The output is as follows:
.. is used to specify the range, meaning the program prints numbers from 1 to 5 inclusively.
To exclude a range, the until keyword is used. Consider the code for 8b_ForLoop_Until.kts:
for(num in 1 until 5){
println(num)
}
The output is as follows:
If we want to traverse the range in a given step size, we can use step. Consider the code for 8c_ForLoop_Step.kts:
for(num in 1 .. 10 step 2){
println(num)
}
The output is as follows:
If we want to iterate in reverse order, we can use downTo.
Consider the code for 8d_ForLoop_downTo.kts:
for(num in 25 downTo 20){
println(num)
}
This gives us the following output:
If we want to iterate in reverse order in a given step size, we can use downTo and step.
Consider the code for 8e_ForLoop_downTo_Step.kts:
for(num in 25 downTo 15 step 2){
println(num)
}
The output is as follows:
Now, consider the code for 8e1_ForLoop_downTo.kts:
for(num in 25 .. 20){
println(num)
}
The output is as follows:
This code compiles without any errors, but when you run it, there will be no output.
For downTo and step, the value has to be a positive number. If we give a negative number, such as -2, it will produce a compilation error.
Consider the code for 8e2_ForLoop_downTo_Step.kts:
for(num in 25 downTo 15 step -2){
println(num)
}
The output is as follows:
- Java語言程序設計
- 數據庫程序員面試筆試真題與解析
- 我的第一本算法書
- JavaScript+Vue+React全程實例
- Reactive Android Programming
- SharePoint Development with the SharePoint Framework
- Windows Server 2016 Automation with PowerShell Cookbook(Second Edition)
- Learning DHTMLX Suite UI
- Gradle for Android
- MATLAB for Machine Learning
- 劍指大數據:企業級數據倉庫項目實戰(在線教育版)
- Access 2010中文版項目教程
- JavaScript腳本特效編程給力起飛
- Hands-On Neural Network Programming with C#
- 小程序從0到1:微信全棧工程師一本通