Computer Science, asked by doctorsunidhi7635, 1 year ago

Write a program for swapping if two variables with out using third variable?

Answers

Answered by kushal2002
0

Method 1 (Using Arithmetic Operators)

The idea is to get sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from sum.

C++

// C++ Program to swap two numbers  without 

// using temporary variable

#include <bits/stdc++.h>

using namespace std;

  

int main()

{

    int x = 10, y = 5;

  

    // Code to swap 'x' and 'y'

    x = x + y; // x now becomes 15

    y = x - y; // y becomes 10

    x = x - y; // x becomes 5

    cout<<"After Swapping: x ="<<x<<", y="<<y;

}

  

// This code is contributed by mohit kumar. 

C

Java

Python 3

C#

PHP

Output :

After Swapping: x = 5, y = 10

Similar questions