w3resource

Kotlin recursive function: Find the nth term of arithmetic sequence

Kotlin Function: Exercise-7 with Solution

Write a Kotlin recursive function to find the nth term of the arithmetic sequence.

Sample Solution:

Kotlin Code:

fun findNthTermArithmetic(x: Int, d: Int, n: Int): Int {
    if (n == 1) {
        return x
    }

    return findNthTermArithmetic(x + d, d, n - 1)
}

fun main() {
    val x = 5
    val d = 3
    val n = 7
    val nthTerm = findNthTermArithmetic(x, d, n)
    println("The $n-th term of the arithmetic sequence is: $nthTerm")
}

Sample Output:

The 7-th term of the arithmetic sequence is: 23

Explanation:

In the above exercise -

  • The "findNthTermArithmetic()" function takes three parameters: x (the first term of the sequence), d (the common difference), and n (the term number to find).
  • The function uses recursion to find the nth term of the arithmetic sequence. If n is 1, it means we have reached the first term, so the function returns x.
  • Otherwise, it calculates the next term by adding the common difference d to the previous term x. It calls itself recursively with the updated values of x (the next term), d (the common difference), and n - 1 (to find the next term).
  • The recursion continues until n reaches 1, at which point the first term x is returned.
  • In the "main()" function, we define the values of x (5), d (3), and n (7) to find the 7th term of the arithmetic sequence. We then call the "findNthTermArithmetic()" function with these values and store the result in the nthTerm variable. Finally, we print the result to the console.

Kotlin Editor:


Previous: Product of odd numbers in a range.
Next: Check prime number.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/kotlin-exercises/recursion-function/kotlin-recursion-function-exercise-7.php