w3resource

Kotlin program: Arithmetic operations on two numbers


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

Sample Solution:


Pre-Knowledge (Before you start!)

  • Basic Kotlin Syntax.
  • Kotlin Functions.
  • Command-Line Arguments.
  • Type Conversion.
  • Arithmetic Operations.
  • Conditional Statements.
  • Error Handling.
  • String Interpolation.

Hints (Try before looking at the solution!)

  • Define the main() Function.
  • Check Input Count.
  • Convert Inputs to Numbers.
  • Validate Conversion.
  • Perform Arithmetic Operations.
  • Display Results.
  • Handle Errors Gracefully.
  • Test with Different Inputs.
  • Common Errors to Avoid:
    • Forgetting to check args size.
    • Not handling invalid inputs properly.
    • Misplacing operators or parentheses.

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.

Go to:


PREV : User input and display.
NEXT : Check if a number is even or odd.

Kotlin Editor:


Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.