Staircase – HackerRank Solution

Staircase – HackerRank Solution

Problem :

Consider a staircase of size n = 4:

   #
  ##
 ###
####

Observe that its base and height are both equal to n, and the image is drawn using # symbols and spaces. The last line is not preceded by any spaces.

Write a program that prints a staircase of size n.

Function Description :

Complete the staircase function in the editor below. It should print a staircase as described above.

staircase has the following parameter(s):

  • n: an integer

Input Format :

A single integer, n, denoting the size of the staircase.

Constraints :

0 < n <= 100 .

Output Format :

Print a staircase of size n using # symbols and spaces.

Note: The last line must have 0 spaces in it.

Sample Input :

6 

Sample Output :

     #
    ##
   ###
  ####
 #####
######

Explanation :

The staircase is right-aligned, composed of # symbols and spaces, and has a height and width of n = 6.

Solution :

#include <bits/stdc++.h>
using namespace std;

// Complete the staircase function below.
void staircase(int n) {
    for (int i = 1; i <= n; i++) {
        for (int a = n-i; a > 0; a--) {
            cout << " ";
        }
        for (int a = 1; a <= i; a++) {
            cout << left << "#";
        }
        cout << endl;
    }

}

int main()
{
    int n;
    cin >> n;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    staircase(n);

    return 0;
}

 178 total views,  1 views today

Leave a Reply

Your email address will not be published. Required fields are marked *