Saturday, May 22, 2010

Reg c:write a function that interchange two values without temp variable?

swap(a,b)

Reg c:write a function that interchange two values without temp variable?
swap(a,b) is not a standard C function, it is a standard C++ function. The question asks about writing are own code for swap(a,b) anyway:





#include %26lt;stdio.h%26gt;





int a = 7;


int b = 23;


/* C uses call-by-value by default */


void swap(int x, int y)


{


a = y;


b = x;


}





int main()


{


printf("a= %d\n",a);


printf("b=%d\n",b);





swap(a,b);





printf("a= %d\n",a);


printf("b=%d\n",b);





return 0;


}





(how do you save indentation when you post here?)





Edit: I like mashiur1973's answer below but keep in mind, the a and b inside swap won't exist outside of the swap function unless you use global variables (like I did) which is usually bad practice or if you use pointers and references like this:





#include %26lt;stdio.h%26gt;





void swap(int *a, int *b)


{


*a = *a + *b;


*b = *a - *b;


*a = *a - *b;


}





int main()


{


int a = 2;


int b = 3;





printf("a= %d\n",a);


printf("b= %d\n",b);





swap(%26amp;a,%26amp;b);





printf("a= %d\n",a);


printf("b= %d\n",b);





return 0;


}
Reply:I think you can use the following:-





void swap(int a, int b)


{


a = a + b;


b = a - b;


a = a - b;


}





Let's analyze the function:-


considering a = 2, b = 3, we call the function


swap(a,b);





Stmt 1: a = a + b;


new value of 'a' would be = 2 + 3 = 5;





Stmt 2: b = a - b;


new value of 'b' would be = 5 - 3 = 2;





Stmt 3: a = a - b;


new value of 'a' would be = 5 - 2 = 3;





Hence at the end we have a = 3 and b = 2;

snow of june

No comments:

Post a Comment