C++ Program to Reverse a Sentence Using Recursion

09/06/2024 0 By indiafreenotes

Reversing a sentence using recursion is an interesting problem that illustrates the utility of recursive thinking in solving real-world problems. In this context, reversing a sentence means to print or return the words in reverse order compared to how they were originally inputted.

Here is a simple C++ program that demonstrates how to reverse a sentence using recursion. The program will ask the user for a sentence, then reverse it word by word using a recursive function.

#include <iostream>

#include <string>

#include <sstream>

// Recursive function to reverse the words in the sentence

void reverseSentence(std::istringstream& iss) {

    std::string word;

    if (iss >> word) {  // Read the next word

        reverseSentence(iss);  // Recursive call before printing the word

        std::cout << word << ” “;



int main() {

    std::cout << “Enter a sentence: “;

    std::string input;

    getline(std::cin, input);  // Read the full line of text

    std::istringstream iss(input);  // Use istringstream to read words from the sentence

    std::cout << “Reversed sentence: “;


    std::cout << std::endl;

    return 0;



  • Input:

The program reads a complete line as input using getline, which allows it to handle spaces between words effectively.

  • Using istringstream:

The input string is fed into an istringstream object. This utility helps in extracting words one by one from the sentence.

  • Recursive Function (reverseSentence):

This function takes an istringstream object as an argument. It tries to extract a word from the stream. If it succeeds (i.e., if there are still words left to read), it makes a recursive call before it prints the word. This order of operations ensures that the recursion goes all the way to the end of the sentence, starts unwinding, and then prints the words in reverse order as the recursion stack collapses.

  • Output:

The words are printed in reverse order as the recursive function unwinds.

Note on Efficiency

The recursive method is clear and concise for reversing sentences or similar tasks where depth is typically not going to be prohibitive. However, recursion depth is limited by stack size, so for extremely long texts, an iterative approach might be necessary or you might need to adjust system settings to allow deeper recursion if stack overflow occurs. This is generally not an issue for most simple sentences or standard use cases.