Swap two numbers
C Programming
#include<stdio.h>
int main() {
int a,b,t;
printf("Enter any two numbers: ");
scanf("%d%d",&a,&b);
t = a;
a = b;
b = t;
printf("a = %d \t b = %d",a,b);
}
C++ Programming
#include<iostream>
using namespace std;
int main() {
int a,b,t;
cout << "Enter any two numbers: ";
cin >> a >> b;
t = a;
a = b;
b = t;
cout << a << "\t" << b;
return 0;
}
Java
import java.util.Scanner;
class Swap {
public static void main(String args[]) {
int a,b,t;
Scanner sc = new Scanner(System.in);
System.out.print("Enter any two numbers: ");
a = sc.nextInt();
b = sc.nextInt();
t = a;
a = b;
b = t;
System.out.println("a = "+a+" \t b = "+b);
}
}
Go Lang
package main
import "fmt"
func main() {
var a,b,t int32
fmt.Print("Enter any two numbers: ")
fmt.Scan(&a,&b)
t = a
a = b
b = t
fmt.Println(a," \t ",b)
}
PHP
<?php
if(isset($_POST['sub'])) {
$a = $_POST['num1'];
$b = $_POST['num2'];
$t = $a;
$a = $b;
$b = $t;
echo $a."\t".$b;
}
?>
/**
* Note: In the above program, It is assumed that a form is created with two number fields which have * names num1 and num2 respectively.
*/
Other Tips
Swap without using a temporary variable.
a = a + b;
b = a - b;
a = a - b;
a = a * b;
b = a / b;
a = a / b;
a = a ^ b;
b = a ^ b;
a = a ^ b;
Note:
- In the above program snippet, ^ (XOR) operator, which is a bitwise operator and only allowed in the programming languages in which bitwise operators are allowed.
- Using XOR ( ^ ) operator, if the numbers are too large and nearly close to the endpoint of the available range, still this method works for swapping and the outcome doesn't go beyond the range as it is possible to loose precision in sum and product methods.
Swap of 3 numbers
t = a;
a = b;
b = c;
c = t;
a = a + b + c;
c = a - b - c;
b = a - b - c;
a = a - b - c;
a = a * b * c;
c = a / b / c;
b = a / b / c;
a = a / b / c;
a = a ^ b ^c
c = a ^ b ^c
b = a ^ b ^c
a = a ^ b ^c
Comments