In this lesson, we will use nested loops to print different shapes of triangles with alphabets and numbers.

Printing triangle with numbers

Challenge 1: Upright Right Triangle

Let’s start with the first triangle in which we are printing numbers in each line according to the line number.

h = 5        h = 7           h = 9
1            1               1
1 2          1 2             1 2
1 2 3        1 2 3           1 2 3
1 2 3 4      1 2 3 4         1 2 3 4
1 2 3 4 5    1 2 3 4 5       1 2 3 4 5
             1 2 3 4 5 6     1 2 3 4 5 6
             1 2 3 4 5 6 7   1 2 3 4 5 6 7
                             1 2 3 4 5 6 7 8
                             1 2 3 4 5 6 7 8 9

Solution

Let’s figure out the pattern first:

Get hands-on with 1200+ tech skills courses.