官术网_书友最值得收藏!

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 our numbers to be inclusive, we use ( ..). If we want to exclude the range, we use until.

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:

.. works on a range in ascending order.

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:

主站蜘蛛池模板: 始兴县| 合川市| 舞阳县| 威远县| 民权县| 鄂托克前旗| 手游| 眉山市| 辛集市| 绵竹市| 长汀县| 武威市| 蒙阴县| 蓝田县| 灯塔市| 大田县| 梓潼县| 永福县| 华阴市| 临猗县| 九江县| 龙山县| 井研县| 龙门县| 安宁市| 贺兰县| 阜宁县| 通辽市| 方山县| 晋州市| 蓬溪县| 安达市| 财经| 临夏县| 莒南县| 武强县| 永济市| 阜康市| 巴塘县| 舒城县| 灵武市|