w3resource

Kotlin program: Arithmetic operations on two numbers

Kotlin Basic: Exercise-5 with Solution

Write a Kotlin program to perform addition, subtraction, multiplication and division of two numbers.

Sample Solution:

Kotlin Code:

fun main(args: Array<String>) {
    if (args.size >= 2) {
        val number1 = args[0].toDoubleOrNull()
        val number2 = args[1].toDoubleOrNull()

        if (number1 != null && number2 != null) {
            val sum = number1 + number2
            val difference = number1 - number2
            val product = number1 * number2
            val quotient = number1 / number2

            println("Sum: $sum")
            println("Difference: $difference")
            println("Product: $product")
            println("Quotient: $quotient")
        } else {
            println("Invalid input. Please enter valid numbers.")
        }
    } else {
        println("Insufficient number of arguments. Please provide two numbers as command-line arguments.")
    }
}

Sample Output:

Arguments: 12 10
Sum: 22.0
Difference: 2.0
Product: 120.0
Quotient: 1.2

Explanation:

In the above exercise -

  • The program checks if the args array has at least two elements using args.size >= 2.
  • If there are sufficient command-line arguments, it proceeds with the number conversion and calculations.
  • If the conversion is successful, it performs the addition, subtraction, multiplication, and division operations.
  • If the conversion fails or the required number of arguments is not provided, it displays appropriate error messages.

Kotlin Editor:


Previous: User input and display.
Next: Check if a number is even or odd.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/kotlin-exercises/basic/kotlin-basic-exercise-5.php