Users Online
· Guests Online: 97
· Members Online: 0
· Total Members: 188
· Newest Member: meenachowdary055
· Members Online: 0
· Total Members: 188
· Newest Member: meenachowdary055
Forum Threads
Newest Threads
No Threads created
Hottest Threads
No Threads created
Latest Articles
Articles Hierarchy
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.
-
#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;
-
}
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.