In: Computer Science
#include <stdio.h>
int sum(int n); //prototype
int main() {
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
printf("sum = %d", result);
return 0;
}
int sum(int n) {
if (n != 0)
return n + sum(n-1);
else
return n;
}
What does the code above do?
Implementation of given program;
Screenshots
Output:
The given code calculates the sum of all natural numbers from 1 to given number where number is given by the user. The given code uses recursive function to calculate the sum of all natural numbers.
i.e., For a given value of number, the program calculates sum as
sum=(number*(number+1))/2
For example when number = 10
then sum = (10*11)/2
= 110/2
= 55
Iterations in program for number = 10
sum(10)
= 10+sum(9) [ sum(9) is a function call again ]
= 10+9+sum(8) [ sum(8) is a function call again ]
= 10+9+8+sun(7) [ sum(7) is a function call again ]
= 10+9+8+7+sum(6) [ sum(6) is a function call again ]
= 10+9+8+7+6+sum(5) [ sum(5) is a function call again ]
= 10+9+8+7+6+5+sum(4) [ sum(4) is a function call again ]
= 10+9+8+7+6+5+4+sum(3) [ sum(3) is a function call again ]
= 10+9+8+7+6+5+4+3+sum(2) [ sum(2) is a function call again ]
= 10+9+8+7+6+5+4+3+2+sum(1) [ sum(1) is a function call again ]
= 10+9+8+7+6+5+4+3+2+1+sum(0) [ sum((0) returns 0 ]
= 10+9+8+7+6+5+4+3+2+1+0
= 55