Home »
Kotlin »
Kotlin Programs »
Kotlin Basic Programs
Kotlin program to find sum of natural numbers from 1 to N using recursion
Kotlin | Sum of the natural numbers: Here, we are going to learn how to find the sum of the natural numbers from 1 to N (given number) using recursion in Kotlin programming language?
Submitted by IncludeHelp, on April 27, 2020
Kotlin - Find sum of natural numbers from 1 to N using recursion
Given a number (num), we have to find the sum of the natural numbers from 1 to num.
Example:
Input:
num = 5
Output:
1+2+3+4+5 = 15
Program to find sum of natural numbers from 1 to N using recursion in Kotlin
package com.includehelp.basic
import java.util.*
//function to calculate sum of natural number using recursion
fun addSum(number:Int):Int{
return if (number > 0) number + addSum(number - 1) else 0
}
//Main Function entry Point of Program
fun main(args: Array<String>) {
//Input Stream
val scanner = Scanner(System.`in`)
//input integer number
print("Enter Number : ")
val num: Int = scanner.nextInt()
//Call function to find out sum of all numbers up to given number
var sum= addSum(num)
//Print Sum
println("Sum of All Natural Numbers up to num are : $sum")
}
Output
Run 1:
Enter Number : 99
Sum of All Natural Numbers up to 99 are : 4950
---
Run 2:
Enter Number : 999
Sum of All Natural Numbers up to 999 are : 499500