84
Program to swap two numbers without using the third variable
This program is to swap/exchange two numbers without using the third number in the way as given below:
Example: Suppose, there are two numbers 25 and 23.
Let
X= 25 (First number), Y= 23 (second number) Swapping Logic: X = X + Y = 25 +23 = 48 Y = X - Y = 48 - 23 = 25 X = X -Y = 48 - 25 = 23 and the numbers are swapped as X =23 and Y =25.
Algorithm
- STEP 1: START
- STEP 2: ENTER x, y
- STEP 3: PRINT x, y
- STEP 4: x = x + y
- STEP 5: y= x – y
- STEP 6: x =x – y
- STEP 7: PRINT x, y
- STEP 8: END
Java Program
Output:
Enter the value of x and y 23 43 before swapping numbers: 23 43 After swapping: 43 23
C Program
Output:
Enter the value of x and y? 13 22 before swapping numbers: 13 22 After swapping: 22 13
C# Program
Output:
Enter the value of x and y 213 432 before swapping numbers: 213 432 After swapping: 432 213
Python Program
Output:
Enter the value of x? 12 Enter the value of y? 24 before swapping numbers: 12 24 After swapping: 24 12
PHP Program
Output:
Enter the value of x 55 Enter the value of y 46 before swapping numbers: 55 46 After swapping 46 55
Next Topic#