Tim Beyer Tim Beyer - 2 months ago 9
C Question

c printf(%*s) explanation

So, I am trying to output a formatted string of mario's pyramid, i.e:

##
###
####


The dots represent spaces. The height is determined by the user during runtime. The following code is what I have found to work.

#include <stdio.h>

void hash(void) {
printf("%s", "#");
}

int main(void) {
int height;
printf("%s", "Enter height of mario's pyramid: ";
scanf("%i", &height);

for (int i = 0; i < height; i++) {
int spaces;
if (height == 1 || i == (height - 1) {
spaces = 0;
}
else {
spaces = height - (i + 1);
printf("%*s", spaces, " ");
}
for (int j = 0; j < (i + 1); j++) {
hash();
}
printf("\n");
}

return 0;
}


Now that you see what works, let's see something that doesn't work, everything is the same except the for loops.

#include <stdio.h>

void hash(void) {
printf("%s", "#");
}

int main(void) {
int height;
printf("%s", "Enter height of mario's pyramid: ";
scanf("%i", &height);

for (int i = 0; i < height; i++) {
int spaces;

spaces = height - (i + 1);
printf("%*s", spaces, " ");

for (int j = 0; j < (i + 1); j++) {
hash();
}
printf("\n");
}
return 0;
}


So, as you can see, the only difference is the conditional statements, setting spaces to 0 if
height == 1
or
i == height - 1
, but the outcome is completely different. For some reason, when using the conditional statements, the space doesn't seem to print, which is actually what I wanted, but I'm pretty sure this isn't how I should do it. So, I was wondering if anyone knows what exactly is happening here and could explain it to me.

Answer

This command:

printf("%*s", spaces, " ");

Will always print at least one space, because a single space is the string you're printing.

Change it to print an empty string:

printf("%*s", spaces, "");