C++ program to Reverse a String using recursion

Reverse a String using recursion


Write a C++ program to Reverse a String using recursion. Here’s simple C++ program to Reverse a String using recursion in C++ Programming Language.


What are Functions ?


Function is a block of statements that performs some operations. All C++ programs have at least one function – function called “main()”. This function is entry-point of your program.

A function declaration tells the compiler about a function’s name, return type, and parameters. A function definition provides the actual body of the function.


Defining a Function : :


The general form of a C++ function definition is as follows:

return_type Function_Name( list of parameters )
{
//function’s body
}

  • return_type : suggests what the function will return. It can be void, int, char, some pointer or even a class object.
  • Function_Name : is the name of the function, using the function name it is called.
  • Parameters : are variables to hold values of arguments passed while function is called. A function may or may not contain parameter list.
  • Function body : is he part where the code statements are written.

Below is the source code for C++ program to Reverse a String using recursion which is successfully compiled and run on Windows System to produce desired output as shown below :


SOURCE CODE : :


/*  C++ program to Reverse a String using recursion  */

#include <iostream>
using namespace std;

void reverse(const string& a);

int main()
{
    string str;
    cout << "\nPlease Enter any string :: ";
    getline(cin, str);

    cout<<"\nReverse of String [ "<<str<<" ] is :: ";
    reverse(str);

    return 0;
}

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));
    }
}

OUTPUT : :


/*  C++ program to Reverse a String using recursion  */

Please Enter any string :: CodezClub

Reverse of String [ CodezClub ] is :: bulCzedoC

Process returned 0

Above is the source code for C++ program to Reverse a String using recursion which is successfully compiled and run on Windows System.The Output of the program is shown above .

If you found any error or any queries related to the above program or any questions or reviews , you wanna to ask from us ,you may Contact Us through our contact Page or you can also comment below in the comment section.We will try our best to reach up to you in short interval.


Thanks for reading the post….

Leave a Reply