Friday, 1 November 2013

Swapping Values of Two Variables - C++ Source Code

This is a very simple program to swap values of two numbers and output.

Code

/*Support us by subscribing, commenting, and viewing the 
blog frequently! - GeekyCircle Admin :)*/
#include<iostream.h>
#include<conio.h>

void main()
{
    int x,y,t;
    cout<<"Enter first number (x) : ";
    cin>>x;
    cout<<"\nEnter second number (y) : ";
    cin>>y;
   
    t = x;
    x = y;
    y = t;

    cout<<"Value of x now is "<<x<<endl;
    cout<<"Value of y now is "<<y<<endl;

    getch();
}


For newer IDEs, visit this page.
Working

After inputting the numbers, the value of x is assigned to a temporary variable t. Now value of x is assigned to y and value of y is replaced by the value of the temporary variable t. Effectively, value of y is transferred to x and x's value to y.
Graphical representation


No comments:

Post a Comment

You might also like