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; 
}

 

Sree Hari Sanjeev

The founder and CEO of Wisdom Overflow. His enthusiasm and effort has taken the blog to next level. You will be motivated just by taking a look at his daily schedule.