Program to swap two numbers

Program to swap two numbers

  • Write a program to swap two numbers in C
  • Write a program to swap two numbers in C++
  • Write a program to swap two numbers in Python
  • Write a program to swap two numbers in PHP
  • Write a program to swap two numbers in Java
  • Write a program to swap two numbers in Java Script
  • Write a program to swap two numbers in C#

Explanation:

When two numbers are swapped, their values are changed. Programming can accomplish this in a number of methods, including bitwise XOR, arithmetic operations, and temporary variables.

Using a Temporary Variable

  • The simplest and most commonly used method.

temp = a

a = b

b = temp

Using Arithmetic Operations (Addition and Subtraction)

  • No extra variable is needed.
  • Be careful with integer overflow in some languages.

a = a + b

b = a - b

a = a - b

Using Arithmetic Operations (Multiplication and Division)

  • Only works if neither number is zero.

a = a * b

b = a / b

a = a / b

Using Bitwise XOR

  • Efficient and doesn’t require a temporary variable.
  • Works for integers.

a = a ^ b

b = a ^ b

a = a ^ b

Program to find quotient and remainder of number

#include <stdio.h>

int main() {
    int a = 5, b = 10;
    printf("Before swapping: a = %d, b = %d\n", a, b);

    // Using a temporary variable
    int temp = a;
    a = b;
    b = temp;

    printf("After swapping: a = %d, b = %d\n", a, b);

    return 0;
}

#include <iostream>

int main() {
    int a = 5, b = 10;
    std::cout << "Before swapping: a = " << a << ", b = " << b << std::endl;

    // Using a temporary variable
    int temp = a;
    a = b;
    b = temp;

    std::cout << "After swapping: a = " << a << ", b = " << b << std::endl;

    return 0;
}

a = 5
b = 10
print(f"Before swapping: a = {a}, b = {b}")

# Using a temporary variable
temp = a
a = b
b = temp

print(f"After swapping: a = {a}, b = {b}")

<?php
$a = 5;
$b = 10;
echo "Before swapping: a = $a, b = $b\n";

// Using a temporary variable
$temp = $a;
$a = $b;
$b = $temp;

echo "After swapping: a = $a, b = $b\n";
?>

public class Main {
    public static void main(String[] args) {
        int a = 5, b = 10;
        System.out.println("Before swapping: a = " + a + ", b = " + b);

        // Using a temporary variable
        int temp = a;
        a = b;
        b = temp;

        System.out.println("After swapping: a = " + a + ", b = " + b);
    }
}

let a = 5;
let b = 10;
console.log(`Before swapping: a = ${a}, b = ${b}`);

// Using a temporary variable
let temp = a;
a = b;
b = temp;

console.log(`After swapping: a = ${a}, b = ${b}`);

using System;

class Program {
    static void Main() {
        int a = 5, b = 10;
        Console.WriteLine($"Before swapping: a = {a}, b = {b}");

        // Using a temporary variable
        int temp = a;
        a = b;
        b = temp;

        Console.WriteLine($"After swapping: a = {a}, b = {b}");
    }
}

List of All Programs