Nested Loops and Alignment
This simple program prints 10 multipliers of number 6 in a single line. It then advances to the next line.
This program prints multipliers of numbers 6, 7 and 8. Each multiplier is in its own line.
Why not print the whole multiplication table?
A for loop can be used to repeat the piece of code that prints a single line of multipliers.
Nesting one loop inside another creates a double loop.
A double loop consists of an outer loop and an inner loop.
In this example, the outer for loop repeats 10 times a piece of code that prints out multipliers of number 6.
Can you modify this program so that each row prints multipliers of a different number? The first row should print multipliers of number 1, the second row multipliers of 2 and so on.
Hint: What is the name of the control variable of the outer for loop?
: print j*i," ";
We would also like the output to be aligned so that it looks like a table. Can you add the alignment?
Type int has a getter function for aligning the output. This getter function returns a value of type string. To apply a getter function on an expression, put the expression inside parenthesis.
: print (j*i).pad(3)," ";
This program prints out all possible pairs of numbers 1-9.
The named argument ln of the print statement sets the output line, causing the second print statement to always output at the same place.
This program prints out all possible pairs of numbers 1-9 where the first number of a pair is greater than or equal to the second number.
The only change is the bounding value (j) of the inner for loop.
The type int can be aligned with a getter function .pad.
The type num can be aligned with a getter function .al. The getter function .al accepts two arguments. It returns a value of type string.
The function pow can be used to raise a number to the given power.
The function pow returns a value of type num. Therefore, the result of function pow can be aligned with getter function .al.
The function pow accepts two arguments. In other words, the function pow has two parameters. The first parameter is called the base and the second parameter is called the exponent. Both parameters are of type num.
The output of this program is not perfectly aligned. There are two issues. Correct both of them.
Solution Part 1
print "pow(2,",i.pad(2),") = ";
Solution Part 2
Here is a simple animation with letters involving a nested for loop.
Try modifying text of the logo.
Named arguments ln and ch are used to set the desired line and character position.
This program uses a for loop nested inside a while loop.
To calculate the color of a letter, the program uses the modulo operator %%, explained two chapters before.