Small Basic – Numbers Triangle


A Triangle of Numbers

This next example has a nested loop where the inner loop’s counter depends on the outer loop. Try out the Listing.

 

Listing: Nesting For loops to draw numbers displayed in a triangle

1 ‘ Triangle.sb

2 ‘ Draws a triangle of numbers

3

4 For R = 1 To 5   ‘ Loops for 5 rows (R)

5   For C = 1 To‘ Loops for R columns (C)

6     TextWindow.Write(C + ” “)  ‘ Writes C, followed by a space

7   EndFor  

8   TextWindow.WriteLine(“”)    ‘ Moves to the next line

9 EndFor

 

The outer loop’s counter, R, runs from 1 to 5 (Line 4). For each iteration of the outer loop, the inner loop (with loop counter C) runs from 1 to the current value of R (Line 5). That’s why, in the first iteration of the outer loop, C runs from 1 to 1 (one iteration). In the second iteration of the outer loop, C runs from 1 to 2 (two iterations), and in the third iteration it runs from 1 to 3 (three iterations), and so on. The inner loop just displays the value of its loop counter and a space after it (Line 6). When the inner loop is finished, the program displays an empty line to move to the next line (Line 8), and the outer loop restarts its next iteration. Here’s the output you get:

1

1 2

1 2 3

1 2 3 4

1 2 3 4 5

   

TRY IT OUT! 

Write a program that displays the multiplication table for number 1 through 5. The output of the program should look like this:

Output:

    1   2   3   4   5

    ——————-

1 | 1   2   3   4   5

2 | 2   4   6   8   10

3 | 3   6   9   12  15

4 | 4   8   12  16  20

5 | 5   10  15  20  25

 

 

Leave a comment if you have any questions!

 

Head to http://blogs.msdn.com/SmallBasic to download it and learn all about it!

   

Small and Basically yours,

   – Ninja Ed & Majed Marji

 

Comments (3)

  1. ThamNT says:

    How do you loop to n line ?

  2. Tham, you replace "R" with the variable "n" instead! =^)

    I'm just kidding. You should head to your programming language's forum and ask there. For Small Basic:

    social.msdn.microsoft.com/…/threads

    Thanks!

  3. Computers Today (part 1 of 6)

    blogs.msdn.com/…/computers-today.aspx

    …..

    CS SPOTLIGHT: Girls in computer programming… why it matters!!!

    blogs.msdn.com/…/cs-spotlight-girls-in-computer-programming-why-it-matters.aspx

    Computational Thinking – Videos & Papers by Jeannette Wing

    blogs.msdn.com/…/computational-thinking-videos-amp-papers-by-jeannette-wing.aspx

Skip to main content