1

I want to print a char '*' repeatedly where I give the no. of times the asterisk should be repeated.

Example: count = 20 and I want to print ******************** using printf() and format specifiers.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
anonymous
  • 11
  • 3
  • 1
    Does [this](https://stackoverflow.com/questions/14678948/how-to-repeat-a-char-using-printf) answer your question? – KUSH42 Aug 26 '20 at 07:13
  • I want the code for count =n not for small constant like 20. I mentioned that as an example. – anonymous Aug 26 '20 at 17:21

3 Answers3

2

There is certainly no way to achieve that using only format specifier. You could hide your loop in a macro maybe but you'll definitely need a loop somewhere.

Puck
  • 2,080
  • 4
  • 19
  • 30
1

You cannot do that with standard format specifiers provided by printf(). However, there's a hacky solution (assuming the maximum padding length is reasonable), if you are willing to waste some space to store a filler string in your program.

#include <stdio.h>

int main(void) {
    const char *fill = "********************"; // 20 chars

    printf("%.*s\n", 10, fill);
    printf("%.*s\n", 15, fill);

    int n = 20;
    printf("%.*s\n", n, fill);

    return 0;
}

This works using .* to provide the maximum length of the string to print as first parameter.

Output:

**********
***************
********************

NOTE: you will only get up to strlen(fill) characters of padding (20 in the above example), anything more and printf will stop at the \0 terminator of fill.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
  • This answers the question but I am pretty sure this shouldn't be used in most cases. – Puck Aug 26 '20 at 07:34
  • 1
    @Puck it's definitely not idiomatic, but there are times in which you need a quick and dirty solution even in C. I think this is the closest it gets to what OP wants. – Marco Bonelli Aug 26 '20 at 07:36
  • @Marco Boneli that answers my question up to a certain extent. Besides that could you mind providing me the solution for **count equal to some unknown value 'n'** instead of a known constant like 20? I want to overcome the issue of time complexity by avoiding loop. – anonymous Aug 26 '20 at 17:25
  • @anonymous you can just use the variable instead of a number: `printf("%.*s\n", n, fill)`. – Marco Bonelli Aug 26 '20 at 19:18
0

I hope this is what you are looking for:

#include <stdio.h>
int main()
{
printf("%.*s", 20, "********************************");;
  return 0;
}