Want to find sum of natural numbers using R? Use the following code to find sum of natural numbers using R. To solve this problem, a recursive function calculate_sum()
function is created.
1 2 3 4 5 6 7 |
calculate_sum() <- function(n) { if(n <= 1) { return(n) } else { return(n + calculate_sum(n-1)) } } |
Output
1 2 |
> calculate_sum(7) [1] 28 |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.