In this post, we will learn to code the Kotlin Program to Find the Sum of Natural Numbers Using Recursion. Let’s see the Sum of Natural Numbers using recursion in Kotlin Programming Language.
What are Natural Numbers?
Natural Numbers are a part of the number system. They include all the positive numbers from 1 to infinity.
For example, 1, 2, 3, 4, 5, . . . . , ∞ (infinity) These are Natural Number.
let’s see the Sum of N Natural Numbers where N is 10.
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
Now, let’s see the Sum of Natural Numbers Using Recursion in Kotlin Programming Language.
Kotlin Program to Find the Sum of Natural Numbers Using Recursion
//Kotlin Program to Find the Sum of Natural Numbers Using Recursion import java.util.Scanner; fun sumOfNum(n: Int): Int{ if(n==1) return 1; return n + sumOfNum(n-1); } fun main() { var sc = Scanner(System.`in`); println("Enter the value of N: "); var n = sc.nextInt(); println("The Sum of Natural numbers till $n is"); val ans = sumOfNum(n); println(ans); }
Output
Enter the value of N: 15
The Sum of Natural numbers till 5 is
15
How Does This Program Work?
var sc = Scanner(System.`in`); println("Enter the value of N: "); var n = sc.nextInt();
In this program, first, we have taken the input of the value of N from the user, using the Scanner Class of Java. We import the Scanner Class using import java.util.Scanner;
val ans = sumOfNum(n);
Then, we call the recursive function sumOfNum()
which gives the sum of N natural numbers.
fun sumOfNum(n: Int): Int{ if(n==1) return 1; return n + sumOfNum(n-1); }
In this recursive function, we put the base case as return 1 if N is 1. i.e. Sum of Natural numbers till 1 is 1.
We return the sum of N and call the same function for value N-1. At last, we get the sum of the natural numbers till N in the sum variable in the main function.
This is the Kotlin Program to Find the Sum of Natural Numbers Using Recursion.
Conclusion
I hope after going through this post, you understand how to code Kotlin Program to Find the Sum of Natural Numbers Using Recursion.
If you have any doubt regarding the topic, feel free to contact us in the Comment Section. We will be delighted to help you.
Learn More: