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 booksUse a
for loop with withIndex() to iterate over booksInside the loop, create a string called
bookEntry that combines the index (starting from 1) and the book titleAdd 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