In this tutorial you will learn about the C++ Program to Reverse of String and its application with practical example.
In this tutorial, we will learn to create a C++ program that will Reverse of String using C++ programming.
Before starting with this tutorial we assume that you are best aware of the following C++ programming topics:
- looping statements.
- Basic input/output.
- Basic c++ programming
- For Loop.
Usually “string,” means a collection of characters called ‘string’ that represents text data in languages like c,c++ and Java.
What is array?
C++ Program to Reverse of String
In this program we will reversing a string. We would first declared and initialized the required variables. Next, we would prompt user to input a string .Later we will reverse a string.
using namespace std;
int main ()
char strng, tmp; // declaring avriables..
int i, j;
cout << "Enter a string : "; // taking string from user..
j = strlen(strng) - 1; // finding length of string
for (i = 0; i < j; i++,j--)
tmp = strng[i]; // reversing a string..
strng[i] = strng[j];
strng[j] = tmp;
cout << "\nReversing the String : " << strng; // printing reverse string..
In the above program, we have first declared and initialized a set variables required in the program.
- strng = it will hold entered string.
- tmp = it will hold a finding character.
- i and j= for iteration.
In our program, we print the string in reverse order.
i.e the last element of array should be displayed first,followed by second last element and so on.
First of all we take a string as input from user and store the value in variable strng.
And now with the help of strlen() function we will find the length of a string and store the length of string in variable j.
Within the loop we reverse the value of string with help of tmp variable as shown in below image.
And after traversing the whole string traverse from last to first and print the string element in reverse order.