Wednesday, July 6, 2011

C Programs 04: To swap two numbers without using a temporary variable

Two programs are given below to swap two numbers without using a temporary variable.

Program 1

#include<stdio.h>
main(void)
{
int a,b;
printf("Enter two numbers a and b\n");
scanf("%d",&a);
scanf("%d",&b);
printf("\n A = %d \n B  = %d ",a,b);

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

printf("\nAfter swapping \n A = %d \n B  = %d \n",a,b);
}

Program 2:



#include<stdio.h>
main(void)
{
int a,b;
printf("Enter two numbers a and b\n");
scanf("%d",&a);
scanf("%d",&b);
printf("\n A = %d \n B  = %d ",a,b);

a=a*b;
b=a/b;
a=a/b;

printf("\nAfter swapping \n A = %d \n B  = %d \n",a,b);
}







2 comments:

Anonymous said...

Great post - thanks! I was looking for how to do this in Java and I found this:

http://www.programmerinterview.com/index.php/general-miscellaneous/swap-numbers-without-temp/

ankit s sachan said...

best solution of C program to swap two numbers

http://programmergallery.com/c-program/c-program-swap-two-numbers.php

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | coupon codes