Write a program in C++ and python to swap two numbers without using a temporary variable:

By | August 1, 2019

In this program, we will accept two values from the user and then swap their variable name.

C++:

#include<iostream.h>
#include< conio.h>
#include<stdio.h>
#include<math.h>

void main()
{
clrscr();
int num_1,num_2;
cout<<"Enter num_1: ";
cin>>num_1;
cout<<"Enter num_2: ";
cin>>num_2;
num_1= num_1+num_2;
num_2= num_1-num_2;
num_1= num_1-num_2;
cout<<"After swapping\n";
cout<<"The value of num_1 is: "<<num_1<<"\n";
cout<<"The value of num_2 is: "<<num_2;
getch();
}

Output:

Enter num_1: 23
Enter num_2: 43
After swapping
The value of num_1 is: 43
The value of num_2 is: 23

Python:

num_1=int(input("Enter num_1: "))
num_2=int(input("Enter num_2: "))
print("After swapping")
num_1=num_1+num_2
num_2=num_1-num_2
num_1=num_1-num_2
print("The value of num_1 is:",num_1)
print("The value of num_2 is:",num_2)

Output:

Enter num_1: 234
Enter num_2: 543
After swapping
The value of num_1 is: 543
The value of num_2 is: 234

Leave a Reply

Your email address will not be published. Required fields are marked *