0
0
Kotlinprogramming~15 mins

For loop with index (withIndex) in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Using For Loop with Index in Kotlin
📖 Scenario: You are managing a small bookstore inventory. You want to list all the books with their position numbers to organize the shelves.
🎯 Goal: Build a Kotlin program that uses a for loop with withIndex() to print each book's position and title.
📋 What You'll Learn
Create a list called books with the exact titles: "The Hobbit", "1984", "Pride and Prejudice"
Create a variable called totalBooks to store the number of books
Use a for loop with withIndex() to iterate over books
Inside the loop, create a string called bookEntry that combines the index (starting from 1) and the book title
Add a final line that stores the last bookEntry in a variable called lastEntry
💡 Why This Matters
🌍 Real World
Listing items with their positions is common in inventory management, menus, and reports.
💼 Career
Understanding loops with indexes helps in data processing, UI lists, and database record handling.
Progress0 / 4 steps
1
Create the books list
Create a list called books with these exact titles: "The Hobbit", "1984", and "Pride and Prejudice".
Kotlin
Need a hint?

Use listOf to create the list with the exact book titles.

2
Add totalBooks variable
Create a variable called totalBooks that stores the number of books in the books list.
Kotlin
Need a hint?

Use books.size to get the number of items in the list.

3
Use for loop with withIndex()
Use a for loop with withIndex() to iterate over books. Inside the loop, create a string called bookEntry that combines the index (starting from 1) and the book title separated by a dot and space. For example, "1. The Hobbit".
Kotlin
Need a hint?

Use for ((index, book) in books.withIndex()) and inside the loop create bookEntry with "${index + 1}. $book".

4
Store the last bookEntry
Add a variable called lastEntry outside the loop. Inside the loop, update lastEntry to the current bookEntry. This will keep the last book entry after the loop finishes.
Kotlin
Need a hint?

Declare lastEntry as an empty string before the loop. Inside the loop, assign lastEntry = bookEntry.