C++ Program to Reverse Each Word in a String


This is a C++ Program to Reverse a String.

Problem Description

The program takes a string and reverses it.

Problem Solution

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.

C++ Program/Source code

Here is the source code of C++ Program to Reverse a String. The program output is shown below.

  1. #include<iostream>
  2. #include<string.h>
  3. using namespace std;
  4. int main ()
  5. {
  6.     char str[50], temp;
  7.     int i, j;
  8.     cout << "Enter a string : ";
  9.     gets(str);
  10.     j = strlen(str) - 1;
  11.     for (i = 0; i < j; i++,j--)
  12.     {
  13.         temp = str[i];
  14.         str[i] = str[j];
  15.         str[j] = temp;
  16.     }
  17.     cout << "\nReverse string : " << str;
  18.     return 0;
  19. }
Program Explanation

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.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
Runtime Test Cases
Case 1 :
Enter a string : MALAYALAM
Reverse string : MALAYALAM
Case 2 :
Enter a string : gubed
Reverse string : debug
Case 3 :
Enter a string : CruisE
Reverse string : EsiurC

Sanfoundry Global Education & Learning Series – C++ Programs.

To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.

Check this: C++ Books | Programming MCQs

Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.