Q1 :- Reverse Right-Angled Triangle Made of Asterisks
Write a JavaScript function that prints the following reverse right-angled triangle pattern of asterisks, for a given positive integer n
:
input
Input = n
Approach
1. Outer Loop
- The outer loop is responsible for printing the rows.
- It starts from
n
and continues as long as the value is greater than 0. - In each iteration, it runs the inner loop and then decreases the value of
i
by 1.
2. Inner Loop
- The inner loop is responsible for printing the columns (like
*
, numbers, etc.). - It starts from
0
and continues until it is less than the current value ofi
(from the outer loop). - Since the outer loop decreases
i
in each step, the inner loop also runs fewer times in each new row.
Example (n = 4):
**** *** ** *
✅ Final JavaScript Solution
function printReverseTriangle(n) { let output = ""; // Outer loop: from n down to 1 for (let i = n; i > 0; i--) { // Inner loop: print i asterisks for (let j = 0; j < i; j++) { output += "*"; } // Add a newline after each row output += "\n"; } return output; } // Test it console.log("Reverse Right-Angled Triangle Pattern for n = 4"); console.log(printReverseTriangle(4));
Q2: Reverse Right-Angled Triangle of Increasing Numbers
🧩 Problem Statement
Write a JavaScript program that prints a triangle made of numbers.
The triangle should be upside down (reverse right-angled) and the numbers in each row should start from 1 and go up.
🧠 Approach
To solve this pattern problem, we will use two loops — one for rows and one for numbers in each row.
✅ Outer Loop (Controls Rows)
- The outer loop decides how many rows will be printed.
- It starts from
n
and goes down to- 1
, because we want the biggest row first. - Each time, it runs the inner loop to print the numbers.
- After each row, we move to a new line.
✅ Inner Loop (Controls Numbers in a Row)
- The inner loop prints numbers from
1
up to the current row number. - For example:
- In the first row (i = 4), it prints
1 2 3 4
- In the second row (i = 3), it prints
1 2 3
- And so on...
- In the first row (i = 4), it prints
- We add a space after each number to keep them separated.
🧪 Example Flow (n = 4)
- Outer loop starts with
i = 4
- Inner loop prints:
1 2 3 4
- Outer loop goes to
i = 3
- Inner loop prints:
1 2 3
- ... continues until
i = 1
Example
Input
Input = 4
Output
1 2 3 4 1 2 3 1 2 1
✅ Final JavaScript Solution
function Print_a_Reverse_Right_Angled_Triangle_With_Increasing_Number(n) { let Number = ''; for (let i = n; i > 0; i--) { for (let j = 1; j <= i; j++) { Number += j + ' '; // Add a space after each number } Number += '\n'; // Move to the next row } return Number; } console.log(Print_a_Reverse_Right_Angled_Triangle_With_Increasing_Number(4));
Top comments (0)