C++ Program to Swap two numbers without using third variable














































C++ Program to Swap two numbers without using third variable



Description
Swap() is used to interchange the number without using another variable.
The logic is simple:
Let's consider two numbers: x and y
Adding these two numbers and then subtracting the sum from x gives y or from x which gives us x
Program Code:
#include <iostream> using namespace std; void Swap (int &a,int &b) { cout<<"Number 1 :"<<a; cout<<"\nNumber 2 :"<<b; a=a+b; b=a-b; a=a-b; cout<<"\nNew Number 1 :"<<a; cout<<"\nNew Number 2 :"<<b; } int main() { int a=4,b=3; Swap(a,b); return 0; }
Output:
Number 1: 4
Number 2: 3
New Number : 3
New Number : 4

More Articles of Avikrit Kohli:

Name Views Likes
C++ Program To Insert At Bottom Of Stack Using Recursion 1363 1
Python Program To Extract Data From Excel 699 1
C++ Program To Reverse Line In Text File 4379 1
C++ Program To Implement Simpsons 3/8th rule 1172 2
C++ Program To Read Text File Word By Word 4331 1
Program To Display Level Order Transversal Using Queue 572 1
C++ Program To Find Length Of Linked List 2643 1
C++ Program To Search An Element Recursively In Linked List 1172 1
C++ Program To Delete Element In Array At Particular Position 1504 1
C++ Program To Find The Minimum In Subarray Of Size k Using Deque 656 2
To Find Negation of Number Using Operator Overloading 925 1
C++ Program To Reverse Linked List Recursively 3003 1
C++ Program To Sort Two Arrays And Inserting Result In Third array 1250 1
To Sort Array Of Integers Using Bubble,Insertion And Selection Sort 1560 1
C++ Program To Implement Stack Using Arrays 2801 1
C++ Program To Balance Parenthesis Using Stack 2127 1
Python Program To Add Source Code of A Webpage 661 1
C++ Program To Insert Element In Array At Given Position 2164 1
C++ Program To Reverse Each Word In Text File 1156 1
C++ Program to Swap two numbers without using third variable 682 2
C++ Program To Reverse String Without Using String Functions 1304 20
C++ Program To Reverse Stack Recursively 1527 1
C++ Program To Find Sum Of Fibonacci Series Using Recursion 3645 1
C++ Program To Create And Display Text File 968 1
C++ Program To Find Root Using Bisection Method 5631 1
C++ Program To Implement Queue Using Array 4813 2
C++ Program To Sort Stack Recursively 1973 1
C++ Program To Create Tower Of Hanoi 6897 1

Comments