Friday 19 July 2013

06. Write a C++ program that uses overloaded functions to swap

#include<iostream>
using namespace std;
void swap(int &,int&);                           /*we are passing the address of the variables to functions
                                                             so that the modified values will take effect on the main method*/
void swap(char&,char&);                     //else the a,b values seems never swap(a=a; b=b)
void swap(float&,float&);
int main()
{
    int ch;
cout<<"\nenter '1' to swap two integers ";
cout<<"\nenter '2' to swap two charecters";
cout<<"\nenter '3' to swap two real values";
ch:                                                      //label "ch" I have used for the successful execution of the program
cin>>ch;                                             //variable to read the choice from user
switch(ch)
{
case 1:
    int a,b;
    cout<<"enter a,b values";
    cin>>a>>b;
    cout<<"a,b values before swaping: "<<a<<" , "<<b<<endl;
    swap(a,b);
    cout<<"a,b values after swaping are : "<<a<<" , "<<b<<endl;
    break;                               //Break have used to skip the execution of remaining cases
case 2:
    char c,d;
    cout<<"enter a,b values";
    cin>>c>>d;
    cout<<"a,b values before swaping: "<<c<<" , "<<d<<endl;
    swap(c,d);
    cout<<"a,b values after swaping are : "<<c<<" , "<<d<<endl;
    break;
case 3:
    float e,f;
    cout<<"enter a,b values";
    cin>>e>>f;
    cout<<"a,b values before swaping: "<<e<<" , "<<f<<endl;
    swap(e,f);
    cout<<"a,b values after swaping are : "<<e<<" , "<<f<<endl;
    break;

default:

    cout<<"enter a valid choice: ";
    goto ch;                                  /*be cautious while using labels. It will transfer control          
                                                    Dynamically(excluding sequence or the order of execution)*/
}

return 0;
}

void swap(int &a,int &b)           /*Function overloading take place by having same name 
                                                   with same number of parameters but different data type*/
{
int t;
t=a;
a=b;
b=t;
}

void swap(float &a,float &b)
{
float t;
t=a;
a=b;
b=t;
}

void swap(char &a,char &b)
{
char t;
t=a;
a=b;
b=t;
}

No comments:

Post a Comment