Reverse function in C++ | C++ program to reverse a string using reverse |

Reverse function in C++:

    C++ has a built in function to reverse the order of given input. It reverses the order of the elements in the range (first, last) of any input. The time complexity of reverse() is O(n).

Program to reverse a given string in C++

#include <bits/stdc++.h>
using namespace std;


int main() {
    cout<<"Enter a String: "<<endl;                //requesting input
    string s;
    cin>>s;
    
    reverse(s.begin(),s.end());                   //using reverse function
    
    cout<<"Reversed String is: "<<s<<endl;                //printing required output
    
    return 0;
}

Input:

Enter a String: 
Rahul

Output:

Reversed String is: luhaR



Program to reverse a string without using reverse function

#include <bits/stdc++.h>
using namespace std;


int main() {
    cout<<
"Enter a String: "<<endl;                          //requesting a string
    string s;
    cin>>s;
    
    string temp=s;                                      //storing in temp for future use
    
    int l=s.length();                                  //calculating the length of string
    int j=0;
    
    for(int i=l-1;i>=0;i--){             //loop to store last to first element of string
        s[j]=temp[i];
        j++;
    }
    
    cout<<"Reversed String is: "<<s<<endl;      //printing the required output
    
    return 0;
}


Input:

Enter a String: 
Rahul

Output:

Reversed String is: luhaR

Post a Comment

0 Comments