C program to reverse words of a given sentence

#include <stdio.h>
#include <string.h>
void  main()
{
    char str[100], rev[100];
    int len, i, index, s, e;
    printf("Enter string: ");
    gets(str);
    len   = strlen(str);
    index = 0;
    s = len - 1;
    e = len - 1;
    while(s > 0)
    {
       if(str[s] == ' ')
        {
            i = s + 1;
            while(i <= e)
            {
                rev[index] = str[i];
                i++;
                index++;
            }
            rev[index++] = ' ';
           e= s - 1;
        }
       s--;
    }
    for(i=0; i<=e; i++)
    {
        rev[index] = str[i];
        index++;
    }
    rev[index] = '\0';
    printf("%s", rev);
}


input: i love my country
output: country my love i

No comments:

Post a Comment