Kotlin program to reverse a string recursively

Published by admin on

Introduction :

In this kotlin programming tutorial, we will learn how to reverse a string recursively in kotlin. The program will take the string from the user and reverse it.
We will use one separate method and call it recursively to reverse the string.

Algorithm :

The algorithm we are using is like below :

1. Ask the user to enter a string. Read and store it in a variable.
2. Pass the string to a different function.
3. Call this function recursively and add the first character to the end of the final string.
4. Keep adding the current character to the end to build the final reverse string.
5. Print out the string.

Kotlin program :

import java.util.Scanner

fun main(args: Array) {
    //1
    val scanner = Scanner(System.`in`)
    
    //2
    println("Enter the string : ")
    var str = scanner.next()

    //3
    println(reverseStr(str))

}

//4
fun reverseStr(str: String): String{
    //5
    if(str.isEmpty())
        return str 
    //6
    return reverseStr(str.substring(1)) + str[0]
}

kotlin reverse string recursively

Explanation :

The commented numbers in the above program denote the step numbers below :

1. Create one Scanner object to read the user input data.
2. Ask the user to enter a string. Read the string and store it in str variable.
3. Call one different function reverseStr and print out the result.
4. reverseStr function takes one string as a parameter. It returns one String i.e. the reversed string.
5. Inside the function, check if the current string is empty or not. If empty, return the same string.
6. Else, call the reverseStr function again recursively. This time we are passing the substring starting from the second character. The final character we are adding to the end of the final string. This process will keep the start character adding to the end of the string on each step.

Sample Output :

Enter the string :
this
siht

Enter the string :
Hello
olleH

Enter the string :
world
dlrow

Enter the string :
universe
esrevinu

kotlin reverse string recursively
You might also like :

Categories: kotlin

Leave a Reply

Your email address will not be published. Required fields are marked *