Sunday, January 22, 2017

Exchange the value of two numeric variables without using a third variable. In C

/*
Language : C

Exchange the value of two numeric variables
without using a third variable

This works for int and float types

By Hemanth Roy MV, 2005
*/
#include<stdio.h>

int main()
{
float a, b;

printf("Enter value for 'a'\n");
scanf("%f", &a);
printf("Enter value for 'b'\n");
scanf("%f", &b);

printf("a = %f\tb = %f\n\n", a, b);

if (a<b){
b=b/a; a=a*b; b=a/b;
} else {
a=a/b; b=b*a; a=b/a;
}

printf("a = %f\tb = %f\n\n", a, b);

return 0;
}

1 comment:

  1. This was my version. But Jatin Mandav on facebook (https://www.facebook.com/profile.php?id=100008242069118)gave a better shorter method

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

    ReplyDelete