⑫ C Program to Swap Two Numbers Without Using a Temporary Variable (With Program and Explanation)

๐Ÿ” C Program to Swap Two Numbers Without Using a Temporary Variable

Swapping two numbers means exchanging their values.
Usually, we use a temporary variable, but in this program, we’ll swap the numbers without using any extra variable.


๐Ÿ’ก Logic Used

We use addition and subtraction to swap the values.

Steps:

  1. Add both numbers and store the result in the first number.

  2. Subtract the second number from the first to get the original first number.

  3. Subtract the new first number from the second to get the original second number.


๐Ÿง  Algorithm

  1. Start

  2. Read two numbers a and b

  3. a = a + b

  4. b = a - b

  5. a = a - b

  6. Print swapped values

  7. End


๐Ÿ’ป C Program Code

#include <stdio.h> int main() { int a, b; // Input from user printf("Enter first number: "); scanf("%d", &a); printf("Enter second number: "); scanf("%d", &b); // Swapping without using temporary variable a = a + b; b = a - b; a = a - b; // Output printf("\nAfter swapping:\n"); printf("First number = %d\n", a); printf("Second number = %d\n", b); return 0; }

๐Ÿ“Œ Example Output

Input

Enter first number: 10 Enter second number: 20

Output

After swapping: First number = 20 Second number = 10

๐Ÿ“ Conclusion

This program demonstrates how two numbers can be swapped without using a temporary variable using simple arithmetic operations. It is commonly asked in C interviews and exams.


๐Ÿ“˜ C Programming Series – What’s Next?

๐Ÿ‘‰ In the next post of this series, we will learn how to Swap Two Numbers (With Temp) with complete explanation and output examples. Stay tuned! ๐Ÿš€


Comments

Popular posts from this blog

⓮C Program to calculate Simple Interest (With Program and Explanation)

9️⃣C Program to Find LCM of Two Numbers (With Program and Explanation)