Search code examples
arrayscstringsortingreverse

I want to know why this program below is not working i want to print the reverse of each string?


#include<stdio.h>
int main()
{
    char str[5][10];
    int i,j,k;
    printf("Enter 5 strings:");
    for(i=0;i<=4;i++)
    {
        scanf("%s",str[i]);
    }
    for(i=0;i<=4;i++)
    {
        for(j=0;str[i][j]!='\0';j++);
        for(k=j-1;k>=0;k--)
        {
            printf("%s",str[i][k]);
        }
    }
    return 0;
}

please also explain my mistake and how to make such program without strrev() function i know it might be a dumb question but i am asking this because i am new to programming please help.


Solution

  • Is this what you were trying to do?

    #include<stdio.h>
    int main()
    {
        char str[5][10];
        int i,j,k;
        printf("Enter 5 strings:");
        for(i=0;i<5;++i)
        {
            scanf("%s",str[i]);
        }
        
        for(i=0; i<5; ++i)
        {
            for(j=strlen(str[i])-1; j>=0; --j)
            {
                printf("%c", str[i][j]);
            }
            printf(" ");
        }
        
     
     return 0;   
    }
    

    Enter 5 strings: Hello world this might work
    
    Output:
    
    olleH dlrow siht thgim krow