Tim Beyer
Tim Beyer

Reputation: 93

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.

Upvotes: 0

Views: 551

Answers (2)

dbush
dbush

Reputation: 223972

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, "");

Upvotes: 2

David Ranieri
David Ranieri

Reputation: 41017

In the last iteration of the for loop the value of spaces is 0, this is equivalent to

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

and printf prints a space even if the width specifier is 0, change to:

if (spaces > 0)
    printf("%*s", spaces, " ");

Upvotes: 1

Related Questions