Python/C/C++/JAVA

Basic Practice Programs with Code and Concept

By D.S

Swap two numbers

In this example, we're going to discuss how to swap two numbers in programming using two different techniques. The first method involves using a temporary variable to store the value of one number while we switch it with the other. This is a straightforward approach and works well for smaller projects or when you're just starting out with programming. The second technique involves using arithmetic operations to manipulate the values of the two numbers without needing a temporary variable. This can be more efficient for larger programs where memory usage becomes important, but it does require a bit more experience with programming concepts and syntax. Hopefully, by learning both methods, you'll have some new tools under your belt for tackling future coding challenges!

(a.) C Code

#include <stdio.h>

    int main() {
        int a = 5, b = 10, temp;

        printf("Before swapping: a = %d, b = %d
", a, b);

        // Swapping logic using a temporary variable
        temp = a;
        a = b;
        b = temp;

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

        return 0;
    }
Output:-
Before swapping: a = 5, b = 10
After swapping: a = 10, b = 5

(b.) C++ Code

#include <iostream>

    using namespace std;

    int main() {
        int a = 5, b = 10, temp;

        cout << "Before swapping: a = " << a << ", b = " << b << endl;

        // Swapping logic using a temporary variable
        temp = a;
        a = b;
        b = temp;

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

        return 0;
    }
Output:-
Before swapping: a = 5, b = 10
After swapping: a = 10, b = 5

(c.) Python Code

a = 5
    b = 10

    print("Before swapping: a =", a, ", b =", b)

    # Swapping logic without using a temporary variable
    a, b = b, a

    print("After swapping: a =", a, ", b =", b)
Output:-
Before swapping: a = 5, b = 10
After swapping: a = 10, b = 5

(d.) Java Code

public class SwapNumbers {
        public static void main(String[] args) {
            int a = 5, b = 10, temp;

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

            // Swapping logic using a temporary variable
            temp = a;
            a = b;
            b = temp;

            System.out.println("After swapping: a = " + a + ", b = " + b);
        }
    }
Output:-
Before swapping: a = 5, b = 10
After swapping: a = 10, b = 5