May anyone tell me why the values aren't swapping?

Joined
Feb 29, 2020
Messages
1
Reaction score
0
Hello guys, I am a beginner in programming and C is the first language I learn.
Below is the suggested code that actually swaps the value with pointers values.

void swap (int *num1, int *num2);

int main() {
int x = 25;
int y = 100;

printf("x is %d, y is %d\n", x, y);
swap(&x, &y);
printf("x is %d, y is %d\n", x, y);

return 0;
}

void swap (int *num1, int *num2) {
int temp;

temp = *num1;
*num1 = *num2;
*num2 = temp;
}

And I have tried to modified it into just simply variables swapping but it won't work. May anyone tell me why isn't it swapping?
I basically only changed pointers variables into normal variables. (Below is the code I modified after like learning for a day)


void swap (int num1, int num2);

int main() {
int x = 25;
int y = 100;

printf("x is %d, y is %d\n", x, y);
swap(x, y);
printf("x is %d, y is %d\n", x, y);

return 0;
}

Thank you guys
void swap (int num1, int num2) {
int temp;

temp = num1; //temp = x
num1 = num2; // x = y
num2 = temp; // y = temp
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top