Swap Two Numbers In C Language

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

In C, there are several ways to swap the values of two variables. One common way is to use a temporary variable to store one of the values, then assign the values to the variables in the correct order. Here's an example of how to swap the values of two integers using a temporary variable:

Copy code

#include <stdio.h> void swap(int *a, int *b) {    int temp = *a;    *a = *b;    *b = temp; } int main() {    int x = 5, y = 10;    printf("Before swapping: x = %d, y = %d\n", x, y);    swap(&x, &y);    printf("After swapping: x = %d, y = %d\n", x, y);    return 0; }

This method works for any type of data and it's a common and easy way to swap two variables.

Another way to swap two numbers is by using bitwise operator XOR, which is a bitwise operator that compares each bit of the first operand to the corresponding operand in the second operand. If both bits are the same, the corresponding result bit is set to 0. If both bits are different, the corresponding result bit is set to 1. Here's an example of how to swap two integers using the bitwise XOR operator:

Copy code

#include <stdio.h> int main() {    int x = 5, y = 10;    printf("Before swapping: x = %d, y = %d\n", x, y);    x = x ^ y;    y = x ^ y;    x = x ^ y;    printf("After swapping: x = %d, y = %d\n", x, y);    return 0; }

It's important

2. Variable and Data Types

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?