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
Program to find sum of natural numbers from 1 to N using recursion in Kotlin
Output
need an explanation for this answer? contact us directly to get an explanation for this answer