Building on Your Loop Skills

You have already learned how to use different types of loops in Lua, including numeric for loops, generic for loops, while loops, and even nested loops. These tools allow you to repeat actions and work with lists or tables of data. Now, let's take your skills further by using loops to solve simple, real-world problems — just like a professional programmer would.

What You'll Learn

In this lesson, you will practice using loops to build small algorithms that process and analyze data. For example, imagine you have a list of countries you plan to visit and a table with the cost for each country. You will learn how to use a loop to calculate the total cost of your trip and find the average cost per country.

Here is a sample code snippet to show what you will be able to do:

Let's break down what the code does:

  • country_costs is a table that stores the cost to visit each country.
  • chosen_countries is a list of the countries you want to visit.
  • total_trip_cost starts at 0. The for loop goes through each country in chosen_countries and adds its cost (from the country_costs table) to total_trip_cost.
  • After the loop, average_cost_per_country is calculated by dividing the total cost by the number of countries in your list.
  • The results are printed: the total cost of the trip and the average cost per country.

This example shows how loops can help you process lists and tables, perform calculations, and generate useful results from your data.

Why This Matters

Being able to use loops to build simple algorithms is a key skill for any programmer. It allows you to automate calculations, analyze data, and solve everyday problems efficiently. Whether you are planning a trip, managing a budget, or working with any kind of list, these techniques will help you write code that is both powerful and practical.

Ready to put your loop knowledge into action? Let’s move on to the practice section and see what you can create!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal