Search code examples
cloopsfor-loopnested-loopsc-strings

How to print a specific character from a string in C


I'm recently practicing looping. I learned how to print: for example home to h ho hom home. by using

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

int main (){
    char s[100];
    
    printf("Input string = ");
    scanf("%[^\n]", s);
    
    for (int i=1; i<=strlen(s); i++){
        for(int j = 0; j<i; j++)
        printf("%c", s[j]);
        printf("\n");
    }

    return 0;

How can i reverse it so it can be home hom ho h instead? thank you.


Solution

  • It is easy to do. For example

    for ( size_t i = strlen( s ); i != 0; i-- )
    {
        for ( size_t j = 0; j < i; j++ )
        { 
            putchar( s[j] );
        }
        putchar( '\n' );
    }
    

    Another way is the following

    for ( size_t i = strlen( s ); i != 0; i-- )
    {
        printf( ".*s\n", ( int )i, s );
    }
    

    provided that an object of the type int is able to store the length of the passed string.

    Here is a demonstration program.

    #include <stdio.h>
    #include <string.h>
    
    int main( void )
    {
        const char *s = "home";
    
        for (size_t i = strlen( s ); i != 0; i--)
        {
            printf( "%.*s\n", ( int )i, s );
        }
    }
    

    The program output is

    home
    hom
    ho
    h