Loops and Methods, Five Ways

A quick review of the loops and methods this course uses, in all five languages, with a snack stand as the example: a for loop, a while loop, a for-each loop, and a method that takes values and returns one.

Novice · C# · Java · Python · JavaScript · TypeScript · Updated

By

After this lesson you can

  • Read and write for, while and for-each loops in your language
  • Write a method that takes parameters and returns a value

Key takeaways

  • A for loop repeats a set number of times, a while loop repeats until something changes, and a for-each loop visits every item in a collection.
  • A method is a named block of code. It takes values (its parameters) and can hand one back (its return value).
  • The five languages write these the same way underneath; only the punctuation changes.

This chapter reviews the code the rest of the course uses, and nothing more. If loops and methods are already second nature in your language, skim this lesson, try its chapter check, and move on. If they feel new, take your time: every data structure in this course is built from these few pieces. (If this chapter is your first meeting with them, a course that starts from zero, such as C# Fundamentals or Python, teaches them more slowly.)

The running example is a small snack stand that sells pretzels, granola bars, trail mix and apple chips.

Three loops for three jobs

A loop repeats a block of code. There are three kinds, each for a different job:

Loop Use it when Everyday version
for You know how many times to repeat "Do ten push-ups"
while You repeat until something changes "Stir until it thickens"
for-each You want to visit every item in a collection "Greet everyone in line"

A method: a recipe with a name

A method is a named block of code you can run whenever you need it, like a recipe card. The values you hand it are its parameters (the ingredients), and the value it hands back is its return value (the dish). Python, JavaScript and TypeScript usually say function; C# and Java say method. It's the same idea.

All four, at the snack stand

The program below uses each one: a for loop counts down to opening time, a for-each loop builds the menu from the list of snacks, a while loop works out how many days the trail mix lasts if 2 bags sell a day, and a method adds up the snacks in stock.

int TotalInStock(List<int> counts)
{
    int total = 0;
    foreach (int count in counts)
    {
        total += count;
    }
    return total;
}

List<string> snacks = new List<string> { "Pretzel", "Granola Bar", "Trail Mix", "Apple Chips" };
List<int> counts = new List<int> { 12, 20, 8, 15 };

string countdown = "";
for (int minute = 3; minute >= 1; minute--)
{
    countdown += minute + " ";
}
Console.WriteLine("Opening in: " + countdown.Trim());

string menu = "";
foreach (string snack in snacks)
{
    menu += snack + ", ";
}
Console.WriteLine("Menu: " + menu.TrimEnd(',', ' '));

int trailMix = 8;
int days = 0;
while (trailMix > 0)
{
    trailMix -= 2;
    days++;
}
Console.WriteLine("Days the trail mix lasts: " + days);

Console.WriteLine("Snacks in stock: " + TotalInStock(counts));
Opening in: 3 2 1
Menu: Pretzel, Granola Bar, Trail Mix, Apple Chips
Days the trail mix lasts: 4
Snacks in stock: 55
int totalInStock(List<Integer> counts) {
    int total = 0;
    for (int count : counts) {
        total += count;
    }
    return total;
}

void main() {
    List<String> snacks = List.of("Pretzel", "Granola Bar", "Trail Mix", "Apple Chips");
    List<Integer> counts = List.of(12, 20, 8, 15);

    String countdown = "";
    for (int minute = 3; minute >= 1; minute--) {
        countdown += minute + " ";
    }
    IO.println("Opening in: " + countdown.trim());

    String menu = "";
    for (String snack : snacks) {
        menu += snack + ", ";
    }
    IO.println("Menu: " + menu.substring(0, menu.length() - 2));

    int trailMix = 8;
    int days = 0;
    while (trailMix > 0) {
        trailMix -= 2;
        days++;
    }
    IO.println("Days the trail mix lasts: " + days);

    IO.println("Snacks in stock: " + totalInStock(counts));
}
Opening in: 3 2 1
Menu: Pretzel, Granola Bar, Trail Mix, Apple Chips
Days the trail mix lasts: 4
Snacks in stock: 55
def total_in_stock(counts):
    total = 0
    for count in counts:
        total += count
    return total


snacks = ["Pretzel", "Granola Bar", "Trail Mix", "Apple Chips"]
counts = [12, 20, 8, 15]

countdown = ""
for minute in range(3, 0, -1):
    countdown += f"{minute} "
print("Opening in: " + countdown.strip())

menu = ""
for snack in snacks:
    menu += snack + ", "
print("Menu: " + menu[:-2])

trail_mix = 8
days = 0
while trail_mix > 0:
    trail_mix -= 2
    days += 1
print(f"Days the trail mix lasts: {days}")

print(f"Snacks in stock: {total_in_stock(counts)}")
Opening in: 3 2 1
Menu: Pretzel, Granola Bar, Trail Mix, Apple Chips
Days the trail mix lasts: 4
Snacks in stock: 55
function totalInStock(counts) {
  let total = 0;
  for (const count of counts) {
    total += count;
  }
  return total;
}

const snacks = ["Pretzel", "Granola Bar", "Trail Mix", "Apple Chips"];
const counts = [12, 20, 8, 15];

let countdown = "";
for (let minute = 3; minute >= 1; minute--) {
  countdown += minute + " ";
}
console.log("Opening in: " + countdown.trim());

let menu = "";
for (const snack of snacks) {
  menu += snack + ", ";
}
console.log("Menu: " + menu.slice(0, -2));

let trailMix = 8;
let days = 0;
while (trailMix > 0) {
  trailMix -= 2;
  days++;
}
console.log(`Days the trail mix lasts: ${days}`);

console.log(`Snacks in stock: ${totalInStock(counts)}`);
Opening in: 3 2 1
Menu: Pretzel, Granola Bar, Trail Mix, Apple Chips
Days the trail mix lasts: 4
Snacks in stock: 55
function totalInStock(counts: number[]): number {
  let total = 0;
  for (const count of counts) {
    total += count;
  }
  return total;
}

const snacks: string[] = ["Pretzel", "Granola Bar", "Trail Mix", "Apple Chips"];
const counts: number[] = [12, 20, 8, 15];

let countdown = "";
for (let minute = 3; minute >= 1; minute--) {
  countdown += minute + " ";
}
console.log("Opening in: " + countdown.trim());

let menu = "";
for (const snack of snacks) {
  menu += snack + ", ";
}
console.log("Menu: " + menu.slice(0, -2));

let trailMix = 8;
let days = 0;
while (trailMix > 0) {
  trailMix -= 2;
  days++;
}
console.log(`Days the trail mix lasts: ${days}`);

console.log(`Snacks in stock: ${totalInStock(counts)}`);
Opening in: 3 2 1
Menu: Pretzel, Granola Bar, Trail Mix, Apple Chips
Days the trail mix lasts: 4
Snacks in stock: 55

Reading the method

Look at the first lines of the code, the method that adds up the stock:

  • Its name says what it does: TotalInStock (C#), totalInStock (Java, JavaScript, TypeScript), total_in_stock (Python). Each language has its own naming style; the course follows each one's.
  • Its parameter, counts, is the list it's handed. In C#, Java and TypeScript, the parameter also says its type (List<int>, List<Integer>, number[]); Python and JavaScript leave the type out.
  • Its return value is total. C#, Java and TypeScript say the type of the return value too: int or number.
  • Calling it, TotalInStock(counts), runs the recipe and puts the answer right where the call was.

Inside it is a for-each loop. Most methods in this course look like this one: a loop that walks through some data, and a value handed back at the end.

Try it. Change the while loop to sell 3 bags a day instead of 2. How many days does the trail mix last now, and why isn't it 8 ÷ 3?

Do it: add up the snack stand's day, in Python

At closing time, the snack stand wants to know how much money came in today.

It keeps two lists, in the same order:

  • prices: the price of each snack.
  • sold: how many of each snack were sold today.

For example, with three snacks:

prices = [2.50, 3.00, 1.25]
sold = [3, 1, 12]
Snack Price Sold Money in
1st $2.50 3 3 × $2.50 = $7.50
2nd $3.00 1 1 × $3.00 = $3.00
3rd $1.25 12 12 × $1.25 = $15.00
The day $25.50

So for these lists, day_total(prices, sold) returns 25.5.

Your job: write the method day_total(prices, sold) so it returns the money that came in today, for any two lists like these.

  • Multiply each snack's price by how many were sold, then add them all up.
  • If nothing was sold, or the lists are empty, return 0.

This one is in Python; the same loop and method work in every language in this course.

Practiced live on the lesson page: write the Python right there and check it.

Check yourself

2 questions to try on the lesson page.

So what

Loops and methods are the two tools every data structure in this course is built with: a loop to walk through the items, and a method for each job the structure does. You'll write dozens of both, starting with the exercise at the end of this chapter.

Key terms

Cheat sheets