Inverted Triangle Of Stars

Posted: 20 Feb, 2021
Difficulty: Easy

PROBLEM STATEMENT

Try Problem

You have been given an integer ‘N’. You need to print an inverted isosceles triangle of stars such that the height of the triangle is N.

For example :
If N = 4 then the output will
*******
 *****
  ***
   *
Input Format:
The first line contains an integer 'T' which denotes the number of test cases or queries to be run. Then the test cases are as follows.

The first line of each test case contains an integer ‘N’ which denotes the height of the inverted isosceles triangle of stars to be printed.
Output Format:
For each test case, print an inverted isosceles triangle of stars such that the height of the triangle is N

Print the output of each test case in a separate line.
Constraints:
1 <= T <= 100
1 <= N <= 100

Time Limit : 1 sec
Approach 1

The basic idea of this approach is to run two loops nested inside an outer loop. The inner two loops make the triangle isosceles, while the outer loop decides the height of the triangle. We can observe the number of stars required at any height ‘h’ is (2 * h - 1). 

 

  • Run two loops nested inside another loop.
  • The first inner loop adds the number of spaces before the stars of each line to make the triangle isosceles. At the ‘i’th level, the number of spaces required before the stars are ‘i’ spaces.
  • The inner second loop prints the required number of stars. At the ‘i’th level, the number of stars required after the spaces are ‘2*(h-i)+1’ stars.
  • The outer loops decide the height of the triangle.
Try Problem