Kotlin Program to Calculate the Sum of Natural Numbers


In this article, we will understand how to calculate the sum of natural numbers in Kotlin. All possible positive numbers from 1 to infinity are called natural numbers.

Below is a demonstration of the same −

Suppose our input is

1 and 100

The desired output would be −

Sum of natural numbers from 1 to 100 is 3825

Algorithm

  • Step 1 − Start

  • Step 2 − Declare an integers input

  • Step 3 − Define the integers

  • Step 4 − Run a for-loop, add the number with its next number until the upper limit is reached. Store the sum in the variable myResult.

  • Step 5 − Display myResult

  • Step 6 − Stop

Example 1

In this example, we will calculate the Sum of Natural Numbers using a for loop. First, declare and set a variable for input −

val input = 100

Set another variable and initialize to 0. This variable with display the sum later on −

var myResult = 0

Now, use the for loop to calculate the sum of natural numbers −

for (i in 1..input) {
   myResult += i
}

Let us now see the complete example to get the sum of natural numbers using for loop −

fun main() { val input = 100 println("The N value is defined as $input") var myResult = 0 for (i in 1..input) { myResult += i } println("The sum of N natural numbers is $myResult") }

Output

The N value is defined as 100
The sum of N natural numbers is 5050

Example 2

In this example, we will calculate the Sum of Natural Numbers −

fun main() { val input = 100 println("The N value is defined as $input") sum(input) } fun sum(input: Int) { var myResult = 0 for (i in 1..input) { myResult += i } println("The sum of N natural numbers is $myResult") }

Output

The N value is defined as 100
The sum of N natural numbers is 5050

Updated on: 13-Oct-2022

442 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements