A loop inside a loop draws a shape. The outer loop goes through the rows, and the inner loop writes the stars of one row.
What to build
Read a digit n and print a triangle of stars with n rows: one star in the first row, two in the second, and so on.
Requirements
- Row
ihasistars. - End every row with a new line, the last row too.
- Print nothing but stars and new lines.
Input
One digit n from 1 to 9, then Enter.
Output
n lines of stars.
Constraints
1 ≤ n ≤ 9.
Example
Input:
3
Output:
*
**
***
Why it works
Because LOOP uses CX for both counts, the outer count has to wait on the stack while the inner loop runs. The inner count is copied from BX, the row number, so each row has one more star than the one before it.
Examples
3
* ** ***
1
*
Hints
Hint 1
The outer loop counts the rows (CX = n), the inner loop counts the stars of a row, which is the row number.
Hint 2
Both loops count with CX: save the outer count with PUSH CX before the inner loop and restore it with POP CX after it.
Hint 3
At the end of every row, print 0Dh and 0Ah. Keep the row number in BX and add 1 to it after each row.
Solution
Show one correct solution (try it yourself first)
; A triangle of stars
.MODEL SMALL
.STACK 100H
.CODE
MAIN PROC
MOV AH, 1
INT 21H
SUB AL, '0'
MOV CL, AL
MOV CH, 0 ; CX = rows
MOV BX, 1 ; stars in this row
ROW:
PUSH CX ; save the row count
MOV CX, BX ; the inner loop counts stars
STAR:
MOV DL, '*'
MOV AH, 2
INT 21H
LOOP STAR
MOV DL, 0DH
INT 21H
MOV DL, 0AH
INT 21H
INC BX
POP CX
LOOP ROW
MOV AH, 4CH
INT 21H
MAIN ENDP
END MAIN
▶ Open this solution in the compiler, then press Visualize to watch it run step by step