Lab Exercise: Understanding the Correct For-Loop Syntax for Iterating over a range of numbers in Kotlin
In Kotlin, for-loops are versatile and designed to simplify iteration over
ranges of numbers,
collections, or
arrays.
One common requirement in programming is to iterate over a range of numbers, either counting up or down, and applying a step (increment or decrement) to control how the loop progresses.
Kotlin has built-in constructs to handle these requirements elegantly.
It is important to understand the correct syntax.
Key Kotlin For-Loop Concepts:
1. **Basic Range Iteration (Counting Up)
- To iterate over a range of numbers in ascending order, we use `..` (the range operator).
- Example:
```kotlin
for (i in 1..5) {
println(i)
}
```
- **Output**: `1, 2, 3, 4, 5`
- The loop starts at 1 and ends at 5 (inclusive).
2. **Counting Down Using `downTo`
- When you want to count down (decreasing numbers), you use the `downTo` keyword.
- Example:
```kotlin
for (i in 5 downTo 1) {
println(i)
}
```
- **Output**: `5, 4, 3, 2, 1`
- The loop starts at 5 and counts down to 1 (inclusive).
3. Stepping Through a Range (Using `step`)
- By default, Kotlin loops increment (or decrement) by 1, but you can customize the step size using the `step` keyword.
- Example (Counting up with a step):
```kotlin
for (i in 1..10 step 2) {
println(i)
}
```
- **Output**: `1, 3, 5, 7, 9`
- The loop starts at 1, skips by 2, and continues until it reaches or exceeds 10.
- Example (Counting down with a step):
```kotlin
for (i in 10 downTo 1 step 3) {
println(i)
}
```
- **Output**: `10, 7, 4, 1`
- The loop starts at 10 and decreases by 3 each time until it reaches 1.
**Understanding the Given Options**:
Let’s now analyze the options provided in the multiple-choice question and understand why the correct answer is `C) for (i in 20 downTo 0 step 5)`.
---
#### **Option A: `for (i in 0 to 20 step 5)`**
- **Explanation**:
This option is **incorrect**.
- `to` is not used in loops like this in Kotlin; instead, we use the range operator `..`.
- The syntax `0 to 20` is not valid in this context, as it doesn't define a range properly. If you want to count from 0 to 20, the correct syntax would be `0..20`.
- Additionally, you typically use `step` in combination with a properly defined range or `downTo` for counting down.
---
#### **Option B: `for (i in 20 to 0 step 5)`**
- **Explanation**:
This option is **incorrect**.
- Similar to option A, `to` cannot be used to define a range in a for-loop.
- Additionally, this loop attempts to count **down** from 20 to 0, but `to` does not support descending ranges. Instead, you must use `downTo` for descending ranges.
---
#### **Option C: `for (i in 20 downTo 0 step 5)`**
- **Explanation**:
This option is **correct**.
- `downTo` is the correct keyword to use when you want to count down from a higher number to a lower number.
- `step 5` correctly specifies that the loop should decrement by 5 each time.
- This loop will count from 20 down to 0, stepping by 5, and the values of `i` will be: `20, 15, 10, 5, 0`.
**Example**:
```kotlin
for (i in 20 downTo 0 step 5) {
println(i)
}
```
**Output**:
```plaintext
20
15
10
5
0
```
---
#### **Option D: `for (i in 0 downTo 20 step 5)`**
- **Explanation**:
This option is **incorrect**.
- `downTo` is used to count **down**, so it cannot be used with a range where you are starting at a lower number (`0`) and trying to go up to a higher number (`20`).
- To count **up** from 0 to 20, you should use the `..` operator (i.e., `0..20`), not `downTo`.
---
### **Important Takeaways**:
1. **Use `..` for Counting Up**:
- `for (i in 1..10)` counts from 1 to 10 (inclusive).
2. **Use `downTo` for Counting Down**:
- `for (i in 10 downTo 1)` counts from 10 down to 1 (inclusive).
3. **Use `step` for Custom Increments/Decrements**:
- By default, loops increment or decrement by 1. Use `step` to define a custom step size.
- You can combine `step` with both `..` and `downTo` for ascending and descending loops, respectively.
---
### **Example Exercise:**
Here’s a practical exercise to help solidify the concept:
```kotlin
fun main() {
// Loop 1: Count up from 1 to 10, stepping by 2
for (i in 1..10 step 2) {
println(i) // Output: 1, 3, 5, 7, 9
}
// Loop 2: Count down from 15 to 0, stepping by 3
for (i in 15 downTo 0 step 3) {
println(i) // Output: 15, 12, 9, 6, 3, 0
}
}
```
### **Conclusion**:
- The correct syntax for counting **down** from 20 to 0 in steps of 5 is:
`for (i in 20 downTo 0 step 5)`.
- Make sure to use `..` for counting up and `downTo` for counting down in Kotlin for-loops. Combine them with `step` when you want to adjust the increment/decrement value.
By mastering this syntax, you'll be able to write efficient and concise loops in Kotlin, making your code both elegant and readable!
Let me know if there are any more questions or if your students need further clarification! 😊
Want to print your doc? This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (