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

0 Comments

Start the conversation!

Be the first to share your thoughts

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support