asked 117k views
3 votes
Can anyone help me understand how this code is actually swapping the two numbers? The example numbers im using are numb1 = 85 and numb2 = 100 . But when i try to do the math out on paper, i understand how numb1 becomes 100, but i end up with 115 for variable numb2.

include <stdio.h>
int main(void)
{
int numb1, numb2;
printf("what is the vaule of numb1: "); scanf("%i", &numb1);
printf("what is the vaule of numb2: "); scanf("%i", &numb2);
numb1 = numb1 - numb2;
numb2 = numb1 + numb2;
numb1 = numb2 - numb1;

printf("The swapped value of numb1 is: %i \\", numb1);
printf("The swapped value of numb2 is: %i", numb2);
return 0; }​

asked
User Car
by
8.0k points

1 Answer

2 votes

numb1=85-100=-15

numb2=-15+100=85

numb1=85-(-15)=100

And so you end up with numb1=100 and numb2=85.