Write a c program to swap two numbers without using temporary variable

Swapping Two Numbers Without Using Third Variable in C

किसी भी variable मे saved दो numbers को एक तीसरे variable की help से बहुत easily swap किया जा सकता है लेकिन challenge तब आता है जब आपको कहा जाये की तीसरा variable use न करो और दो variable की values को swap करो | इसके लिए maths के simple logic को समझने की जरुरत है | दो variable की values को swap करने के लिए आप addition, multiplication, pointers, XOR or call by reference टेक्निक को use कर सकते है | यहाँ पर हम simple addition and multiplication technique का C program बता रहे है  | 

Swap Number Program C hindi

Swap Number Program

Method 1 (Using Arithmetic Operator + )

#include <stdio.h>

int main() {
int x = 20, y = 10; //Declare x and y variables with fix value
//Maths Logic to swap ‘x’ and ‘y’
x = x + y; // x is now 30
y = x – y; // y is 20
x = x – y; // x replaced and it is 10 now

printf(“After Swapping x and y Values are : x = %d, y = %d”, x, y);

return 0;
}

Method 2 (Using Arithmetic Operators * and /)

#include <stdio.h>
int main() {
int x = 20, y = 10;
   // Maths logic to swap 'x' and 'y' with multiplication and divide operator
  x = x * y;  // x now becomes 200
  y = x / y;  // y becomes 20
  x = x / y;  // x becomes 10
  printf("After Swapping x and y values are : x = %d, y = %d", x, y);
   return 0;
 
Problems with both methods-
1) अगर x or y की value 0 है तो multiplication and division operators का logic fail ho जायेगा and swap function काम नहीं करेगा क्योकि 0 से कुछ भी multiply करो 0 ही आएगा |

2) Addition operator के case मे arithmetic overflow हो सकता है क्योकि अगर x and y की value ज्यादा बड़ी हो तो addition and multiplication दोनों के case मे out of integer range ho जायेगा | 

Vikas Sir Explained it in very easy way – 

One Response

  1. Rahul vishwakarma August 15, 2017

Leave a Reply