How to sum of natural numbers using recursion? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to sum of natural numbers using recursion?

What are the difference between for loop and recursion

29th Dec 2020, 5:29 AM
Mike
4 Answers
+ 1
Mike Recursion is a function which calls it self until an return statement is incountered. In C and C++ we use an if statement or the function will recurse infinitly. If you are a beginner with Recursion use a print to prevent any problems before it's too late. Loops: Faster than recursion. Easy to use. Used widely. Recursion: Slower than loops. Uses more memory. Hard to understand. Recursion is the simplest algorithm in some programming situation but loops are better. Happy Recursion!
29th Dec 2020, 7:58 AM
Muzammil
Muzammil - avatar
+ 2
Here's a link to the course section covering recursion. Loops are covered earlier, you'll get to it soon (if you haven't already) https://www.sololearn.com/learn/CPlusPlus/1641/?ref=app
29th Dec 2020, 5:55 AM
Ipang
29th Dec 2020, 5:55 AM
Alphin K Sajan
Alphin K Sajan - avatar
0
To calculate the sum of natural numbers using recursion in C, we follow a simple approach where the problem is divided into smaller problems, and those smaller problems are solved individually. The base condition in this recursive function will be when the number n is 1, in which case the function should return 1. Otherwise, the function calls itself with n-1 and adds n to the result of that call. This process repeats until the base condition is met. #include <stdio.h> // Function declaration int sumOfNaturalNumbers(int n); int main() { int n, sum; printf("Enter a positive integer: "); scanf("%d", &n); sum = sumOfNaturalNumbers(n); printf("Sum = %d", sum); return 0; } // Function to find the sum of natural numbers using recursion int sumOfNaturalNumbers(int n) { if (n != 0) return n + sumOfNaturalNumbers(n - 1); // Recursive call else return n; } For further details and more programs, visit Sum of Natural Numbers Using Recursion in C (https://teachingbee.in/blog/sum-of-natural-numbers-using-recursion-in-c/).
2nd Mar 2024, 10:55 AM
WorkAnything Pvt. Limited
WorkAnything Pvt. Limited - avatar