Visualize the Right Triangle star pattern step by step. Watch nested loops place each star row by row, making loop logic crystal-clear for beginners.
About this algorithm
The right triangle is the first star pattern most people write: the first row has one star, the second has two, and so on until the last row is n stars wide, all lined up against the left edge. It teaches the one idea every other pattern builds on, which is that the inner loop can depend on the outer loop variable.
Start here if nested loops are new to you. The rule has a single moving part (how many stars) and no spaces in front, so you can watch the outer loop pick a row and the inner loop fill it. The inverted triangle is the same shape upside down and is the natural next page. Move on to the pyramid once you are happy here, because the pyramid adds leading spaces and centres the shape, and that is a second rule to juggle.
Let i run from 0 to n - 1. Each value of i is one printed line, so n rows in total.
Let j run across the columns of that row. On this page j goes all the way from 0 to n - 1 so you can see every cell, stars and blanks alike.
Row i should hold i + 1 stars, which are the columns 0, 1, ... i. So the test is j <= i. Columns past i get a space. The stars therefore stop on the diagonal where the column number equals the row number.
After the inner loop finishes, print a newline so the next row starts underneath.
The page loads n = 5, so the grid is 5 by 5. Row 0: only j = 0 passes j <= 0, giving *. Row 1: j = 0 and 1 pass, giving **. Row 2 gives ***, row 3 gives ****, and row 4 gives *****, with every column passing. Count them: 1 + 2 + 3 + 4 + 5 = 15 stars, and the other 10 cells are spaces, for 25 cells visited in all. In general the stars add up to n(n + 1) / 2, so at n = 8 (the top of the slider) you get 36 stars in a 64 cell grid.
Most textbooks write the inner loop as for j in 0..i and print only the stars, so the spaces to the right are never printed at all. The output looks the same. This page visits the empty cells too, which makes the j <= i boundary visible as the line where stars turn into blanks.
Writing j < i instead of j <= i. Row 0 then prints nothing and the triangle ends one star short on every row.
Time: the page checks every cell of an n by n grid, and even the textbook loop prints n(n + 1) / 2 stars, which still grows with n². Space: printing needs only the two counters i and j; the page keeps the grid only so it can draw it.