How to calculate the sum of all odd numbers between two given numbers in Kotlin
How to calculate the sum of all odd numbers between two given numbers in Kotlin.
Here's a step-by-step tutorial on how to calculate the sum of all odd numbers between two given numbers in Kotlin:
- Start by defining a function that takes two parameters representing the lower and upper limits of the range:
fun sumOfOddNumbers(lower: Int, upper: Int): Int {
// implementation goes here
}
- Inside the function, initialize a variable to hold the sum:
fun sumOfOddNumbers(lower: Int, upper: Int): Int {
var sum = 0
// implementation goes here
}
- Use a loop to iterate over the numbers within the range:
fun sumOfOddNumbers(lower: Int, upper: Int): Int {
var sum = 0
for (num in lower..upper) {
// implementation goes here
}
return sum
}
- Check if the current number is odd using the modulo operator (%):
fun sumOfOddNumbers(lower: Int, upper: Int): Int {
var sum = 0
for (num in lower..upper) {
if (num % 2 != 0) {
// implementation goes here
}
}
return sum
}
- If the number is odd, add it to the sum:
fun sumOfOddNumbers(lower: Int, upper: Int): Int {
var sum = 0
for (num in lower..upper) {
if (num % 2 != 0) {
sum += num
}
}
return sum
}
- Finally, call the function with the desired lower and upper limits and print the result:
fun main() {
val lower = 1
val upper = 10
val sum = sumOfOddNumbers(lower, upper)
println("The sum of odd numbers between $lower and $upper is: $sum")
}
Putting it all together, here's the complete code:
fun sumOfOddNumbers(lower: Int, upper: Int): Int {
var sum = 0
for (num in lower..upper) {
if (num % 2 != 0) {
sum += num
}
}
return sum
}
fun main() {
val lower = 1
val upper = 10
val sum = sumOfOddNumbers(lower, upper)
println("The sum of odd numbers between $lower and $upper is: $sum")
}
When you run the program, it will calculate the sum of all odd numbers between the given lower and upper limits and display the result.