1. Introduction
Kotlin continues to gain traction as a preferred language for Android development and server-side applications. It offers many modern programming concepts out-of-the-box, making it a joy to work with. In today's blog, we'll walk through a straightforward program: subtracting two numbers entered by the user in Kotlin.
2. Program Overview
Our Kotlin program will:
1. Prompt the user to input two numbers.
2. Read these numbers from the console.
3. Subtract the second number from the first.
4. Display the result to the user.
3. Code Program
import java.util.Scanner
fun main() {
// Create a Scanner object to read user input from the console
val reader = Scanner(System.in)
// Ask the user to provide the first number
print("Enter the first number: ")
// Read and store the first number
val num1 = reader.nextDouble()
// Ask the user to provide the second number
print("Enter the second number: ")
// Read and store the second number
val num2 = reader.nextDouble()
// Subtract the second number from the first
val difference = num1 - num2
// Display the result
println("The difference between $num1 and $num2 is: $difference")
}
Output:
Enter the first number: 10.5 Enter the second number: 4.5 The difference between 10.5 and 4.5 is: 6.0
4. Step By Step Explanation
1. Scanner Object: The Scanner class from the java.util package helps in capturing input from users. We've created an instance of this class named reader.
2. Input for First Number: Using the print function, we guide the user to enter their first number. Immediately after, reader.nextDouble() fetches this input, which we save in the variable num1.
3. Input for Second Number: In the same way, we direct the user to enter their second number and store it in the variable num2.
4. Subtraction Operation: We find the difference between the two numbers with the subtraction operation (num1 - num2) and store the result in the difference variable.
5. Displaying the Result: Using the println function, the computed difference is shown back to the user.
Through this basic Kotlin program, we get a feel for user interactions, arithmetic operations, and Kotlin's concise syntax. This example serves as a foundation for more complex operations and applications in the Kotlin world.
Comments
Post a Comment
Leave Comment