This is a C++ Program to Reverse a String.
The program takes a string and reverses it.
1. The program takes a string.
2. Using a for loop and string function, the string is reversed.
3. The result is printed.
4. Exit.
Here is the source code of C++ Program to Reverse a String. The program output is shown below.
#include<iostream>
#include<string.h>
using namespace std;
int main ()
{
char str[50], temp;
int i, j;
cout << "Enter a string : ";
gets(str);
j = strlen(str) - 1;
for (i = 0; i < j; i++,j--)
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
cout << "\nReverse string : " << str;
return 0;
}
1. The user is asked to enter a string and it is stored in the character variable ‘str’.
2. The length of ‘str’ is stored in the variable ‘j’ and ‘i’ is initialized as 0.
3. Using a for loop, the string is reversed.
4. The ith character of str is swapped with jth character using a temporary variable ‘temp’.
5. The loop terminates when i is less than j.
6. str is then printed which is th result.