C++ program – Swap two variables using function overloading

by Nideesh C on April 14, 2011 · 0 comments

in C++




A program to demonstrate how function overloading is carried out for swapping of two variables of the various data types, namely integer, floating point number and character types.

#include<iostream.h>
#include<conio.h>
void swap(int &ix,int &iy);
void swap(float &fx,float &fy);
void swap(char &cx,char &cy);
void main()
{
		int ix,iy;
float fx,fy;
char cx,cy;
clrscr();
cout<<"Enter 2 integers:";
cin>>ix>>iy;
cout<<"Enter 2 floating point no:s:";
cin>>fx>>fy;
cout<<"Enter 2 characters:";
cin>>cx>>cy;
cout<<"\nIntegers:";
cout<<"\nix="<<ix<<"\niy="<<iy;
swap(ix,iy);
cout<<"\nAfter swapping";
cout<<"\nix="<<ix<<"\niy="<<iy;
cout<<"\nFloating point no:s";
cout<<"\nfx="<<fx<<"\nfy="<<fy;
swap(fx,fy);
cout<<"\nAfter swapping";
cout<<"\nfx="<<fx<<"\nfy="<<fy;
cout<<"\nCharacters";
cout<<"\ncx="<<cx<<"\ncy="<<cy;
swap(cx,cy);
cout<<"\nAfter swapping";
cout<<"\ncx="<<cx<<"\ncy="<<cy;
getch();
}
void swap(int &a,int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}
void swap(float &a, float &b)
		{
float temp;
temp=a;
a=b;
b=temp;
}
void swap(char &a, char &b)
{
char temp;
temp=a;
a=b;
b=temp;
}

Output:

 Enter 2 integers: 100 200
 Enter 2 floating point no:s :-11.11  22.22
 Enter 2 characters: s t

Integers:
 Ix=100
 Iy=200
 After swapping
 Ix=200
 Iy=100
 Floating point no:
 Fx=-11.11
 Fy=22.22
 After swapping
 Fx=22.22
 Fy=-11.11
 Characters
 Cx=s
 Cy=t
 After swapping
 Cx=t
 Cx=s



Not Satisfied ? Just search & get the result

Related Posts Plugin for WordPress, Blogger...
Be Sociable, Share!

Related posts:

  1. C program to read two integers M and N and to swap their values. Use a user-defined function for swapping. Output the values of M and N before and after swapping with suitable messages
  2. C++ program – Perform complex arithmetic using operator overloading
  3. c program to swap the contents of two numbers using bit-wise XOR operation. Don’t use either the temporary variable or arithmetic operators
  4. C++ program – Perform arithmetic operations of two complex numbers using operator overloading
  5. C program to accept an array of 10 elements and swap 3rd element with 4th element using pointers. And display the results

Leave a Comment

Previous post:

Next post: