w3resource

Kotlin Program: Calculate the sum of numbers between a given range


Write a Kotlin program to calculate the sum of all numbers between two given numbers.


Pre-Knowledge (Before you start!)

  • Basic Kotlin Syntax.
  • Kotlin Functions.
  • Loops in Kotlin.
  • Range Operator.
  • Variable Initialization.
  • Printing Output.

Hints (Try before looking at the solution!)

  • Define the Function.
  • Initialize a Sum Variable.
  • Use a For Loop.
  • Add Numbers to the Sum.
  • Return the Result.
  • Display the Output.
  • Test with Different Ranges.
  • Common Errors to Avoid:
    • Forgetting the range operator.
    • Misplacing loop boundaries.
    • Not initializing the sum variable correctly.

Sample Solution:

Kotlin Code:

fun main() {
    val start = 15
    val end = 25

    val sum = calculateSum(start, end)
    println("Sum of numbers between $start and $end: $sum")
}

fun calculateSum(start: Int, end: Int): Int {
    var sum = 0

    for (num in start..end) {
        sum += num
    }

    return sum
}

Sample Output:

Sum of numbers between 15 and 25: 220

Explanation:

In the above exercise,

  • In the main() function the variables start and end represent the starting and ending numbers of the range for which we want to calculate the sum.
  • The calculateSum() function takes the start and end values as arguments and returns the sum of all numbers between them.
  • Inside the calculateSum() function, we initialize a variable sum to hold the cumulative sum and set it to 0.
  • We use a for loop to iterate over the numbers from start to end (inclusive) using the range operator ...
  • For each number in the range, we add it to the sum variable.
  • After the loop completes, we return the calculated sum.

Go to:


PREV : Fibonacci series up to a given number.
NEXT : Generate a multiplication table of a number.

Kotlin Editor:


Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.