Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
74 views

Example: Sum of Natural Numbers Using Recursion

This document discusses using recursion to calculate the sum of natural numbers. It provides an example C program that defines a recursive sum function to calculate the sum. The sum function calls itself recursively, each time decreasing the number passed in by 1, until the number reaches 0, at which point it returns the current sum. This allows it to build up the total sum across all recursive calls to ultimately return the final sum to the main function. The document also notes that while recursion makes programs more elegant, it uses more memory and is generally slower than an iterative approach using loops.

Uploaded by

Mahbubur Rahman
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views

Example: Sum of Natural Numbers Using Recursion

This document discusses using recursion to calculate the sum of natural numbers. It provides an example C program that defines a recursive sum function to calculate the sum. The sum function calls itself recursively, each time decreasing the number passed in by 1, until the number reaches 0, at which point it returns the current sum. This allows it to build up the total sum across all recursive calls to ultimately return the final sum to the main function. The document also notes that while recursion makes programs more elegant, it uses more memory and is generally slower than an iterative approach using loops.

Uploaded by

Mahbubur Rahman
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Example: Sum of Natural Numbers Using

Recursion
#include​ ​<stdio.h>
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

Initially, the ​sum()​ is called from the ​main()​ function with ​number​ passed as an
argument.
Suppose, the value of ​num​ is 3 initially. During next function call, 2 is passed to
the ​sum()​function. This process continues until ​num​ is equal to 0.

When ​num​ is equal to 0, the if condition fails and the else part is executed
returning the sum of integers to the ​main()​ function.
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​.

You might also like