How to print a symbol `n` times using a `for` loop, in C?

2.6k Views Asked by At

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);
}
3

There are 3 best solutions below

9
On BEST ANSWER

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 like

for ( int i = 0; i < n; i++ )
{
    putchar( '#' );
}
putchar( '\n' );

Here is a demonstrative program.

#include <stdio.h>

int main(void) 
{
    const char c = '#';
    
    while ( 1 )
    {
        printf( "Enter a non-negative number (0 - exit): " );
        
        unsigned int n;
        
        if ( scanf( "%u", &n ) != 1  || n == 0 ) break;
        
        putchar( '\n' );
        
        for ( unsigned int i = 0; i < n; i++ )
        {
            for ( unsigned int j = 0; j < i + 1; j++ )
            {
                putchar( c );
            }
            putchar( '\n' );
        }
        
        putchar( '\n' );
    }
    return 0;
}

The program output might look like

Enter a non-negative number (0 - exit): 10

#
##
###
####
#####
######
#######
########
#########
##########

Enter a non-negative number (0 - exit): 0

If you need to send the symbol in a file stream then use the function

int fputc(int c, FILE *stream);

instead of putchar.

6
On

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.

0
On

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