Swapping is a way of exchanging the values of two different variables. In C programming, we have multiple approaches to swap two numbers efficiently. In this article, we will learn each approach one by one.
Approach 1: Swap two numbers using a Temporary variable.
In this approach, we take the help of a third temp variable for swapping values.
Step-by-step algorithm:
Step 1: Input the two numbers from the user.
Step 2: Create a temporary variable to hold the value of one of the numbers.
Step 3: Assign the value of the first number to the temporary variable.
Step 4: Assign the value of the second number to the first number.
Step 5: Assign the value of the temporary variable to the second number.
Step 6: Print the swapped values of the two numbers.
Below is the C program to swap two numbers using the third temporary variable.
//C Program to swap two numbers usingn third variable #include <stdio.h> int main() { int num1, num2, temp; // Input the two numbers printf("Enter two numbers: "); scanf("%d %d", &num1, &num2); // Create a temporary variable and swap the numbers temp = num1; num1 = num2; num2 = temp; // Print the swapped values printf("Swapped values: %d %d\n", num1, num2); return 0; }
Enter two numbers: 20 10
Swapped values: 10 20
Approach 2: Swap two numbers using Arithmetic Operations.
- Add the first number to the second number and store the result in the first number.
- Subtract the second number from the first number and store the result in the second number.
- Subtract the second number (new value) from the first number (new value) and store the result in the first number.
//C program to swap two number without third variable #include <stdio.h> int main() { int num1, num2; // Input the two numbers printf("Enter two numbers: "); scanf("%d %d", &num1, &num2); // Perform arithmetic operations to swap the numbers num1 = num1 + num2; num2 = num1 - num2; num1 = num1 - num2; // Print the swapped values printf("Swapped values: %d %d\n", num1, num2); return 0; }
Enter two numbers: 20 10
Swapped values: 10 20
Approach 3: Swap two numbers using Bitwise XOR Operation.
//C program to swap to number using XOR operation #include <stdio.h> int main() { int num1, num2; // Input the two numbers printf("Enter two numbers: "); scanf("%d %d", &num1, &num2); // Perform bitwise XOR operations to swap the numbers num1 = num1 ^ num2; num2 = num1 ^ num2; num1 = num1 ^ num2; // Print the swapped values printf("Swapped values: %d %d\n", num1, num2); return 0; }
Enter two numbers: 8 10
Swapped values: 10 8
No comments:
Post a Comment