0
for (n = 1; n <= num1, n++)
{
    num2 = num1 - n;
    printf("%*s%*c\n", num2, "", n, '#');   
}

I'm trying to get a half-pyramid of hashtags, with the bottom-left corner left-aligned, and the height x width determined by a single input(num1). Like this:

num1 = 4

Output:
   #
  ##
 ###
####

Instead, I'm getting this (with an input of 4):

   #
   #
   #
   #

2 Answers 2

3

There are a number of ways to do this. Here is a favorite. It takes the width as the first argument to the program (default 5):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char **argv) {

    int width = argc > 1 ? atoi (argv[1]) : 5;
    if (width < 0) width = -width;

    char *hash = "################################################";
    size_t max = strlen (hash);
    char *p = hash + max;
    int i = width > max ? max : width;

    while (i--)
        printf ("%*s\n", width, p -width + i);

    return 0;
}

Output

$ ./bin/padstr_hash
    #
   ##
  ###
 ####
#####

$ ./bin/padstr_hash 6
     #
    ##
   ###
  ####
 #####
######
Sign up to request clarification or add additional context in comments.

Comments

1

%*c is a specifier for width or precision of the field. You're not printing n characters, you're just printing one character padded n spaces.

If you want to print a character multiple times, use a for loop.

1 Comment

If my answer works for you, then please accept it by flagging it with a green check. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.