Reverse the sentence using recursion
Question
Write a program to reverse the sentence using recursion. Get the sentence from the user.
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
- For each word, we mark start(st) and end(en) index.
- We iterate through each character in a word and if word finished, recursively call next word.
- When we reach the last word in sentence (‘/0’ null character) print the word.
- 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; }