Q14. Write a C program to reverse the place of words in a sentence.

Suppose input is “Welcome to gyantoday” then output should be “gyantoday to welcome”

Steps of  algorithm:

  1. Reverse whole sentence first.

“yadotnayg ot emoclew”

  1. Reverse each word individually.

“gyantoday to welcome”


#include <stdio.h>

/* Function to reverse a string in place */

void reverse(char *l, char *r)


char temp;

while(l < r)


temp    = *l;

*l++ = *r;

*r– = temp;



See also Write a C program to reverse the bits in an integer.

int main()


char str[] = “Welcome to gyantoday”;

 char *str_end, *x, *y;

/* Reverse the whole sentence first */

for(str_end=str; *str_end; str_end++);

reverse(str, str_end-1);

/* Now swap each word within sentence */

x = str-1;

 y = str;

 while(x++ < str_end)


if(*x == ‘\0’ || *x == ‘ ‘)


reverse(y, x-1);

y = x+1;



/* Now print the final string */




Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.