Saturday, December 4, 2021
HomeTop Coding QuestionWrite a program to reverse an string

Write a program to reverse an string

Given a string ,we need to reverse the whole string ,and print their value on the screen.

Example:

input:abcde
output:edcba

Logic:

Step 1-create a temp variable.
Step 2-initalise low=0,high=n-1
Step 3-start swapping till (low<high) satisfy.

Code-

#include<bits/stdc++.h>
using namespace std;
int main()
{
   string s="abcde";
    int n=s.length();
    for(int i=0;i<n/2;i++)
    {
        swap(s[i],s[n-i-1]);
    }
    
    for(int i=0;i<n;i++)
    {
        cout<<s[i];
    }
    cout<<endl;
   
  
   
    
    
}

Output:

edcba

Time complexity:0(N)

Space Complexity:O(1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments