Swapping two numbers using functions

This program swaps two numbers entered by the user.

[code='cpp']#include
void swap(int,int);
void main()
{
int a,b;
cout<<"Enter the numbers";
cin>>a>>b;
swap(a,b);
cout<<"The number which you entered were "< cout< }
void swap(int x, int y)
{
int temp;
temp=x;
x=y;
y=temp;
cout<<"The swapped numbers are as follows"< cout< }
[/code]

  • Guest

    thank you.

    Can you explain the working of the program please?

    • http://gyanguru.org Gyanguru

      Here is what I did in swapping two numbers.

      First, I make a variable called 'temp' which acts a medium for swapping. Then I store the value of x(i.e., my first variable) in temp.

      Then what I do is, I store the value of y in x(I have no problem in losing the value of x here because I already have it safe in my temp variable)

      Now i simply give the value of temp to y.

  • Kovvurisriramareddy8

    plz post how to swap 2 variables using single compound statement.

    • http://gyanguru.org Gyanguru

      You may try doing this

      x=x+y-(y=x);

      Here x and y are the two variables which are to be swapped.

  • Rittabensingh

    html program for swapping 2 numbers

  • Praveenkumarct

    hi

  • Pinky Smiliy

    cn i get flowchart to swap anumber using friend function