Kotlin recursive function: Find the nth term of arithmetic sequence
Write a Kotlin recursive function to find the nth term of the arithmetic sequence.
Pre-Knowledge (Before You Start!)
Before solving this exercise, you should understand these concepts:
- Arithmetic Sequence: A sequence of numbers where each term is obtained by adding a fixed value (common difference) to the previous term.
- Recursive Function: A function that calls itself with a modified argument until it reaches a base case.
- Base Case: The condition where recursion stops, preventing infinite loops.
- Mathematical Formula: The nth term of an arithmetic sequence is given by x + (n-1) * d.
- Recursive Approach: Instead of using the formula directly, recursion is used to find each term step by step.
Hints (Try Before Looking at the Solution!)
Here are some hints to help you solve the problem:
- Hint 1: Use recursion to calculate each term of the sequence step by step.
- Hint 2: The base case occurs when n == 1, in which case return the first term x.
- Hint 3: In each recursive step, add the common difference d to the current term and decrease n by 1.
- Hint 4: The recursion will stop once it reaches the first term (n = 1), returning the computed value.
- Hint 5: Try solving a small example manually before implementing the recursive function.
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics