Java From Beginner To Advanced

0% completed

Previous
Next
Swapping Two Elements

Problem Statement

Write a Java program to swap the values of two variables. For instance, if variable a holds the value 5 and variable b holds the value 10, after swapping, a should hold 10 and b should hold 5.

Examples

Example 1:

  • Input: a = 5, b = 10
  • Output: a = 10, b = 5
  • Justification: Values of variable a and b are swapped.

Example 2:

  • Input: a = 3.14, b = 2.71
  • Output: a = 2.71, b = 3.14
  • Justification: Values of variable a and b are swapped.

Step-by-Step Algorithm

Swapping two variables using a temporary variable involves the following steps:

  1. Initialize Variables:
    • Let a and b be the two variables to be swapped.
  2. Use a Temporary Variable:
    • Create a temporary variable temp to hold the value of a.
  3. Swap Values:
    • Assign the value of b to a.
    • Assign the value stored in temp to b.
  4. Result:
    • The values of a and b are now swapped.

Code

Below is the Java code that demonstrates how to swap two variables using a temporary variable.

Java
Java

. . . .

Explanation:

  1. Example 1: Swapping Integers

    • Before Swap:
      • a is initialized to 5.
      • b is initialized to 10.
    • Swapping Process:
      • A temporary variable temp stores the value of a (temp = 5).
      • a is assigned the value of b (a = 10).
      • b is assigned the value stored in temp (b = 5).
    • After Swap:
      • a holds 10.
      • b holds 5.
  2. Example 2: Swapping Doubles

    • Before Swap:
      • x is initialized to 3.14.
      • y is initialized to 2.71.
    • Swapping Process:
      • A temporary variable tempDouble stores the value of x (tempDouble = 3.14).
      • x is assigned the value of y (x = 2.71).
      • y is assigned the value stored in tempDouble (y = 3.14).
    • After Swap:
      • x holds 2.71.
      • y holds 3.14.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next