1. Introduction
In this blog post, we're exploring a classic Kotlin program: swapping two numbers without a temporary variable.
2. Program Overview
This Kotlin program will:
1. Request the user to input two numbers.
2. Capture the numbers provided by the user.
3. Swap the numbers without using a temporary or third variable.
4. Display the swapped values to the user.
3. Code Program
import java.util.Scanner
fun main() {
// Initialize the Scanner class for user input
val reader = Scanner(System.in)
// Ask the user to input the first number
print("Enter the first number: ")
val a = reader.nextInt()
// Prompt the user for the second number
print("Enter the second number: ")
val b = reader.nextInt()
// Swap the numbers without using a temporary variable
a = a + b
b = a - b
a = a - b
// Display the swapped values to the user
println("After swapping: First number = $a, Second number = $b")
}
Output:
Enter the first number: 5 Enter the second number: 10 After swapping: First number = 10, Second number = 5
4. Step By Step Explanation
1. Scanner Initialization: To capture user input, we make use of the Scanner class from the java.util package. The reader instance represents our scanner object.
2. Capture User Input: Using the print function, the program asks the user for two integer values, storing them in a and b.
3. Number Swapping Technique: Instead of relying on a third variable for swapping, we exploit arithmetic operations:
- The sum of a and b is stored in a.- By subtracting the new a (which is the sum) by the original b, we get the original a value, which we then assign to b.- Finally, by subtracting the new a (still the sum) by the new b (the original a), we derive the original b value, which we assign back to a. The swapping is now complete.
4. Showcase Swapped Values: The program then uses the println function to display the swapped values to the user.
Comments
Post a Comment
Leave Comment