Reverse a Sentence

Beginner

Introduction

In this lab, you will learn step-by-step how to write a C++ program that can reverse any input sentence using recursion. The program will take an input sentence from the user and output the reversed sentence.

Include Necessary Libraries

In C++, to use the standard input/output stream objects like cin, cout, we need to include the iostream library. So, add the following code block in the beginning of the main.cpp file:

#include <iostream>
using namespace std

Declare a Reverse Function

In this program, we need a function to reverse the string recursively. Add the following code block after the using namespace std; statement:

void reverse(const string& a);

Define the main Function

As we know, the main function is the entry point of our program. In the main function, we will ask the user to enter a sentence and pass that sentence to our reverse function.

int main() {
  string str;

  cout << "Please enter a sentence: ";
  getline(cin, str);

  reverse(str);

  return 0;
}

Here, we are asking the user to enter a sentence, and then we are calling our reverse function and passing the entered sentence as an argument.

Define the reverse Function

Now, we need to define the reverse function that we declared earlier. We will use recursion to reverse the entered sentence. Here is the implementation of the function:

void reverse(const string& str) {
  size_t numOfChars = str.size();

  if(numOfChars == 1) {
    cout << str << endl;
  }
  else {
    cout << str[numOfChars - 1];
    reverse(str.substr(0, numOfChars - 1));
  }
}

In this function, we first calculate the size of the input string using str.size(), if the size of the string is 1, then it is the base case, and we just print the last letter of the input sentence. Otherwise, we print the last character, and then we recursively call the reverse function with the string excluding the last letter.

Compile and Run

We have finished writing our program. Now, we need to compile and run it. Open a terminal in the ~/project directory and use the following command to compile the code:

g++ main.cpp -o main

This command will generate an executable named main. Now, use the following command to run the program:

./main

After running the program successfully, you can see the output like:

Please enter a sentence: Study tonight
thgnot ydutS

Summary

In this lab, you have learned how to write a C++ program that can reverse a sentence using recursion. You have implemented a reverse function that uses recursion to reverse the entered sentence and then called that function in the main function with the input sentence as an argument. Finally, you have compiled and run the program in the terminal to see the output.

Other Tutorials you may like