Home » Kotlin

Program to design a simple calculator in Kotlin

In this program, we will create a simple calculator program with basic operation like addition, subtraction, multiplication and divide in Kotlin programming language.
Submitted by Aman Gautam, on November 26, 2017

This is a very simple program that you may already have made in other programming language like C, C++, Python etc. but this program will make you familiar with Kotlin language.

/**
 * Created by Aman gautam on 25-Nov-17.
 */
fun main(args:Array<String>){
    println("Basic Calculator using Kotlin!")
    println("Enter two values ")
    print("a = ")
    var a=readLine()!!.toDouble()
    print("b = ")
    var b=readLine()!!.toDouble()
    println("1. Addition \n2. Substraction \n3. Multiplication \n4. Divide")
    print("Enter Choice : ")
    var ch= readLine()!!.toInt()
    print("Result : ")
    when(ch){
        1 -> print("a+b = ${a+b}")
        2 -> print("a-b = ${a-b}")
        3 -> print("a*b = ${a*b}")
        4 -> print("a/b = ${a/b}")
        else -> print("Wrong Choice")
    }
}

This program takes two input a and b. The function readLine() is used to take user input and then input is converted to Double data type so that we can get accurate and precise results.The !! operator is used so that the input is not null. There are 4 choices, after selecting any choice the control passes to when block (similar to switch block). The switch block processes the parameter ‘ch’ and according to thatwe get desired output.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.