ISourceCode

Make the frequent cases fast and the rare case correct

Program to Reverse a String

The following is a code for Reversing a string . First Reverse function uses a simple swapping mechanism using a temp variable. Second Reverse function uses a recursive procedure.

#include<iostream>
#include<cstring>
using namespace std;

void Reverse(char *);

int main()
{
 char s[100];
 cout<<"\nEnter the string=";
 cin.getline(s,100);
 Reverse(s);

 return 0;
}

void Reverse(char *s)
{
 for(int i=0, j=strlen(s)-1;i<j;i++,j--)
 {
 char temp=s[j];
 s[j]=s[i];
 s[i]=temp;
 }
 cout<<"\nReverse="<<s<<"\n";

}

Recursive procedure :

#include<iostream>
#include<cstring>
using namespace std;

void ReverseRecursion(char *, int);
int main()
{
 char s[100];
 cout<<"\nEnter the string=";
 cin.getline(s,100);
 ReverseRecursion(s,0);
 return 0;
}
void ReverseRecursion(char *s, int ptr)
{
 if(ptr<strlen(s)/2)
 {
 char temp=s[ptr];
 s[ptr]=s[strlen(s)-ptr-1];
 s[strlen(s)-ptr-1]=temp;

 ReverseRecursion(s, ++ptr);
 }
 else
 cout<<"\nReverseRecursion="<<s<<"\n";
}

OUTPUT:

laptop:~/code$ g++ reversestring.cpp
oducs@oducs-laptop:~/code$ ./a.out

Enter the string=algo

Reverse=ogla

laptop:~/code$ g++ reversestringrec.cpp
laptop:~/code$ ./a.out

Enter the string=algo

ReverseRecursion=ogla

There are many approaches as well to solve this problem. It is important
to note that Arrays were used in these implementation.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: