Kotlin Basic Programs

 




1) Program to Add Two Numbers

Code:
fun main(args: Array<String>) {

    val first: Int = 10
    val second: Int = 20

    val sum = first + second

    println("The sum is: $sum")
}

2) Find ASCII Value of a Character

Code:
fun main(args: Array) {

    val c = 'a'
    val ascii = c.toInt()

    println("The ASCII value of $c is: $ascii")
}


3) Program to Swap Two Numbers using the temporary variable

Code:
fun main(args: Array<String>) {

    var first = 1.20f
    var second = 2.45f

    println("--Before swap--")
    println("First number = $first")
    println("Second number = $second")

    // Value of first is assigned to temporary
    val temporary = first

    // Value of second is assigned to first
    first = second

    // Value of temporary (which contains the initial value of first) is assigned to the second
    second = temporary

    println("--After swap--")
    println("First number = $first")
    println("Second number = $second")
}


4) Program to Swap Two Numbers Without Using Temporary Variable

Code:
fun main(args: Array<String>) {

    var first = 12.0f
    var second = 24.5f

    println("--Before swap--")
    println("First number = $first")
    println("Second number = $second")

    first = first - second
    second = first + second
    first = second - first

    println("--After swap--")
    println("First number = $first")
    println("Second number = $second")
}


5) Program To Check a Number is Even or Odd

Code:
import java.util.*

fun main(args: Array<String>) {

    val reader = Scanner(System.`in`)

    print("Enter a number: ")
    val num = reader.nextInt()

    val evenOdd = if (num % 2 == 0) "even" else "odd"

    println("$num is $evenOdd")
}


AJ Blogs

Hello everyone, My name Arth and I like to write about what I learn. Follow My Website - https://sites.google.com/view/aj-blogs/home

Post a Comment

Previous Post Next Post
Best Programming Books

Facebook

AJ Facebook
Checkout Our Facebook Page
AJ Blogs
Checkout Our Instagram Page