07
Jan
2020

Hackerrank Staircase (C++)

C++ :

void staircase(int n) {
    int num = n;
    for(int i = 1; i <= n; i++){
        for(int j = (n - i); j > 0; j--){
            cout << " ";
        }
        for(int k = 0; k < i; k++){
            cout << "#";
        }
        cout << endl;
    }
}

Explanation:

This is one of our favorites. Used to print stars (*) in school assignments previously, now we are printing hashtags (#). The loop for j is to take care of the spaces, the loop for k is to take care of the #. The i loop is to take care of printing the correct newline. Yes, this solution is not pretty with this many for loops. The timing for this is O² still, since there are 2 layers of nested loops.

You may also like...

Leave a Reply

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