Ad

What Is My C Code Not Printing # In Staircase Pattern, This Is From Hackerrank, I Did Not Pass All Test Cases, But I Can't Point Out Why?

- 1 answer

Write a program that prints a staircase of size n.

I did not pass through all the test cases and don't understand where I made mistake.

This is my code:

void staircase(int n) {
    char a[n][n];
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++) {
            if((i + j) > ((n / 2) + 1)) {
                a[i][j] = '#';
                printf("%c", a[i][j]);
            } else {
                printf(" ");
            }
        }
        printf("\n");
    }
}

Given Input
6
Expected Output

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

Explanation:

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

Ad

Answer

The problem is in the condition

if((i + j) > ((n / 2) + 1))

It should be

if(j >= n - i - 1)    // or   if(i + j >= n - 1)

To make this easier, I would create a helper function. Also, there's no need for the VLA a[n][n] that you don't even use for anything.

void repeat_char(int x, char ch) {
    for(int i=0; i < x; ++i) putchar(ch);
}

void staircase(int n) {
    for(int i = 1; i <= n; ++i) {        
        repeat_char(n - i, ' ');   // or  printf("%*s", n - i, "");
        repeat_char(i, '#');
        putchar('\n');
    }
}
Ad
source: stackoverflow.com
Ad