Given a sentence reverse the words of the sentence but not the characters in the words

Given a sentence reverse the words of the sentence but not the characters in the words.

For Example:

If the input string is "CodeRegister Loves Coding"

then the output should be "Coding Loves CodeRegister"



Implementation:



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

/* Function reverse to print the word from next character of a ' ' character 
till ' ' character or '\0' character */
void reverse(char *s,int n)
{
 /* If we come across a space character or a null character, stop the recursive call */
  if(*(s+n)=='\0' || *(s+n)==' ')
   return;
   
  /* Until that print every character */
  printf("%c",*(s+n));
  
  /* And call the recursive function */
  reverse(s,n+1);
}

int main()
{
  char *s;
  int i;
  
  /* allocate memory block of 256 characters & assign starting address
  to character pointer 's' */
  s=(char*)malloc(sizeof(char)*256);
  
  /* Get the sentence from the user */
  gets(s);
  
  /* calculate the size of the sentence using strlen() library function */
  i=strlen(s)-1;
  
  /* until the index 0 */
  while(i>=-1)
  {
   
   /* traverse from last character of the sentence until we encounter a space */
    if(*(s+i)==' ' || i==-1)
    {
     /* Reverse the string from index next to space until another space or 
     null character */
      reverse(s,i+1);
      
      /* Print a space for every word */
      printf(" ");
    }
    /* Decrease the index pointer of the string */
    i--;
  }
  return 0;
}