CodeBlanks Logo Icon CodeBlanks

Summary - Loops

JavaScript course · Beginner · Lesson 41/133

Print a multiplication table using for and while loops.

Summary - Loops

In this group you learned four loop types: for, while, do...while and nested loops. You also learned to exit with break and skip steps with continue.

for (let i = 1; i <= 3; i++) {
  console.log(i);
}

Now let's combine them in one task: a multiplication table with for, and a sum with while. You'll build a real piece of a program using what you've learned.

Exercise A 5x5 multiplication table

Use nested for loops to print a 5x5 multiplication table. The outer loop walks i, the inner loop walks j, both from 1 to 5. In each cell add i * j to a row variable separated by a space, and print each row with console.log(row).

Show example solution
for (let i = 1; i <= 5; i++) {
  let row = "";
  for (let j = 1; j <= 5; j++) {
    row += (i * j) + " ";
  }
  console.log(row);
}

Exercise Sum from 1 to 100

Use a while loop to compute the sum of numbers from 1 to 100. Accumulate it in a total variable. Keep the counter as n, add it to total each step, and increment n. Finally print it with console.log(total).

Show example solution
let total = 0;
let n = 1;
while (n <= 100) {
  total += n;
  n++;
}
console.log(total);

Test yourself

  1. Which loop is best for 10 repeats with a known count?

    • for loop
    • while loop
    • do...while loop
    • nested loop
    Show answer

    for loop — The for loop is ideal for known counts, since init, condition and increment fit on one line.

  2. Match the loop type to its use case

    for
    loop with known count
    while
    loop with unknown condition
    do...while
    run first, then test

All lessons in Beginner