Reputation: 161
Can someone show me where I am going wrong within this Code Academy problem. I'm having a world of trouble with Recursion and am only vaguely beginning to understand how it works at a fundamental level... The first set of code is what I have written followed by the same code with the blanks I have tried to fill in.
Fill in the blanks: Write a conditional statement for the base case of
multiplyEach()
. We want to end the recursion when there are no more values in stack. Then we want to return the variableint
, since this represents the last value evaluated. Complete the recursive case with a recursive call to the function, without any arguments.
Blank Problem with fill-in-the-blanks (___
):
var stack = [];
function countDown(int) {
stack.push(int);
if (int === 1) {
return 1;
}
return countDown(int - 1);
}
function multiplyEach() {
// Remove the last value of the stack
// and assign it to the variable int
int = stack.pop();
x = stack.length;
// Base case
if (___) {
return ___;
}
// Recursive case
else {
stack[x - 1] = int * stack[x - 1];
return ___;
}
}
// Call the function countDown(7)
countDown(7);
// And then print out the value returned by multiplyEach()
console.log(multiplyEach());
This is my Try:
var stack = [];
function countDown(int) {
stack.push(int);
if (int === 1) {
return 1;
}
return countDown(int - 1);
}
function multiplyEach() {
// Remove the last value of the stack
// and assign it to the variable int
int = stack.pop(int);
x = stack.length;
// Base case
if (x === 0) {
return int;
}
// Recursive case
else {
stack[x - 1] = int * stack[x - 1];
return multiplyEach(stack);
}
}
// Call the function countDown(7)
countDown(7);
// And then print out the value returned by multiplyEach()
console.log(multiplyEach());
Thanks!
Upvotes: 1
Views: 5591
Reputation: 350941
You filled in the blanks correctly!
There is just one bug you introduced in a part of the code you did not have to touch:
Replace:
int = stack.pop(int);
with:
var int = stack.pop();
Because pop
returns the value you need. There is no need to pass anything.
Also, you passed the stack
argument to a function that does not take that argument (the variable is global). This does no harm, but to avoid confusion, it is better to call the function without arguments, as it is supposed to be:
return multiplyEach();
Some side-comments on the code you have been provided with:
int
as it might become a reserved word in future versions of JavaScript;var
: var int = ...
Upvotes: 4