Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to reverse a string

C++ Code Example — String Programs

ADVERTISEMENT

WAP to reverse a string

Objective

Write a C++ program to reverse a string.

Algorithm / Approach

  1. Include the <algorithm> header file.
  2. Read a string into s1.
  3. Call the built-in reverse function using iterators: reverse(s1.begin(), s1.end()).
  4. Print the modified string.
main.cpp
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
 string s1;
 cout<<"Enter a string : ";
 getline(cin,s1);
 reverse(s1.begin(),s1.end());
 cout<<"Reverse String = "<< s1;
 return 0;
}

Expected Output

Enter a string : cprowess
Reverse String = sseworpw

Explanation of the Program

  • The &lt;algorithm&gt; library in C++ provides a massive suite of highly optimized functions for manipulating data collections.
  • The reverse() function takes two "iterators" (pointers that define a start and end boundary) and perfectly reverses the elements between them in-place, without requiring a second backup string.

Complexity

Time Complexity O(n)
Space Complexity O(1)
ADVERTISEMENT