4.16 Exercise: Stars

This is a classic exercise for beginner programmers. Write a function showStars(rows) that prints a triangle of stars: in the first row one star, in the second two stars, and so on until rows rows have been printed. showStars(5) produces five rows; showStars(1) produces a single star. Pause the video, try it, then read the correction.

Solution with two nested loops

function showStars(rows) {
  for (let row = 1; row <= rows; row++) {
    let pattern = '';
    for (let i = 0; i < row; i++) {
      pattern += '*';
    }
    console.log(pattern);
  }
}

showStars(5);
// *
// **
// ***
// ****
// *****
  • The outer loop walks through each row from 1 to rows.
  • For each row, we build a pattern string in an inner loop that runs row times.
  • Each iteration appends one * to pattern with +=.
  • When the inner loop ends, we log the row.

What you see here is a nested loop: a loop inside another loop. This pattern shows up everywhere — in matrix traversal, table rendering, combinatorics — so it's worth being comfortable with it.

Summary

This lesson covers a classic beginner programming exercise: building a function that displays asterisks in an increasing triangle pattern. The solution uses nested loops—an outer loop to iterate through each line and an inner loop to add the correct number of stars for each line.

Key points

  • Use an outer loop to iterate through each line number (1 to n)
  • Declare an empty string variable to build the pattern for each line
  • Use an inner loop that executes as many times as the current line number
  • Concatenate asterisks to the pattern string in the inner loop
  • Print the completed pattern after the inner loop finishes
  • This demonstrates the nested loops pattern—a fundamental programming concept with widespread applications

FAQ

Why do we need two loops for this exercise?

The outer loop controls which line we're creating, while the inner loop builds the star pattern for that specific line. The inner loop repeats a different number of times based on the line number.

How many times does the inner loop execute when we pass 5 as the parameter?

The inner loop runs 1 time on line 1, 2 times on line 2, 3 times on line 3, 4 times on line 4, and 5 times on line 5—matching the current line number.

What is a nested loop and where is it used?

A nested loop is a loop inside another loop. It's commonly used for creating patterns (like this star triangle), processing multi-dimensional arrays, and comparing elements in lists.