Reverse the sentence using recursion

Question

Write a program to reverse the sentence using recursion. Get the sentence from the user.

Reverse the sentence using recursion

LOGIC

  • To Reverse the sentence, we are going to recursively call until we reach the last word.
  • Print the last word and return back to the previous word and repeat the same process.
  • Starting and ending index is marked for each word.

Algorithm

  1. For each word, we mark start(st) and end(en) index.
  2. We iterate through each character in a word and if word finished, recursively call next word.
  3. When we reach the last word in sentence (‘/0’ null character) print the word.
  4. Print word and return control to the previous word.

 

#include<stdio.h>
void recurse()
void main()
{
   char arr[]={"welcome to wisdom overflow"};
   recurse(arr,0);            //call
}
void recurse(char a[],int n) 
{
   int st = n;                // starting index 
   int i;
   int en = st;               // ending index
   while(1)
   {
      if(a[en] =='\0')
         break;               // base condition
      else if(a[en] ==' ')
      { 
         recurse(a,en+1);     //recursive call if word ended
         break;
       }
       else
          en++;               // incrementing index if it is character
   }
   for( i =st;i<=en;i++)
   {
      printf("%c",a[i]);      // printing the word
   }

  return; 
}

 

Follow For Instant Updates

Join WhatsApp Group: link
Join our Telegram Channel: link
Like our Facebook Page:  link
Subscribe to our Youtube channel: link

Sree Hari Sanjeev

The founder of Wisdom Overflow. Software Developer at Zoho Corporation.
4 2 votes
Article Rating
Subscribe
Notify of
guest
5.4K Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
5.4K
0
Would love your thoughts, please comment.x
()
x