+ 1
How to sum of natural numbers using recursion?
What are the difference between for loop and recursion
4 Réponses
+ 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!
+ 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
+ 2
post your attempt to get help
https://www.sololearn.com/Discuss/1914674/?ref=apphttps://www.sololearn.com/Discuss/2132208/?ref=app
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/).