Navigation Menu

Currently the navigation bar is not functioning. Use the Blog Archive or the Google Custom Search to find content.

Thursday 26 September 2013

C program to exchange the values of two variables with and without temporary variable

Given below is a c program to exchange the values of two variables with and without temporary variable.

Concept (using temporary variable):

Use a temporary variable(temp) to store the value of a variable(a) and then put the contents of another variable(b) into variable(a) and then put the value of variable(temp) into variable(b).

temp=a;
a=b;
b=temp;

Concept (without using temporary variable):

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

Code :
#include <conio.h>
#include <stdio.h>
main()
{
    int a=10,b=20,x;
    clrscr();
    printf("Before swapping\t");
    printf("a=%d\tb=%d",a,b);
    printf("\nAfter swapping\t");
    x=a;
    a=b;
    b=x;
    printf("a=%d\tb=%d",a,b);
    printf("\nBefore swapping\t");
    printf("a=%d\tb=%d",a,b);
    a=a-b;
    b=a+b;
    a=b-a;
    printf("\nAfter swapping\t");
    printf("a=%d\tb=%d",a,b);
    getch();
}
Output :
Before swapping    a=10    b=20
After swapping     a=20    b=10
Before swapping    a=10    b=20
After swapping     a=20    b=10
Note : The program above has been tested using TurboCPP. Leave a comment if you feel the program is incorrect and/or has errors and/or if the program and its output don't match. Please report about broken links.