Last Updated: 26 Nov, 2020

Diamond of Stars

Easy
Asked in companies
DeloitteCompro TechnologiesAppSuccessor

Problem statement

You are given an integer ‘N’. Your task is to print the following pattern for the ‘N’ number of rows.

For Example:
Pattern for ‘N’ = 5:

The dots represent spaces.
Note:
‘N’ is always odd.
Input format :
The first line of input contains ‘T’, denoting the number of test cases. Then each test case follows.

Each test case contains a single integer ‘N’, denoting the number given.
Output format :
For each test case print 'N' strings denoting the pattern. 
Constraints :
1 <= ‘T’ <= 5
1 <= ‘N’ <= 600

Time limit = 1 sec.

Approaches

01 Approach

The main idea is to divide the pattern into two halves, the upper half and the lower half, and print them separately.

 

The steps are as follows:

  • Declare a variable ‘currRow’ and initialize it to 1.
  • Execute a while loop with the condition that ‘currRow’ is less than equal to ‘N’/2 + 1:
    • Maintain a variable ‘spaces’ which tells us how many spaces to give.
    • Print ‘N’/2 + 1 - ‘currRow’ spaces.
    • Declare a variable ‘currCol’ = 1.
    • Loop while ‘currCol’ is less than equal to (2 * ‘currRow’) - 1
      • Print stars ‘*’
      • Increase ‘currCol’ by 1.
    • End with a line.
  • Repeat the same task for the bottom half, but this time ‘currRow’ would go till ‘N’/2 and ‘currCol’ will start from 2 * ((‘N’ / 2) 0 ‘currRow’ + 1) - 1 and go till 1.