Program to Reverse Sentence Using Recursion in C
Recursion :
Recursion is defined as calling the function by itself. It can be used when the solution depends on solutions to smaller instances of the same problem. Here we will use recursion to find sum of natural number.
Working of Program :
In the program, we will take the sentence and use recursion function to reverse the sentence
Run
#include<stdio.h> void help() { // function to reverse sentence char ch; scanf("%c", &ch); if (ch != '\n') { help(); // calling function again printf("%c", ch); } } int main() { printf("Enter the sentence : "); help(); return 0; }
Output :
Enter the sentence : tseb si atsniperp prepinsta is best
What Happened Above?
In the Above Program, we take the sentence from the user and write the help function to reverse the statement. In help function, we take the character by character of the sentence and reverse it.
Example :
Let’s solve the same problem but this time we use the iterative method.
Run
#include<stdio.h> int main() { char str[100] = "tseb si atsniperP"; int len = 0; for(int i=0; str[i]!= '\0'; i++){ // calculate the length of sentence len++; } printf("Reverse Sentence is : "); for(int i=0;i < len;i++){ // loop to reverse sentence printf("%c", str[len-i-1]); } return 0; }
Output :
Reverse Sentence is :Prepinsta is best
What Happened Above?
In the above program, we take the sentence and iterate the for loop from 0 to length of sentence and print the sentence by reversing.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment