Users Online

· Guests Online: 97

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

C++ Program to Reverse Each Word in a String

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.

 

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 1.07 seconds
10,835,272 unique visits