Example 1: Kotlin Program to Add Two Dates
Kotlin Program to Add Two Dates .we’ll learn about working with dates in Kotlin. We’ll be looking into Date-related operations such as creating, formatting and manipulating dates.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import java.util.Calendar fun main(args: Array<String>) { val c1 = Calendar.getInstance() val c2 = Calendar.getInstance() val cTotal = c1.clone() as Calendar cTotal.add(Calendar.YEAR, c2.get(Calendar.YEAR)) cTotal.add(Calendar.MONTH, c2.get(Calendar.MONTH) + 1) // Zero-based months cTotal.add(Calendar.DATE, c2.get(Calendar.DATE)) cTotal.add(Calendar.HOUR_OF_DAY, c2.get(Calendar.HOUR_OF_DAY)) cTotal.add(Calendar.MINUTE, c2.get(Calendar.MINUTE)) cTotal.add(Calendar.SECOND, c2.get(Calendar.SECOND)) cTotal.add(Calendar.MILLISECOND, c2.get(Calendar.MILLISECOND)) println("${c1.time} + ${c2.time} = ${cTotal.time}") } |
Example 2: Kotlin Program to Calculate the Power of a Number
Kotlin Program to Calculate the Power of a Number: In this program, base and exponent are assigned values 3 and 4 respectively. Using the while loop, we keep on multiplying the result by base until exponent becomes zero.In this case, we multiply result by base 4 times in total, so result = 1 * 3 * 3 * 3 * 3 = 81.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | fun main(args: Array<String>) { val base = 3 var exponent = 4 var result: Long = 1 while (exponent != 0) { result *= base.toLong() --exponent } println("Answer = $result") } |
Example 3: Kotlin Program to Display Armstrong Numbers Between Intervals Using Function
Kotlin Program to Display Armstrong Numbers Between Intervals Using Function: To find all Armstrong numbers between two integers, check Armstrong() function is created. This function checks whether a number is Armstrong or not.
In the below program, we’ve created a function named checkArmstrong()
which takes a parameter num and returns a boolean value. If the number is Armstrong, it returns true. If not, it returns false.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | fun main(args: Array<String>) { val low = 999 val high = 99999 for (number in low + 1..high - 1) { if (checkArmstrong(number)) print("$number ") } } fun checkArmstrong(num: Int): Boolean { var digits = 0 var result = 0 var originalNumber = num // number of digits calculation while (originalNumber != 0) { originalNumber /= 10 ++digits } originalNumber = num // result contains sum of nth power of its digits while (originalNumber != 0) { val remainder = originalNumber % 10 result += Math.pow(remainder.toDouble(), digits.toDouble()).toInt() originalNumber /= 10 } if (result == num) return true return false } |
Example 4: Kotlin Program to Find Factorial of a Number Using Recursion
Kotlin Program to Find Factorial of a Number Using Recursion: Write a program to find factorial of a given number is a common kotlin program asked in an interview with freshers.The factorial of a non-negative integer n is the product of all positive integers less than or equal to n.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | fun main(args: Array<String>) { val num = 6 val factorial = multiplyNumbers(num) println("Factorial of $num = $factorial") } fun multiplyNumbers(num: Int): Long { if (num >= 1) return num * multiplyNumbers(num - 1) else return 1 } |
Example 5: Kotlin Program to Check Leap Year
Kotlin Program to Check Leap Year : In this program, you’ll learn to check if the given year is a leap year or not in Kotlin. This is checked using an if-else statement and a when statement.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | fun main(args: Array<String>) { val year = 1900 var leap = false if (year % 4 == 0) { if (year % 100 == 0) { // year is divisible by 400, hence the year is a leap year leap = year % 400 == 0 } else leap = true } else leap = false println(if (leap) "$year is a leap year." else "$year is not a leap year.") } |
Example 6: Kotlin Program to Display Prime Numbers Between Intervals Using Function
Kotlin Program to Display Prime Numbers Between Intervals Using Function: Below the program, we’ve created a function named check prime number() which takes a parameter num and returns a boolean value. If the number is prime, it returns true. If not, it returns false. Based on the return value, the number is printed on the screen inside the main() function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | fun main(args: Array<String>) { var low = 20 val high = 50 while (low < high) { if (checkPrimeNumber(low)) print(low.toString() + " ") ++low } } fun checkPrimeNumber(num: Int): Boolean { var flag = true for (i in 2..num / 2) { if (num % i == 0) { flag = false break } } return flag } |
Example 7: Kotlin Program to Reverse a Number
Kotlin Program to Reverse a Number: In this, you will see how to reverse a number in Kotlin. We will learn two different ways to do that. The first method will use one loop and the second method will use a different approach to solve it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | fun main(args: Array<String>) { var num = 1234 var reversed = 0 while (num != 0) { val digit = num % 10 reversed = reversed * 10 + digit num /= 10 } println("Reversed Number: $reversed") } |
Example 8: Kotlin Program to Find ASCII value of a character
Kotlin Program to Find ASCII value of a character : To find the ASCII value of ch, we use a Kotlin’s built-in function called toInt(). This converts a Char value into an Int value. This converted value is then stored in a variable ASCII. Finally, we print the ASCII value using the println() function.
1 2 3 4 5 6 7 8 9 | fun main(args: Array) { val c = 'a' val ascii = c.toInt() println("The ASCII value of $c is: $ascii") } |
Example 9: Kotlin Program to Find all Roots of a Quadratic Equation
Kotlin Program to Find Roots of a Quadratic Equation: The roots of any quadratic equation is given by: x = [-b +/- sqrt(-b^2 – 4ac)]/2a.
Write down the quadratic in the form of ax^2 + bx + c = 0. If the equation is in the form y = ax^2 + bx +c, simply replace the y with 0. This is done because the roots of the equation are the values where the y-axis is equal to 0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | fun main(args: Array<String>) { val a = 2.3 val b = 4 val c = 5.6 val root1: Double val root2: Double val output: String val determinant = b * b - 4.0 * a * c // condition for real and different roots if (determinant > 0) { root1 = (-b + Math.sqrt(determinant)) / (2 * a) root2 = (-b - Math.sqrt(determinant)) / (2 * a) output = "root1 = %.2f and root2 = %.2f".format(root1, root2) } // Condition for real and equal roots else if (determinant == 0.0) { root2 = -b / (2 * a) root1 = root2 output = "root1 = root2 = %.2f;".format(root1) } // If roots are not real else { val realPart = -b / (2 * a) val imaginaryPart = Math.sqrt(-determinant) / (2 * a) output = "root1 = %.2f+%.2fi and root2 = %.2f-%.2fi".format(realPart, imaginaryPart, realPart, imaginaryPart) } println(output) } |
Example 10: Kotlin Program to Display Armstrong Number Between Two Intervals
Kotlin Program to Display Armstrong Number Between Two Intervals: In this program, you’ll learn to display all Armstrong numbers between two given intervals, low and high, in Kotlin.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | fun main(args: Array<String>) { val low = 999 val high = 99999 for (number in low + 1..high - 1) { var digits = 0 var result = 0 var originalNumber = number // number of digits calculation while (originalNumber != 0) { originalNumber /= 10 ++digits } originalNumber = number // result contains sum of nth power of its digits while (originalNumber != 0) { val remainder = originalNumber % 10 result += Math.pow(remainder.toDouble(), digits.toDouble()).toInt() originalNumber /= 10 } if (result == number) print("$number ") } } |
Example 11: Kotlin Program to Round a Number to n Decimal Places
Kotlin Program to Round a Number to n Decimal Places. In the below program, we’ve used format() method to print the given floating-point number num to 4 decimal places.
1 2 3 4 5 6 7 8 9 10 11 12 | import java.math.RoundingMode import java.text.DecimalFormat fun main(args: Array<String>) { val num = 1.23467 val df = DecimalFormat("#.###") df.roundingMode = RoundingMode.CEILING println(df.format(num)) } |
Example 12: Kotlin Program to Check if a String is Numeric
Kotlin Program to Check if a String is Numeric. To check if the string contains numbers only, in the try block, we use Double ‘s parseDouble() method to convert the string to a Double.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import java.lang.Double.parseDouble fun main(args: Array<String>) { val string = "12345s15" var numeric = true try { val num = parseDouble(string) } catch (e: NumberFormatException) { numeric = false } if (numeric) println("$string is a number") else println("$string is not a number") } |
Example 13: Kotlin Program to Count Number of Digits in an Integer
Kotlin Program to Count Number of Digits in an Integer: In this program, while loop is iterated until the test expression num != 0 is evaluated to 0 (false). After the first iteration, num will be divided by 10 and its value will be 345. Then, the count is incremented to 1.
1 2 3 4 5 6 7 8 9 10 11 12 13 | fun main(args: Array<String>) { var count = 0 var num = 1234567 while (num != 0) { num /= 10 ++count } println("Number of digits: $count") } |
Example 14: Kotlin Program to Convert Array to Set HashSet and Vice-Versa
Kotlin Program to Convert Array to Set (HashSet) and Vice-Versa. The collection object has a constructor that accepts a Collection object to initial the value. Since both Set and List are extended the Collection, the conversion is quite straightforward.
1 2 3 4 5 6 7 8 9 10 11 12 | import java.util.* fun main(args: Array<String>) { val array = arrayOf("c", "d", "f") val set = HashSet(Arrays.asList(*array)) println("Set: $set") } |
Example 15: Kotlin Program to Add Two Integers Number
In this program, You will learn how to add two numbers using class and object in Kotlin.
you’ll learn to store and add two integer numbers in Kotlin. After addition, the final sum is displayed on the screen.
1 2 3 4 5 6 7 8 9 10 11 | fun main(args: Array<String>) { val first: Int = 10 val second: Int = 20 val sum = first + second println("The sum is: $sum") } |
Example 16: Kotlin Program to Convert String to Date
Kotlin Program to Convert String to Date.we will learn how to convert a string to a date in Kotlin. We will use the java.util.LocalDate class to convert a string to a Date.LocalDate comes with one static method parse that takes one date string as input and formats it as LocalDate object.
1 2 3 4 5 6 7 8 9 10 11 12 | import java.time.LocalDate import java.time.format.DateTimeFormatter fun main(args: Array<String>) { // Format y-M-d or yyyy-MM-d val string = "2020-07-25" val date = LocalDate.parse(string, DateTimeFormatter.ISO_DATE) println(date) } |
Example 17: Kotlin Program to Sort ArrayList of Custom Objects By Property
Kotlin Program to Sort ArrayList of Custom Objects By Property. For sorting the list with the property, we use the list ‘s sorted with the () method. The sorted with() method takes a comparator to compare that compares the custom property of each object and sorts it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import java.util.* fun main(args: Array<String>) { val list = ArrayList<CustomObject>() list.add(CustomObject("A")) list.add(CustomObject("B")) list.add(CustomObject("C")) list.add(CustomObject("D")) list.add(CustomObject("Aa")) var sortedList = list.sortedWith(compareBy({ it.customProperty })) for (obj in sortedList) { println(obj.customProperty) } } public class CustomObject(val customProperty: String) { } |
Example 18: Kotlin Program to Convert Map HashMap to List
Kotlin Program to Convert Map (HashMap) to List. We can convert key-value pairs into ArrayList or HashMap keys into ArrayList or HashMap values into ArrayList.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import java.util.ArrayList import java.util.HashMap fun main(args: Array<String>) { val map = HashMap<Int, String>() map.put(1, "a") map.put(2, "b") map.put(3, "c") map.put(4, "d") map.put(5, "e") map.put(6, "f") val keyList = ArrayList(map.keys) val valueList = ArrayList(map.values) println("Key List: $keyList") println("Value List: $valueList") } |
Example 19: Kotlin Program to Print an Array
Kotlin Program to Print an Array. In this tutorial, we’ll look into Kotlin array. If you’re new to Kotlin, it’s recommended to go through the Introduction to Kotlin tutorial to ensure that you’re up to speed with this tutorial.
1 2 3 4 5 6 7 8 9 | fun main(args: Array<String>) { val array = intArrayOf(1, 2, 3, 4, 5,6,7) for (element in array) { println(element) } } |
Example 20: Kotlin Program to Calculate Average Using Arrays
Kotlin Program to Calculate Average Using Arrays. In the below program, the numeracy stores the floating-point values whose average is to be found. Then, to calculate the average, we need to first calculate the sum of all elements in the array.
1 2 3 4 5 6 7 8 9 10 11 12 13 | fun main(args: Array<String>) { val numArray = doubleArrayOf(45.3, 67.5, -45.6, 20.34, 33.0, 45.6) var sum = 0.0 for (num in numArray) { sum += num } val average = sum / numArray.size println("The average is: %.2f".format(average)) } |
Example 21: Kotlin Program to Find the Largest Among Three Numbers
Kotlin Program to Find the Largest Among Three Numbers: In this Kotlin programming, we will learn how to find out the largest number among the three. The user will enter the number values, our program will find and print out the result. To compare three numbers and finding out the largest one, we can either implement our own algorithm or we can use Kotlin’s built-in method maxOf.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | fun main(args: Array<String>) { val n1 = -4.5 val n2 = 3.9 val n3 = 2.5 if (n1 >= n2 && n1 >= n3) println("$n1 is the largest number.") else if (n2 >= n1 && n2 >= n3) println("$n2 is the largest number.") else println("$n3 is the largest number.") } |
Example 22: Kotlin Program to Display Characters from A to Z using a loop
Kotlin Program to Display Characters from A to Z using a loop: In this program, you’ll learn to print English alphabets using while loop in Kotlin. You’ll also learn to print only uppercased and lowercased alphabets.
1 2 3 4 5 6 7 8 9 10 11 | fun main(args: Array<String>) { var c: Char c = 'A' while (c <= 'Z') { print("$c ") ++c } } |
Example 23: Kotlin Program to Check Armstrong Number
Kotlin Program to Check Armstrong Number: In this program, you’ll learn to check whether a given number is Armstrong number or not. You’ll learn to do this by using a while loop in Kotlin.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | fun main(args: Array<String>) { val number = 371 var originalNumber: Int var remainder: Int var result = 0 originalNumber = number while (originalNumber != 0) { remainder = originalNumber % 10 result += Math.pow(remainder.toDouble(), 3.0).toInt() originalNumber /= 10 } if (result == number) println("$number is an Armstrong number.") else println("$number is not an Armstrong number.") } |
Example 24: Kotlin Program to Print an Integer Entered by the User
Kotlin Program to Print an Integer Entered by the User: In this program, you’ll learn to print an integer entered by the user. The integer is stored in a variable and printed to the screen using nextInt() and println() functions respectively.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import java.util.Scanner fun main(args: Array<String>) { // Creates a reader instance which takes // input from standard input - keyboard val reader = Scanner(System.`in`) print("Enter a number: ") // nextInt() reads the next integer from the keyboard var integer:Int = reader.nextInt() // println() prints the following line to the output screen println("You entered: $integer") } |
Example 25: Kotlin Program to Remove All Whitespaces from a String
Kotlin Program to Remove All Whitespaces from a String. In the below program, we use String’s replaceAll() method to remove and replace all whitespaces in the string sentence.
1 2 3 4 5 6 7 8 9 | fun main(args: Array<String>) { var sentence = "T his is b ett er." println("Original sentence: $sentence") sentence = sentence.replace("\\s".toRegex(), "") println("After replacement: $sentence") } |
Example 26: Kotlin Program to Compare Strings
Kotlin Program to Compare Strings. Compares this object with the specified object for order. Returns zero if this object is equal to the specified another object, a negative number if it’s less than other, or a positive number if it’s greater than other.
1 2 3 4 5 6 7 8 9 10 11 12 | fun main(args: Array<String>) { val style = "Bold" val style2 = "Bold" if (style == style2) println("Equal(=)") else println("Not Equal") } |
Example 27: Kotlin Program to Compute Quotient and Remainder
Kotlin Program to Compute Quotient and Remainder: In the above program Kotlin Program to Compute Quotient and Remainder, two numbers 25 (dividend) and 4 (divisor) are stored in the dividend and division numbers respectively. Unlike Java, they are automatically assigned type Int in Kotlin.
1 2 3 4 5 6 7 8 9 10 11 12 13 | fun main(args: Array<String>) { val dividend = 25 val divisor = 4 val quotient = dividend / divisor val remainder = dividend % divisor println("Quotient = $quotient") println("Remainder = $remainder") } |
Example 28: Kotlin Program to Multiply to Matrix Using Multi-dimensional Arrays
Kotlin Program to Multiply to Matrix Using Multi-dimensional Arrays: In this program, you’ll learn to multiply two matrices using multi-dimensional arrays in Kotlin.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | fun main(args: Array<String>) { val r1 = 2 val c1 = 3 val r2 = 3 val c2 = 2 val firstMatrix = arrayOf(intArrayOf(6, -1, 5), intArrayOf(2, 0, 6)) val secondMatrix = arrayOf(intArrayOf(7, 4), intArrayOf(-2, 0), intArrayOf(0, 4)) // Mutliplying Two matrices val product = Array(r1) { IntArray(c2) } for (i in 0..r1 - 1) { for (j in 0..c2 - 1) { for (k in 0..c1 - 1) { product[i][j] += firstMatrix[i][k] * secondMatrix[k][j] } } } // Displaying the result println("Product of two matrices is: ") for (row in product) { for (column in row) { print("$column ") } println() } } |
Example 29: Kotlin Program to Convert Character to String and Vice-Versa
Kotlin Program to Convert Character to String and Vice-Versa. If you want to convert the String to a char array, try calling. toCharArray() on the String. If the string is 1 character long, just take that character.
1 2 3 4 5 6 7 8 9 10 | fun main(args: Array<String>) { val ch = 'c' val st = Character.toString(ch) // Alternatively // st = String.valueOf(ch); println("The string is: $st") } |
Example 30: Kotlin Program to Find Largest Element in an Array
Kotlin Program to Find Largest Element in an Array. Note that it is the kth largest element in the sorted order, not the kth distinct element. In the below program, we store the first element of the array in the variable largest.Then, the largest is used to compare other elements in the array. If any number is greater than the largest, the largest is assigned the number.
1 2 3 4 5 6 7 8 9 10 11 12 13 | fun main(args: Array<String>) { val numArray = doubleArrayOf(23.4, -34.5, 50.0, 33.5, 55.5, 43.7, 5.7, -66.5) var largest = numArray[0] for (num in numArray) { if (largest < num) largest = num } println("Largest element = %.2f".format(largest)) } |
Example 31: Kotlin Program to Convert List ArrayList to Array and Vice-Versa
Kotlin Program to Convert List (ArrayList) to Array and Vice-Versa. In the below program, we have an array list of strings list.
1 2 3 4 5 6 7 8 9 10 11 12 | import java.util.* fun main(args: Array<String>) { val array = arrayOf("c", "d") val list = Arrays.asList(*array) println(list) } |
Example 32: Kotlin Code To Create a Pyramid and Pattern
Kotlin Code To Create a Pyramid and Pattern. In this program, you will learn to create a pyramid, half pyramid, inverted pyramid, Pascal’s triangle, and Floyd’s triangle sing control statements in Kotlin.
1 2 3 4 5 6 7 8 9 10 11 12 | fun main(args: Array<String>) { val rows = 6 for (i in 1..rows) { for (j in 1..i) { print("* ") } println() } } |
Example 33: Kotlin Program to Lookup Enum by String value
Kotlin Program to Lookup enum by the String value. we ‘ll deep dive into Kotlin enums.
With the evolution of programming languages, the usage and application of enums have also advanced.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | enum class TextStyle { BOLD, ITALICS, UNDERLINE, STRIKETHROUGH } fun main(args: Array<String>) { val style = "Bold" val textStyle = TextStyle.valueOf(style.toUpperCase()) println(textStyle) } |
Example 34: Kotlin Program to Sort a Map By Values
Kotlin Program to Sort a Map By Values. In order to sort HashMap by values, you can first create a Comparator, which can compare two entries based on values.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | fun main(args: Array<String>) { var capitals = hashMapOf<String, String>() capitals.put("pak", "islamabbad") capitals.put("India", "New Delhi") capitals.put("United States", "Washington") capitals.put("England", "London") capitals.put("Australia", "abcd ") val result = capitals.toList().sortedBy { (_, value) -> value}.toMap() for (entry in result) { print("Key: " + entry.key) println(" Value: " + entry.value) } } |
Example 35: Kotlin Program to Get Current Working Directory
Kotlin Program to Get Current Working Directory .the program begins by testing for command-line arguments. If a command-line argument is available, the command-line argument is used for the Path.
1 2 3 4 5 6 7 8 9 | fun main(args: Array<String>) { val path = System.getProperty("user.dir") println("Working Directory = $path") } |
Example 36: Kotlin Program to Find the Sum of Natural Numbers using Recursion
Kotlin Program to Find the Sum of Natural Numbers using Recursion: Find the last digit of a number using modular division by 10. Add the last digit found above to the sum variable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | fun main(args: Array<String>) { val number = 20 val sum = addNumbers(number) println("Sum = $sum") } fun addNumbers(num: Int): Int { if (num != 0) return num + addNumbers(num - 1) else return num } |
Example 37: Kotlin Program to Generate Multiplication Table
Kotlin Program to Generate Multiplication Table: In this program, you’ll learn about how to generate the multiplication table of a given number. This is done by using a for and a while loop in Kotlin.
1 2 3 4 5 6 7 8 9 10 | fun main(args: Array<String>) { val num = 5 for (i in 1..10) { val product = num * i println("$num * $i = $product") } } |
Example 38: Kotlin Program to calculate the power using recursion
Kotlin Program to calculate the power using recursion?Recursion is a powerful technique, it allows us to define a complex problem in terms of solving a simpler version.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | fun main(args: Array<String>) { val base = 3 val powerRaised = 4 val result = power(base, powerRaised) println("$base^$powerRaised = $result") } fun power(base: Int, powerRaised: Int): Int { if (powerRaised != 0) return base * power(base, powerRaised - 1) else return 1 } |
Example 39: Kotlin Program to Find Factorial of a Number
Kotlin Program to find Factorial of a Given Number : In this program, you’ll learn to find the factorial of a number using for and while loop in Kotlin. You’ll also learn to use ranges to solve this problem.
1 2 3 4 5 6 7 8 9 10 11 12 | fun main(args: Array<String>) { val num = 10 var factorial: Long = 1 for (i in 1..num) { // factorial = factorial * i; factorial *= i.toLong() } println("Factorial of $num = $factorial") } |
Example 40: Kotlin Program to Multiply two Matrices by Passing Matrix to a Function
Kotlin Program to Multiply two Matrices by Passing Matrix to a Function: In this program, you’ll learn to multiply two matrices using a function in Kotlin. For matrix multiplication to take place, the number of columns of the first matrix must be equal to the number of rows of the second matrix.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | fun main(args: Array<String>) { val r1 = 2 val c1 = 3 val r2 = 3 val c2 = 2 val firstMatrix = arrayOf(intArrayOf(3, -2, 5), intArrayOf(3, 0, 4)) val secondMatrix = arrayOf(intArrayOf(2, 3), intArrayOf(-9, 0), intArrayOf(0, 4)) // Mutliplying Two matrices val product = multiplyMatrices(firstMatrix, secondMatrix, r1, c1, c2) // Displaying the result displayProduct(product) } fun multiplyMatrices(firstMatrix: Array, secondMatrix: Array, r1: Int, c1: Int, c2: Int): Array { val product = Array(r1) { IntArray(c2) } for (i in 0..r1 - 1) { for (j in 0..c2 - 1) { for (k in 0..c1 - 1) { product[i][j] += firstMatrix[i][k] * secondMatrix[k][j] } } } return product } fun displayProduct(product: Array) { println("Product of two matrices is: ") for (row in product) { for (column in row) { print("$column ") } println() } } |
Example 41: Kotlin Program to Display Prime Numbers Between Two Intervals
Kotlin Program to Display Prime Numbers Between Two Intervals : In this program, you’ll learn to display prime numbers between two given intervals, low and high. You’ll learn to do this using a while and a for loop in Kotlin.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | fun main(args: Array<String>) { var low = 20 val high = 50 while (low < high) { var flag = false for (i in 2..low / 2) { // condition for nonprime number if (low % i == 0) { flag = true break } } if (!flag) print("$low ") ++low } } |
Example 42: Kotlin Program to Multiply two Floating-Point Numbers
Kotlin Program to Multiply two Floating-Point Numbers: In the above program Kotlin Program to Multiply two Floating-Point Numbers, we have two floating-point numbers 1.5f and 2.0f stored in variables first and second respectively.
1 2 3 4 5 6 7 8 9 10 11 | fun main(args: Array<String>) { val first = 1.5f val second = 2.0f val product = first * second println("The product is: $product") } |
Example 43: Kotlin Program to Calculate Difference Between Two Time Periods
Kotlin Program to Calculate Difference Between Two Time Periods. The Time class has a constructor that initializes the value of hours, minutes and seconds.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | class Time(internal var hours: Int, internal var minutes: Int, internal var seconds: Int) fun main(args: Array<String>) { val start = Time(11, 22, 55) val stop = Time(9, 12, 15) val diff: Time diff = difference(start, stop) print("TIME DIFFERENCE: ${start.hours}:${start.minutes}:${start.seconds} - ") print("${stop.hours}:${stop.minutes}:${stop.seconds} ") print("= ${diff.hours}:${diff.minutes}:${diff.seconds}") } fun difference(start: Time, stop: Time): Time { val diff = Time(0, 0, 0) if (stop.seconds > start.seconds) { --start.minutes start.seconds += 60 } diff.seconds = start.seconds - stop.seconds if (stop.minutes > start.minutes) { --start.hours start.minutes += 60 } diff.minutes = start.minutes - stop.minutes diff.hours = start.hours - stop.hours return diff } |
Example 44: Kotlin Program to Check Whether a Number can be Expressed as Sum of Two Prime Numbers
Kotlin Program to Check Whether a Number can be Expressed as Sum of Two Prime Numbers: In this program, you’ll learn to check whether a given number can be expressed as a sum of two prime numbers or not.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | fun main(args: Array<String>) { val number = 34 var flag = false for (i in 2..number / 2) { // condition for i to be a prime number if (checkPrime(i)) { // condition for n-i to be a prime number if (checkPrime(number - i)) { // n = primeNumber1 + primeNumber2 System.out.printf("%d = %d + %d\n", number, i, number - i) flag = true } } } if (!flag) println("$number cannot be expressed as the sum of two prime numbers.") } // Function to check prime number fun checkPrime(num: Int): Boolean { var isPrime = true for (i in 2..num / 2) { if (num % i == 0) { isPrime = false break } } return isPrime } |
Example 45: Kotlin Program to Convert OutputStream to String
Kotlin Program to Convert OutputStream to String. This is done using the stream’s write() method. Then, we simply convert the OutputStream to a final string using String ‘s constructor which takes a byte array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import java.io.* fun main(args: Array<String>) { val stream = ByteArrayOutputStream() val line = "Hello are you there!" stream.write(line.toByteArray()) val finalString = String(stream.toByteArray()) println(finalString) } |
Example 46: Kotlin Program to Find Transpose of a Matrix
Kotlin Program to Find Transpose of a Matrix: The transpose of a matrix is simply a flipped version of the original matrix. We can transpose a matrix by switching its rows with its columns.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | fun main(args: Array<String>) { val r1 = 2 val c1 = 3 val r2 = 3 val c2 = 2 val firstMatrix = arrayOf(intArrayOf(3, -2, 5), intArrayOf(3, 0, 4)) val secondMatrix = arrayOf(intArrayOf(2, 3), intArrayOf(-9, 0), intArrayOf(0, 4)) // Mutliplying Two matrices val product = multiplyMatrices(firstMatrix, secondMatrix, r1, c1, c2) // Displaying the result displayProduct(product) } fun multiplyMatrices(firstMatrix: Array, secondMatrix: Array, r1: Int, c1: Int, c2: Int): Array { val product = Array(r1) { IntArray(c2) } for (i in 0..r1 - 1) { for (j in 0..c2 - 1) { for (k in 0..c1 - 1) { product[i][j] += firstMatrix[i][k] * secondMatrix[k][j] } } } return product } |
Example 47: Kotlin Program to Reverse a Sentence Using Recursion
Kotlin Program to Reverse a Sentence Using Recursion. Recursive function (reverse) takes string pointer (str) as input and calls itself with the next location to passed pointer (str+1).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | fun main(args: Array<String>) { val sentence = "Go work" val reversed = reverse(sentence) println("The reversed sentence is: $reversed") } fun reverse(sentence: String): String { if (sentence.isEmpty()) return sentence return reverse(sentence.substring(1)) + sentence[0] } |
Example 48: Kotlin Program to Join Two Lists
Kotlin Program to Join Two Lists. You will see how to merge two or more collections into one. However, before we move ahead, we need to understand the difference between mutable and immutable types.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import java.util.ArrayList fun main(args: Array<String>) { val list1 = ArrayList<String>() list1.add("a") val list2 = ArrayList<String>() list2.add("b") val joined = ArrayList<String>() joined.addAll(list1) joined.addAll(list2) println("list1: $list1") println("list2: $list2") println("joined: $joined") } |
Example 49: Kotlin Program to Make a Simple Calculator Using switch Case
Kotlin Program to Make a Simple Calculator Using switch Case:In this program, you’ll learn to make a simple calculator using when expression in Kotlin. This calculator would be able to add, subtract, multiply and divide two numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import java.util.* fun main(args: Array<String>) { val reader = Scanner(System.`in`) print("Enter two numbers: ") // nextDouble() reads the next double from the keyboard val first = reader.nextDouble() val second = reader.nextDouble() print("Enter an operator (+, -, *, /): ") val operator = reader.next()[0] val result: Double when (operator) { '+' -> result = first + second '-' -> result = first - second '*' -> result = first * second '/' -> result = first / second // operator doesn't match any case constant (+, -, *, /) else -> { System.out.printf("Error! operator is not correct") return } } System.out.printf("%.1f %c %.1f = %.1f", first, operator, second, result) } |
Example 50: Kotlin Program to Convert InputStream to String
Kotlin Program to Convert InputStream to String. In this program, you’ll learn to convert the input stream to a string using InputStreamReader in Kotlin.In the below program, the input stream is created from a String and stored in a variable stream.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import java.io.* fun main(args: Array<String>) { val stream = ByteArrayInputStream("Hello are you Here!".toByteArray()) val sb = StringBuilder() var line: String? val br = BufferedReader(InputStreamReader(stream)) line = br.readLine() while (line != null) { sb.append(line) line = br.readLine() } br.close() println(sb) } |
Kotlin 51: Kotlin Program to Add Two Matrix Using Multi-dimensional Arrays
Kotlin Program to Add Two Matrix Using Multi-dimensional Arrays: In the below program, the two matrices are stored in 2d array, namely first matrix and second matrix. We’ve also defined the number of rows and columns and stored them in variables rows and columns respectively.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | fun main(args: Array<String>) { val rows = 2 val columns = 3 val firstMatrix = arrayOf(intArrayOf(2, 3, 4), intArrayOf(5, 2, 3)) val secondMatrix = arrayOf(intArrayOf(-4, 5, 3), intArrayOf(5, 6, 3)) // Adding Two matrices val sum = Array(rows) { IntArray(columns) } for (i in 0..rows - 1) { for (j in 0..columns - 1) { sum[i][j] = firstMatrix[i][j] + secondMatrix[i][j] } } // Displaying the result println("Sum of two matrices is: ") for (row in sum) { for (column in row) { print("$column ") } println() } } |
Example 52: Kotlin Program to Convert Binary Number to Octal and vice versa
Kotlin Program to Convert Binary Number to Octal and vice versa. Conversion binary to decimal and vice versa: We multiply each binary digit by its weighted position, and add each of the weighted value together.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | fun main(args: Array<String>) { val binary: Long = 101001 val octal = convertBinarytoOctal(binary) println("$binary in binary = $octal in octal") } fun convertBinarytoOctal(binaryNumber: Long): Int { var binaryNumber = binaryNumber var octalNumber = 0 var decimalNumber = 0 var i = 0 while (binaryNumber.toInt() != 0) { decimalNumber += (binaryNumber % 10 * Math.pow(2.0, i.toDouble())).toInt() ++i binaryNumber /= 10 } i = 1 while (decimalNumber != 0) { octalNumber += decimalNumber % 8 * i decimalNumber /= 8 i *= 10 } return octalNumber } |
Example 53: Kotlin Program to Append Text to an Existing File
Kotlin Program to Append Text to an Existing File. Learn how to append text to file in Kotlin using Kotlin’s extension function, File.appendText() a single line of code, with an example program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import java.io.IOException import java.nio.file.Files import java.nio.file.Paths import java.nio.file.StandardOpenOption fun main(args: Array<String>) { val path = System.getProperty("user.dir") + "\\src\\test.txt" val text = "Added text" try { Files.write(Paths.get(path), text.toByteArray(), StandardOpenOption.APPEND) } catch (e: IOException) { } } |
Example 54: Kotlin Program to Convert File to Byte Array and Vice-Versa
Kotlin Program to Convert File to byte array and Vice-Versa. Before we convert a file to byte array and vice-versa, we assume we have a file named test.txt in our src folder. In the below program, we store the path to the file in the variable path.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import java.io.IOException import java.nio.file.Files import java.nio.file.Paths import java.util.Arrays fun main(args: Array<String>) { val path = System.getProperty("user.dir") + "\\src\\test.txt" try { val encoded = Files.readAllBytes(Paths.get(path)) println(Arrays.toString(encoded)) } catch (e: IOException) { } } |
Example 55: Kotlin Program to Find G.C.D Using Recursion
Kotlin Program to Find G.C.D Using Recursion: In this program, you’ll learn to find GCD of two numbers in Kotlin. … The HCF or GCD of two integers is the largest integer that can exactly divide both numbers (without a remainder).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | fun main(args: Array<String>) { val n1 = 366 val n2 = 60 val hcf = hcf(n1, n2) println("G.C.D of $n1 and $n2 is $hcf.") } fun hcf(n1: Int, n2: Int): Int { if (n2 != 0) return hcf(n2, n1 % n2) else return n1 } |
Example 56: Kotlin Program to Create String from Contents of a File
Kotlin Program to Create String from Contents of a File. Kotlin has inherited Java’s fidgety (but very flexible) way of doing I/O, but with some simplifying extra features.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import java.io.File fun main(args: Array<String>) { val fileName = "data.txt" var file = File(fileName) // create a new file val isNewFileCreated :Boolean = file.createNewFile() if(isNewFileCreated){ println("$fileName is created successfully.") } else{ println("$fileName already exists.") } // try creating a file that already exists val isFileCreated :Boolean = file.createNewFile() if(isFileCreated){ println("$fileName is created successfully.") } else{ println("$fileName already exists.") } } |
Example 57: Kotlin Program to Convert Milliseconds to Minutes and Seconds
Kotlin Program to Convert Milliseconds to Minutes and Seconds. Basically when you want to check the exact time taken to execute a program then you may need to calculate the time.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import java.util.concurrent.TimeUnit fun main(args: Array<String>) { val milliseconds: Long = 100000000 // long minutes = (milliseconds / 1000) / 60; val minutes = TimeUnit.MILLISECONDS.toMinutes(milliseconds) // long seconds = (milliseconds / 1000); val seconds = TimeUnit.MILLISECONDS.toSeconds(milliseconds) println("$milliseconds Milliseconds = $minutes minutes") println("Or") println("$milliseconds Milliseconds = $seconds seconds") } |
Example 58: Kotlin Program to Display Factors of a Number
Kotlin Program to Display Factors of a Number: In the below program, the number whose factors are to be found is stored in the variable number (60). The for loop is iterated from 1 to number.
1 2 3 4 5 6 7 8 9 10 11 12 | fun main(args: Array<String>) { val number = 60 print("Factors of $number are: ") for (i in 1..number) { if (number % i == 0) { print("$i ") } } } |
Example 59: Kotlin Program to Find GCD of two Numbers
Kotlin Program to Find GCD of two Numbers: The HCF or GCD of two integers is the largest integer that can exactly divide both numbers (without a remainder). This is done by using a while loop with the help of the if-else statement.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | fun main(args: Array<String>) { val n1 = 81 val n2 = 153 var gcd = 1 var i = 1 while (i <= n1 && i <= n2) { // Checks if i is factor of both integers if (n1 % i == 0 && n2 % i == 0) gcd = i ++i } println("G.C.D of $n1 and $n2 is $gcd") } |
Example 60: Kotlin Program to Convert a Stack Trace to a String
Kotlin Program to Convert a Stack Trace to a String. In the catch block, we use StringWriter and PrintWriter to print any given output to a string. We then print the stack trace using the printStackTrace() method of the exception and write it in the writer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import java.io.PrintWriter import java.io.StringWriter fun main(args: Array<String>) { try { val division = 0 / 0 } catch (e: ArithmeticException) { val sw = StringWriter() e.printStackTrace(PrintWriter(sw)) val exceptionAsString = sw.toString() println(exceptionAsString) } } |
Example 61: Kotlin Program to Convert Octal Number to Decimal and vice versa
Kotlin Program to Convert Octal Number to Decimal and vice-versa: We multiply each binary digit by its weighted position, and add each of the weighted value together.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | fun main(args: Array<String>) { val decimal = 78 val octal = convertDecimalToOctal(decimal) println("$decimal in decimal = $octal in octal") } fun convertDecimalToOctal(decimal: Int): Int { var decimal = decimal var octalNumber = 0 var i = 1 while (decimal != 0) { octalNumber += decimal % 8 * i decimal /= 8 i *= 10 } return octalNumber } |
Example 62: Kotlin Program to Concatenate Two Arrays
Kotlin Program to Concatenate Two Arrays. In the above program, we’ve two integer arrays array1 and array2. In order to combine (concatenate) two arrays, we find its length stored in aLen and bLen respectively. Then, we create a new integer array result with length Alen + ben.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import java.util.Arrays fun main(args: Array<String>) { val array1 = intArrayOf(2, 3, 4) val array2 = intArrayOf(5, 6, 7) val aLen = array1.size val bLen = array2.size val result = IntArray(aLen + bLen) System.arraycopy(array1, 0, result, 0, aLen) System.arraycopy(array2, 0, result, aLen, bLen) println(Arrays.toString(result)) } |
Example 63: Kotlin Program to Calculate Standard Deviation
Kotlin Program to Calculate Standard Deviation: I want to write a method that counts the standard deviation from the provided numbers.this program calculates the standard deviation of an individual series using arrays.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | fun main(args: Array<String>) { val numArray = doubleArrayOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0) val SD = calculateSD(numArray) System.out.format("Standard Deviation = %.6f", SD) } fun calculateSD(numArray: DoubleArray): Double { var sum = 0.0 var standardDeviation = 0.0 for (num in numArray) { sum += num } val mean = sum / 10 for (num in numArray) { standardDeviation += Math.pow(num - mean, 2.0) } return Math.sqrt(standardDeviation / 10) } |
Example 64: Kotlin Program to Convert Byte Array to Hexadecimal
Kotlin Program to Convert Byte Array to Hexadecimal. To convert byte array to a hex value, we loop through each byte in the array and use String ‘s format().
1 2 3 4 5 6 7 8 9 10 11 12 | fun main(args: Array<String>) { val bytes = byteArrayOf(12, 2, 15, 11) for (b in bytes) { val st = String.format("%02X", b) print(st) } } |
Example 65: Kotlin Program to Get Current Date-TIme
Kotlin Program to Get Current Date/TIme.Kotlin doesn’t have its own date and time implementation. Kotlin and Java are “compatible”, they use the same virtual machine and that’s why they can share their classes.Therefore, Kotlin uses Java classes for date and time. Date – The Date class from the java. util package was the first attempt at storing date and time in Java.
1 2 3 4 5 6 7 8 9 10 | import java.time.LocalDateTime fun main(args: Array<String>) { val current = LocalDateTime.now() println("Current Date and Time is: $current") } |
Example 66: Kotlin Program to Add Two Integers
Kotlin Program to Add Two Integers: In this program, You will learn how to add two numbers in Kotlin.you’ll learn to store and add two integer numbers in Kotlin. After addition, the final sum is displayed on the screen.
1 2 3 4 5 6 7 8 9 10 11 | fun main(args: Array<String>) { val first: Int = 10 val second: Int = 20 val sum = first + second println("The sum is: $sum") } |
Example 67: Kotlin Program to Find Factorial of a Number Using Recursion
Kotlin Program to Find Factorial of a Number Using Recursion: The factorial of a negative number doesn’t exist. And the factorial of 0 is 1.You will learn to find the factorial of a number using recursion in this example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | fun main(args: Array<String>) { val num = 6 val factorial = multiplyNumbers(num) println("Factorial of $num = $factorial") } fun multiplyNumbers(num: Int): Long { if (num >= 1) return num * multiplyNumbers(num - 1) else return 1 } |
Example 68: Kotlin Program to Convert Binary Number to Decimal and vice-versa
Kotlin Program to Convert Binary Number to Decimal and vice-versa: We multiply each binary digit by its weighted position, and add each of the weighted value together.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | fun main(args: Array<String>) { val num: Long = 110110111 val decimal = convertBinaryToDecimal(num) println("$num in binary = $decimal in decimal") } fun convertBinaryToDecimal(num: Long): Int { var num = num var decimalNumber = 0 var i = 0 var remainder: Long while (num.toInt() != 0) { remainder = num % 10 num /= 10 decimalNumber += (remainder * Math.pow(2.0, i.toDouble())).toInt() ++i } return decimalNumber } |
Example 69: Kotlin Program to Find the Sum of Natural Numbers using Recursion
Kotlin Program to Find the Sum of Natural Numbers using Recursion: The positive numbers 1, 2, 3… are known as natural numbers. The program below takes a positive integer from the user and calculates the sum up to the given number.
You can find the sum of natural numbers using the loop as well. However, you will learn to solve this problem using recursion here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | fun main(args: Array<String>) { val number = 20 val sum = addNumbers(number) println("Sum = $sum") } fun addNumbers(num: Int): Int { if (num != 0) return num + addNumbers(num - 1) else return num } |
Example 70: Kotlin Program to Swap Two Numbers
Kotlin Program to Swap Two Numbers: In this article, we will learn various methods to swap two numbers in Kotlin. We will also study various methods and block like run, also, with and destructing declarations in Kotlin.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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 second second = temporary println("--After swap--") println("First number = $first") println("Second number = $second") } |
Example 71: Kotlin Program to Check Whether a Number is Even or Odd
Kotlin Program to Check Whether a Number is Even or Odd: In this program, you’ll learn to check if a number entered by a user is even or odd. This will be done using two variants of if…else in Kotlin.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import java.util.Scanner fun main(args: Array<String>) { var n: Int var sc = Scanner(System.`in`) print("Enter a Number :") n = sc.nextInt() if (n % 2 == 0) { println("$n is Even") } else { println("$n is Odd") } } |
Example 72: Kotlin Program to Check Whether a Number can be Expressed as Sum of Two Prime Numbers
Kotlin Program to Check Whether a Number can be Expressed as Sum of Two Prime Numbers: In this program, you’ll learn to check whether a given number can be expressed as a sum of two prime numbers or not. This is done with the help of loops and break statements in Kotlin.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | fun main(args: Array<String>) { val number = 34 var flag = false for (i in 2..number / 2) { // condition for i to be a prime number if (checkPrime(i)) { // condition for n-i to be a prime number if (checkPrime(number - i)) { // n = primeNumber1 + primeNumber2 System.out.printf("%d = %d + %d\n", number, i, number - i) flag = true } } } if (!flag) println("$number cannot be expressed as the sum of two prime numbers.") } // Function to check prime number fun checkPrime(num: Int): Boolean { var isPrime = true for (i in 2..num / 2) { if (num % i == 0) { isPrime = false break } } return isPrime } |
Example 73: Kotlin Program to Check Whether an Alphabet is Vowel or Consonant
Kotlin Program to Check Whether an Alphabet is Vowel or Consonant: To check whether ch is vowel or not, we check if ch is any of: (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) . Unlike Java, this is done using if..else expression as opposed to the if..else statement. If the alphabet is any of the vowels, “vowel” string is returned. Else, “consonant” string is returned.
1 2 3 4 5 6 7 8 9 10 | fun main(args: Array<String>) { val ch = 'i' val vowelConsonant = if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') "vowel" else "consonant" println("$ch is $vowelConsonant") } |
Example 74: Kotlin Program to Display Fibonacci Series
Kotlin Program to Display Fibonacci Series: In this program, you’ll learn to display the Fibonacci series in Kotlin using for and while loops. You’ll learn to display the series up to a specific term or a number.
The Fibonacci series is a series where the next term is the sum of the previous two terms. The first two terms of the Fibonacci sequence are 0 followed by 1.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | fun main(args: Array<String>) { val n = 10 var t1 = 0 var t2 = 1 print("First $n terms: ") for (i in 1..n) { print("$t1 + ") val sum = t1 + t2 t1 = t2 t2 = sum } } |
Example 75: Kotlin Program to Make a Simple Calculator Using Switch Case
Kotlin Program to Make a Simple Calculator Using Switch Case: In this program, you’ll learn to make a simple calculator using when expression in Kotlin. This calculator would be able to add, subtract, multiply and divide two numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import java.util.* fun main(args: Array<String>) { val reader = Scanner(System.`in`) print("Enter two numbers: ") // nextDouble() reads the next double from the keyboard val first = reader.nextDouble() val second = reader.nextDouble() print("Enter an operator (+, -, *, /): ") val operator = reader.next()[0] val result: Double when (operator) { '+' -> result = first + second '-' -> result = first - second '*' -> result = first * second '/' -> result = first / second // operator doesn't match any case constant (+, -, *, /) else -> { System.out.printf("Error! operator is not correct") return } } System.out.printf("%.1f %c %.1f = %.1f", first, operator, second, result) } |
Example 76: Kotlin Program to Check Whether a Number is Prime or Not
Kotlin Program to Check Whether a Number is Prime or Not: In this program, You will learn how to check number is prime or not in Kotlin.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | fun main(args: Array<String>) { val num = 29 var flag = false for (i in 2..num / 2) { // condition for nonprime number if (num % i == 0) { flag = true break } } if (!flag) println("$num is a prime number.") else println("$num is not a prime number.") } |
Example 77: Kotlin Program to Calculate the Sum of Natural Numbers
Kotlin Program to Calculate the Sum of Natural Numbers: In this program, you’ll learn to calculate the sum of natural numbers using for loop and while loop in Kotlin. You’ll also see how ranges can be helpful for solving the problem.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | fun main(args: Array<String>) { val num = 100 var sum = 0 for (i in 1..num) { // sum = sum+i; sum += i } println("Sum = $sum") } |