recursion not returning anything
Go to solution
Solved by trag1c,
The problem is your mathematical function is not recursive or iterative, at least in this form.聽 if you want the sum of 5 consecutive terms, you would substitute n = 5 so it would be
x = n(n+1)/2
x = (5)(5+1)/2
x = 15
聽
There is no recursion or iteration when using that formula. If you want to calculate the sum recursively for positive integers you would do the following:
#include <cstdio> int sum(int n); int main(){ int n = 0; printf("Enter a number to calculate the sum of all the number from your input: "); scanf("%d", &n); printf("sum of %d terms is, %d\n", n, sum(n)); return 0; } int sum(int n){ if(n < 2 && n >= 0) { // sum of 1 or sum of 0 terms is 1 or 0 respectively return n; } else if (n < 0) { // positive ints only return 0; } return n + sum(n - 1); }
edit:
I would also add that your original code should segfault (attempt to write an illegal memory address) due to the fact that there is no exit condition that breaks the recursion. As such your stack will just keep on growing with every stack frame of the recursive function. Linux should report this, no idea about any other platform.
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now