Sum of Natural Numbers Using Recursion
C Programming Language Recursion in c (Article) Recursion in c (Program)
865Program:
#include int sum(int n); int main() { int number, result; printf("Enter a positive integer: "); scanf("%d", &number); result = sum(number); printf("sum=%d", result); } int sum(int num) { if (num!=0) return num + sum(num-1); // sum() function calls itself else return num; }
Output:
Enter a positive integer: 3 6
Explanation:
Advantages and Disadvantages of Recursion
Recursion makes program elegant and cleaner. All algorithms can be defined recursively which makes it easier to visualize and prove.
If the speed of the program is vital then, you should avoid using recursion. Recursions use more memory and are generally slow. Instead, you can use loop.
This Particular section is dedicated to Programs only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.