Pages

Custom Search
Showing posts with label reverse order of words. Show all posts
Showing posts with label reverse order of words. Show all posts

Saturday, August 9, 2014

Program to reverse the order of words in a string

Program to reverse the order of words in a string.
For Eg:
Input: this is a simple c program
Output: program c simple a is this

The LOGIC part:
-First determine the length of the string. Use a simple for loop
until you find '\0' else use an inbuilt string function 'strlen()' like I have used.
-then move over to the last word in your string.
Place a pointer at the end of the last word and then find the
space before that word and place a pointer after the space
and using these two pointer append the word to a new string.
-Repeat procedure for all words from last word to first word.


SOURCE CODE:

 #include <stdio.h>  
 #include <stdlib.h>  
 int main()  
 {  
      char str[100], rev[100];  
      int i, j, k, m, n, len, c=0, flag=1;  
      printf("\nEnter a sentence: ");  
      gets(str);  
      printf("\nEntered sentence: ");  
      puts(str);  
      len = strlen(str)-1;          //length of string except \0  
      i=0;  
      j=len;  
      k=0;  
      while(flag==1)                    //while more words to process  
      {  
           flag = 1;  
           i=j;                         //pointer i, j to end of current word  
           while(str[i] != ' ')     //decrement pointer i till beginning of current word  
           {  
                if(i==0)  
                {  
                     flag = 0;          //special case for 1st word of the sentence  
                     break;  
                }  
                i--;  
           }  
            m=i;  
           if(flag)  
           {  
                i=i+1;       
           }       
           for( ; i<=j; )               //append current word to new char array  
           {  
                rev[k++] = str[i++];  
           }  
           j=m-1;                         //move pointer j to end of previous word  
           rev[k++]=' ';  
      }  
      rev[k]='\0';  
      printf("\nReverse sentence: ");  
      puts(rev);  
      printf("\n");  
      return 1;  
 }  


SAMPLE OUTPUT:

Custom Search