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?
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 Input6
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
Related Questions
- → OctoberCMS Backend Loging Hash Error
- → "failed to open stream" error when executing "migrate:make"
- → OctoberCMS - How to make collapsible list default to active only on non-mobile
- → Create plugin that makes objects from model in back-end
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → How to install console for plugin development in October CMS
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → How to update data attribute on Ajax complete
- → October CMS - Conditionally Load a Different Page
Ad