Wednesday, 8 March 2017

C Program to swap two numbers without using third variable

In computer programming, the act of swapping two variables refers to mutually exchanging the values of the variables. Usually, this is done with the data in memory. For example, in a program, two variables may be defined thus (in pseudocode).

Here we used an extra variable to swap two numbers. You can also swap them without using an extra virable.

C Program to swap two  numbers without using extra space is given below:


Program:

#include <stdio.h>
int main()
{
    int a,b;
    printf("enter the two numbers : ");
    scanf("%d%d",&a,&b);
    a=a+b;
    b=a-b;
    a=a-b;
    printf("after swapping the two numbers are : a=%d b=%d\n",a,b);
    return 0;
}

Output:
 


EmoticonEmoticon