1. Array traversal is a key skill
If an array is a box with identical parts, then traversing an array is when you open the box and honestly count what’s inside: how many parts there are, which one is the largest, whether there are defective ones, and how much they cost in total. Almost all basic array tasks boil down to one thing: iterate over the elements and carefully sum something up or check something.
In Kotlin, the for loop can iterate over array elements directly: for (x in a) { ... } is a normal and expected style. But sometimes we need not only the element, but also its position (index). Then we iterate over indices: for (i in a.indices) { ... }.
Two traversal styles: by elements and by indices
From the outside, both styles look almost the same, but they answer different questions. Traversal “by elements” reads like “take each element of the array and do something with it.” This is convenient for sum, counting, condition checks, and output. Traversal “by indices” reads like “iterate over array positions,” and it’s needed when it’s important to remember where exactly something is located: the index of the maximum, the position of a found value, replacing elements in place.
Let’s start with the simplest thing: create an array of steps for a week and just print it to visually see the data (a programmer without console output is like a cook without a spoon).
fun main() {
val steps: IntArray = intArrayOf(4200, 5600, 3100, 8000, 7600, 9000, 1200)
for (x in steps) {
print("$x ")
}
println() // 4200 5600 3100 8000 7600 9000 1200
}
Notice: right now we are iterating by values (x in steps). We don’t see indices; x sequentially takes all values of the array (one at a time).
2. Pattern #1: sum
Sum is the most popular algorithm in the world of beginner programmers, because it’s the first case where you realize: a loop is not “print println seven times,” but “do something important seven times.” We create a special variable (usually sum), give it a starting value (usually 0), and on each step add the next array element.
Logically, it looks like a small flowchart: initialize the sum, go through all elements, update the sum, get the result. In real development, such diagrams are useful when your brain tries to skip some steps and accidentally forgets initialization or updating.
flowchart TD
A[sum = 0] --> B{is there a next element?}
B -->|yes| C[sum = sum + x]
C --> B
B -->|no| D[print sum]
Now let’s implement this as a small project StepStats.
fun main() {
val steps = intArrayOf(4200, 5600, 3100, 8000, 7600, 9000, 1200)
var sum = 0
for (x in steps) {
sum = sum + x
}
println("Total steps = $sum") // Total steps = 38500
}
An important nuance: sum is a var, because we change it. If you try to write val sum = 0, the compiler will stop you (and it will be right).
3. Average: sum and careful division
The average value is almost always built on the sum. First we compute the sum, then we divide by the number of elements. And here Kotlin, as a good programming language, reminds you: dividing Int / Int yields an Int, meaning the fractional part is discarded. This is not a bug; it’s the harsh math of integers.
So, if you want the average as a number with a fraction, you need to “convert” at least one part of the expression to Double. The simplest approach: sum.toDouble().
fun main() {
val steps = intArrayOf(4200, 5600, 3100, 8000, 7600, 9000, 1200)
var sum = 0
for (x in steps) sum = sum + x
val avg = sum.toDouble() / steps.size
println("Average steps = $avg") // Average steps = 5500.0
}
Notice: steps.size is the number of elements. If the array has 7 days, it will be 7.
And yes, we got 5500.0, even though “nicely” it could have been 5500. This is normal: Double is always shown as a number with a decimal point.
4. Pattern #2: conditional counting
Conditional counting is very similar to simple summation, except instead of “add the element’s value,” we “add 1 if the condition is true.” This pattern appears everywhere: how many days were above normal, how many grades are A’s, how many elements are zero, how many characters are letters.
Let’s make a task in StepStats: count how many days had at least 7000 steps (our goal).
fun main() {
val steps = intArrayOf(4200, 5600, 3100, 8000, 7600, 9000, 1200)
var goodDays = 0
for (x in steps) {
if (x >= 7000)
goodDays = goodDays + 1
}
println("Good days = $goodDays") // Good days = 3
}
Here we again use traversal by elements, because we care about the fact (the value), not the position.
Now let’s make a slightly more realistic variant: the user enters some value (a threshold), and we count how many days are above the threshold.
fun main() {
val steps = intArrayOf(4200, 5600, 3100, 8000, 7600, 9000, 1200)
print("Enter threshold: ")
val threshold = readln().toInt()
var count = 0
for (x in steps)
if (x >= threshold) count++
println("Days >= $threshold : $count")
}
Notice: count++ is a short form of “increase by 1.” Very convenient, especially for counters.
5. Pattern #3: search and index
Searching is when we want to find out: “is there a value X in the array?” or “at which position is the first value X?” Here we almost always need indices, because finding the value is often not enough—it’s also important to know where it is.
And if we found nothing, we return -1. Why -1? Because that value definitely cannot be a valid array index (valid ones start at 0).
One more important detail: if we are searching for the first match, then after we find it we can stop using break.
Let’s start by searching for a value in the steps array: let’s see whether there was a day with exactly 9000 steps, and if so—what its index is.
fun main() {
val steps = intArrayOf(4200, 5600, 3100, 8000, 7600, 9000, 1200)
val target = 9000
var index = -1
for (i in steps.indices) {
if (steps[i] == target)
{ index = i; break }
}
println("Index of $target = $index") // Index of 9000 = 5
}
This is exactly the right time to use steps.indices—the range of the array indices. It helps you avoid thinking about “last index = size - 1”.
Let’s do one more practical example. For instance, find the first day when the number of steps was below some minimum (e.g., less than 3000).
fun main() {
val steps = intArrayOf(4200, 5600, 3100, 8000, 7600, 9000, 1200)
var badIndex = -1
for (i in steps.indices) {
if (steps[i] < 3000)
{ badIndex = i; break }
}
println("First day with < 3000 steps: $badIndex") // First day with < 3000 steps: 6
}
If you want, you can add the text “not found” (when badIndex == -1), but for now the pattern itself is what matters.
6. Pattern #4: maximum
Maximum is also a very interesting pattern. Beginners often get trapped by: “let’s set max to zero.” Sometimes it works, and sometimes it doesn’t.
Let’s find the maximum value in the array.
fun main() {
val steps = intArrayOf(4200, 5600, 3100, 8000, 7600, 9000, 1200)
var max = 0
for (x in steps) {
if (x > max)
max = x
}
println("Max steps = $max") // Max steps = 9000
}
Everything works. And it works correctly. But there is a logical error here.
If the array contains negative numbers, then max = 0 breaks the entire logic: you’ll get a maximum of 0 even if it isn’t in the array. The universal rule is: if you are looking for a maximum, you need to start from the first array element.
Here is the correct way to search for the maximum number of steps.
fun main() {
val steps = intArrayOf(4200, 5600, 3100, 8000, 7600, 9000, 1200)
var max = steps[0] // max equals the first value of the array
for (x in steps) {
if (x > max)
max = x
}
println("Max steps = $max") // Max steps = 9000
}
This leads to an important conclusion: to access a[0], the array must be non-empty: size > 0. So either we know in advance that the array is not empty, or we must write a check if (a.size == 0).
Now let’s try to find not only the maximum, but also the day when the user set a record. Here we need indices again.
fun main() {
val steps = intArrayOf(4200, 5600, 3100, 8000, 7600, 9000, 1200)
var maxIndex = 0 // index of the starting value
var max = steps[maxIndex] // starting value for `max`
for (i in steps.indices) {
if (steps[i] > max)
{ max = steps[i]; maxIndex = i }
}
println("Max = $max at index $maxIndex") // Max = 9000 at index 5
}
Pay attention to the style: we update both the value and the index together. If you update only one, you’ll get “the maximum from one day, but the index from another”—that’s not allowed.
7. Adding business logic
Now let’s do the most pleasant part: take the patterns we already know and assemble a small “weekly report.” It’s important not to try to do “everything in one loop” at any cost: for a beginner, it’s easier to read two or three clear loops than one monster loop.
Let’s do this: compute the sum, average, maximum, and the number of days above 7000, and print it nicely.
fun main() {
val steps = intArrayOf(4200, 5600, 3100, 8000, 7600, 9000, 1200)
var sum = 0
var goodDays = 0
var max = steps[0]
for (x in steps) {
sum += x
if (x >= 7000) goodDays++
if (x > max) max = x
}
val avg = sum.toDouble() / steps.size
println("Total = $sum, avg = $avg, max = $max, goodDays = $goodDays")
// Total = 38500, avg = 5500.0, max = 9000, goodDays = 3
}
Below is a small table to lock in how the patterns are similar and how they differ:
| Pattern | What the result variable stores | Starting value | What happens in the loop |
|---|---|---|---|
| Sum | sum of elements (sum) | 0 | sum += x |
| Counting | count (count) | 0 | if (cond) count++ |
| Search | index (index) | -1 | on match index = i and often break |
| Maximum | maximum value (max) | a[0] (only if the array is not empty) | if (x > max) max = x |
Empty array: there is always a catch
An empty array is a situation where size == 0. Sometimes it appears intentionally (for example, “no data”), and sometimes accidentally (for example, you created IntArray(n), but n turned out to be 0).
With an empty array, almost all patterns work fine—except those where you access a[0] (maximum, minimum, sometimes an initial value for something else).
So the rule is simple: if your algorithm requires accessing the first element, then before that there must be a check that the array is not empty.
Here is a safe template for finding the maximum:
fun main() {
val steps = intArrayOf() // empty
if (steps.size == 0) {
println("No data") // No data
} else {
var max = steps[0]
for (x in steps) if (x > max) max = x
println("Max = $max")
}
}
This example doesn’t do anything clever; it just honestly handles the case when there is no data.
8. Typical mistakes when traversing arrays
Mistake #1: compute the average as sum / size and be surprised why it has no fractional part.
If sum and size are Int, then the result will also be Int. Therefore, when computing the average you need to convert the sum (or the size) to Double, for example sum.toDouble() / size.
Mistake #2: start the maximum with 0 “because it’s easier.”
Sometimes it accidentally works (if all numbers are non-negative), but as soon as negative values appear, the logic falls apart. The correct starting point for the maximum is the first array element a[0], but only in the branch where the array is definitely non-empty.
Mistake #3: forget about break in a search and get “the last found index” instead of “the first.”
The most common variant: the search is written, but break is not used. As a result, the loop continues and the index gets overwritten again and again.
Mistake #4: mix up traversal by elements and by indices, and then not understand why you “can’t get the position.”
for (x in a) does not give you an index—only the value. If you want an index, use for (i in a.indices) and access the value as a[i].
Mistake #5: use incorrect index boundaries and accidentally go out of the array.
Classic: write for (i in 0..a.size) and get an out-of-bounds on the last step. The most reliable option is a.indices, because it is exactly “about valid indices.”
Mistake #6: not initialize the accumulator variable, or initialize it “to the wrong thing.”
For sum, the start must be 0. For counting, also 0. For search, it’s convenient to start the index at -1. If you mix up the starting values, the algorithm will produce strange results—sometimes even “almost correct,” which is especially insidious.
Mistake #7: try to solve the task “in one line” and lose readability.
Beginners sometimes do search, sum, maximum, and printing in one giant construct, and then they themselves can’t explain what is happening. At this stage, it’s more important that the code reads linearly: initialization → loop → updates → result.
GO TO FULL VERSION