Write a program to swap two numbers.
Example 1:
Input:a=10,b=24
Output:a=24,b=10
Approach 1: Using the third variable
Java
public class SwapTwoNumber {public static void main(String[] args) {int a = 10;int b = 6;swapWithThirdVariable(a, b);}private static void swapWithThirdVariable(int a, int b) {int c = b;b = a;a = c;System.out.println("a=" + a + "\nb=" + b);}}
C++
#include <bits/stdc++.h>using namespace std;//function to swap two varibalesvoid swapTwoNumber(int &a,int &b){int temp=a;a=b;b=temp;}int main(){int a=10,b=24;cout<<"Numbers before swap\n";cout<<"a = "<<a<<" b = "<<b<<"\n";swapTwoNumber(a,b);cout<<"Numbers after swap\n";cout<<"a = "<<a<<" b = "<<b<<"\n";return 0;}
Approach 2: Without using the third variable(using '+' and '-' operator)
Java
public class SwapTwoNumber {public static void main(String[] args) {int a = 10;int b = 6;swapWithThirdVariable(a, b);swapWithoutThirdVariable(a, b);}private static void swapWithoutThirdVariable(int a, int b) {a = a + b;b = a - b;a = a - b;System.out.println("a=" + a + "\nb=" + b);}}
C++
#include <bits/stdc++.h>using namespace std;//function to swap two varibales//without using third variablevoid swapTwoNumber(int &a,int &b){a=a+b;b=a-b;a=a-b;}int main(){int a=10,b=24;cout<<"Numbers before swap\n";cout<<"a = "<<a<<" b = "<<b<<"\n";swapTwoNumber(a,b);cout<<"Numbers after swap\n";cout<<"a = "<<a<<" b = "<<b<<"\n";return 0;}
Approach 3: Without using a third variable (using '*' and '/' operator)
Java
public class SwapTwoNumber {public static void main(String[] args) {int a = 10;int b = 6;swapWithoutThirdVariableMul(a, b);}private static void swapWithoutThirdVariableMul(int a, int b) {a = a * b;b = a / b;a = a / b;System.out.println("a=" + a + "\nb=" + b);}}
C++
#include <bits/stdc++.h>using namespace std;//function to swap two varibales//without using third variablevoid swapTwoNumber(int &a,int &b){a=a*b;b=a/b;a=a/b;}int main(){int a=10,b=24;cout<<"Numbers before swap\n";cout<<"a = "<<a<<" b = "<<b<<"\n";swapTwoNumber(a,b);cout<<"Numbers after swap\n";cout<<"a = "<<a<<" b = "<<b<<"\n";return 0;}
No comments:
Post a Comment