# Kotlin recursive function: Product of odd numbers in a range

## Kotlin Function: Exercise-6 with Solution

Write a Kotlin recursive function to calculate the product of all odd numbers in a range.

Sample Solution:

Kotlin Code:

fun calculateProductOfOdds(start: Int, end: Int): Long {
if (start > end) {
return 1
}

return if (start % 2 != 0) {
start.toLong() * calculateProductOfOdds(start + 2, end)
} else {
calculateProductOfOdds(start + 1, end)
}
}

fun main() {
val start = 1
val end = 15
val product = calculateProductOfOdds(start, end)
println("Product of odd numbers between \$start and \$end: \$product")
}

Sample Output:

Product of odd numbers between 1 and 15: 2027025

Explanation:

In the above exercise -

• The "calculateProductOfOdds()" function takes the start and end values of the range as parameters. This function recursively calculates the product of odd numbers by checking the current number (starting with start) and determining whether it is odd or even.
• If the current number is odd (i.e., start % 2 != 0), it multiplies the current number with the recursive call to calculateProductOfOdds for the next odd number (start + 2) and continues the recursion.
• In the case of even numbers, calculateProductOfOdds is called with start + 1 to skip to the next odd number.
• The recursion continues until the start exceeds end value. At that point, it returns 1, as 1 multiplied with any number doesn't affect the product.
• In the "main()" function, we define the start and end values of the range (1 and 15, respectively), and then call the "calculateProductOfOdds()" function with these values. It is then printed to the console with the calculated product.

Kotlin Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿