Lesson 12

A loop inside a loop

A loop inside a loop

In this lesson: you will use nested loops to draw shapes and build tables.

The whole lesson on one page

A loop inside a loop

In this lesson: you will use nested loops to draw shapes and build tables.

A rectangle of stars

1тағ баландӣ = 3;
2тағ бар = 5;
3барои (тағ қатор = 1; қатор <= баландӣ; қатор++) {
4 тағ хат = "";
5 барои (тағ сутун = 1; сутун <= бар; сутун++) {
6 хат = хат + "*";
7 }
8 чоп(хат);
9}
  • The outer loop makes the rows (қатор). The inner loop makes the symbols of one row.
  • In each row, хат ("line") starts again as an empty string ("").

A staircase

1тағ н = хонданиРақам();
2барои (тағ и = 1; и <= н; и++) {
3 тағ хат = "";
4 барои (тағ ҷ = 1; ҷ <= и; ҷ++) {
5 хат += "#";
6 }
7 чоп(хат);
8}
Input
4

The inner loop runs и times: one symbol in the first row, two in the second, and so on.

Task: Rectangle

Read the height and the width and print a rectangle made of *.

Input: Two numbers: the height, then the width.

Output: The rectangle.

Task: Triangle of digits

Read the number н and print н lines: 1 on the first, 12 on the second, 123 on the third, and so on.

Input: One number: н (from 1 to 9).

Output: н lines.

Task: The full multiplication table

Read the number н and print the н × н multiplication table: line и has the products from и × 1 to и × н, separated by spaces.

Input: One number: н.

Output: н lines.