My instructor insists that I am not writing recursive functions but has not provided any explanation of why my functions are not recursive. I've been researching recursive functions for weeks now but apparently still do not understand what makes a recursive function. As far as I am able to gather, a recursive function is any function which calls itself using a matching function call to the original.
Psuedo example:
bool foo(int someInt){
++someInt;
return foo(someInt);
}
Below is my latest function.
int LinkedList::sumR(int intIn){
if(intIn == 0){
if(head != NULL)
curr = head;
}
if (head != NULL){
if(curr->next != NULL){
intIn = intIn + curr->data;
curr = curr->next;
return sumR(intIn);
}
else
{
intIn = intIn + curr->data;
}
return intIn;
}
return intIn;
}
I'm completely lost at this point.
After emailing my instructor, they responded that for a function to be recursive it must accept a class or struct pointer as a parameter (as far as they're concerned, I guess).
Without a mathematical definition it is hard to tell, but I think what your instructor expects is that you implement this as a pure function, not relying on any state external to the function (such as your variable named cur
).
eg take the factorial function (5! = 5 x 4 x 3 x 2 x 1)
int fact(n) = { 1 if n == 1 else n * fact(n-1) }
If I implement this the way you implemented your list sum above
prod = 1
fact(n) {
if (n > 1) {
prod *= n;
fact(n - 1);
}
}
This second implementation relies on side-effects (the global state variable prod
).
If your LinkedList
is list of nodes LinkedList::Node
(what your variable cur
and head
point to), then try to redefine your function as:
int LinkedList::sumR(LinkedList::node cur);
and call it with sumR(list->head);
Any recursive method will include the following three basic elements :
Your first example is missing #2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.