English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

4 answers

swap(a,b)

2006-06-24 06:22:47 · answer #1 · answered by iyiogrenci 6 · 0 1

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;

2006-06-25 05:33:27 · answer #2 · answered by mashiur1973 2 · 0 0

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

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

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(&a,&b);

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

return 0;
}

2006-06-24 06:33:19 · answer #3 · answered by George3 4 · 0 0

Use the XOR (unique OR) operator: "In computing gadget programming, the XOR replace is an set of rules which makes use of the XOR bitwise operation to alter diverse values of variables having the comparable information type without using a short-term variable." It sounds like what your instructor is calling for. The bitwise XOR operator (^) is an operator that's accessible in C. there is pattern C code interior the link below.

2016-10-31 10:04:06 · answer #4 · answered by ? 4 · 0 0

fedest.com, questions and answers