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.

sort elements in lexicographical order in c

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

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

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

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription