Nested Loops and Alignment [10/10]
Nested Loops and Alignment
This simple program prints 10 multiples of number 6 in a single line. It then advances to the next line.
This program prints multiples of numbers 6, 7 and 8. Each multiple 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 multiples.
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 multiples of number 6.
Can you modify this program so that each row prints multiples of a different number? The first row should print multiples of number 1, the second row multiples of 2 and so on.
Hint: What is the name of the control variable of the outer for loop?
Solution (click):
: print j*i," ";
We would also like the output to be aligned so that it looks like a table. Can you add the alignment?
Hint:
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.
Solution:
: 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.
Exercise:
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
print pow(2,i).al(7,0);
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.
Examine the given program in detail.
This program uses a for loop nested inside a while loop.
To calculate colors of letters, the program uses the modulo operator %%, explained two chapters before in the chapter named The Type int.
<< F2:Prev - - F4:Next >>