Write a C++ program to Reverse a Sentence Using Recursion

C++ program to Reverse a Sentence Using Recursion

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn C++ programming concepts. You can learn C++ language at your own speed and time. One can learn concepts of C++ language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

C++ program to Reverse a Sentence Using Recursion
C++ program to Reverse a Sentence Using Recursion

Write a C++ program to Reverse a Sentence Using Recursion

PROGRAM:C++ program to Reverse a Sentence Using Recursion

/* C++ program to Reverse a Sentence Using Recursion*/
#include <iostream>
using namespace std;

// function prototype
void reverse(const string& a);

int main() {
  string str;

  cout << " Please enter a string " << endl;
  getline(cin, str);
    
  // function call
  reverse(str);

  return 0;    
}

// function definition
void reverse(const string& str) {

  // store the size of the string
  size_t numOfChars = str.size();

  if(numOfChars == 1) {
    cout << str << endl;
  }
  else {
    cout << str[numOfChars - 1];

    // function recursion
    reverse(str.substr(0, numOfChars - 1));
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *