cloopsfor-loopcharputchar

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


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

Solution

  • 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.