Showing posts with label swapping. Show all posts
Showing posts with label swapping. Show all posts

Saturday, January 29, 2011

Swapping two strings in c++

Swapping two strings is an interesting program , here is the c++ code

******************* Start of Program ************************

// Swapping two strings

#include"iostream.h"
#include"conio.h"
#include"stdio.h"

void main()
{
clrscr();
char str1[20],str2[20],swap[20];
cout<<"Enter 1st string :: ";
gets(str1);
cout<<"Enter 2nd string :: ";
gets(str2);

int i=0;

while(str1[i]!='\0')
{
swap[i]=str1[i];
i++;
}

swap[i]='\0';


int j=0;

while(str2[j]!='\0')
{
str1[j]=str2[j];
j++;
}

str1[j]='\0';

j=0;
while(j{
str2[j]=swap[j];
j++;
}
str2[j]='\0';

cout<<"\n\nAfter Swapping ::";
cout<<"\n\nString 1 is :: "<cout<<"\nString 2 is :: "<
getch();
}

******************* END ************************

Swapping two variables in c++

Swapping of variables means that changing the values of variable with each other's value.

Swapping two integer values


Method 1 (using third variable )
--------

******************* Start of Program ************************

#include"iostream.h"
#include"conio.h"

void main()
{
clrscr();
int a,b,c;
cout<<"Enter value of a :: ";
cin>>a;
cout<<"\nEnter value of b :: ";
cin>>b;


c=a;
a=b;
b=c;

cout<<"\nNow value of a is "<cout<<"\nNow value of b is "<
getch();
}
******************* END ************************



Method 2 ( without using third variable )
--------
* Main advantage of this program is that it uses less memory

******************* Start of Program ************************

#include"iostream.h"
#include"conio.h"

void main()
{
clrscr();
int a,b;
cout<<"Enter value of a :: ";
cin>>a;
cout<<"\nEnter value of b :: ";
cin>>b;


a=a+b;
b=a-b;
a=a-b;

cout<<"\nNow value of a is "<cout<<"\nNow value of b is "<
getch();
}

******************* END ************************