Showing posts with label swapping two variables. Show all posts
Showing posts with label swapping two variables. Show all posts

Wednesday, 17 August 2011

Interchanging two variables without using the third one


Using less variables is a sign of good programming. Here's the example program to interchanging the values of two variables without using third variable.

Code:
#include<stdio.h>
#include<conio.h>
void main()
{
//Initialization
  int var1,var2; 
    printf("Enter two integers\n");
//Taking input from user
      printf("a = ");
      scanf("%d",&var1);
      printf("b = ");
      scanf("%d",&var2);
   var1=var1+var2;
   var2=var1-var2;
   var1=var1-var2;
    printf("a = %d\n",var1);
    printf("b = %d\n",var2);
  getch();

}

Result:

Enter two integers
a = 5
b = 11
a = 11
b = 5