Is it possible to print '#' n
times using a for
loop in C?
I am used to print(n * '#')
in Python.
Is there an equivalent for that in C?
for(i=0; i < h; i++) {
printf("%s\n", i * h);
}
Yes, using %.*s
format specifier.
int h = 10; //upper limit
char pat[h*h];
memset(pat, '#', sizeof pat);
for (int i=0;i<h;i++)
{
printf("%.*s\n",i*h, pat);
}
output:
##########
####################
##############################
########################################
##################################################
############################################################
######################################################################
################################################################################
##########################################################################################
Please excuse me if I misunderstood your question.
No. It's not possible by any mechanism in standard C. If you want a string of some sub-string repeated n times, you will have to construct it yourself.
Simple example:
const char *substring = "foo";
// We could use `sizeof` rather than `strlen` because it's
// a static string, but this is more general.
char buf[8192];
size_t len = strlen(substring);
char *ptr = buf;
// Ideally you should check whether there's still room in the buffer.
for (int i = 0; i < 10; ++i) {
memcpy(ptr, substring, len);
ptr += len;
}
*ptr = '\0';
printf("%s\n", buf);
To output the symbol
'#'
n
times in the for loop there is no need to create dynamically a string. It will be inefficient.Just use the standard function
putchar
likeHere is a demonstrative program.
The program output might look like
If you need to send the symbol in a file stream then use the function
instead of
putchar
.