Please spot the mistake in the code. I don’t know how to do recursion by removing parameters. When I remove parameters, code begins to work fine.
Code Snippet
let number = document.getElementById("inputN").value;
function result2(number) {
if (number == 1)
return 0;
if (number == 2)
return 1;
let answer;
answer = (number - 1) * (result2(number - 1) + result2(number - 2));
return answer
document.getElementById("result").innerHTML = "Result: " + result2(number);
}
<label for="inputN">Enter the value of n:</label>
<input type="number" id="inputN" min="1" step="1" value="1">
<button onclick="result2(number)">Calculate</button>
<p id="result"></p>
>Solution :
There are a couple of significant problems here:
- The line of code which produces output is after a
returnstatement, so it can never execute. - You define the value of
numberonce, and only once, when the page loads. That value is1. You always call the function with1, so it always immediately returns.
You can correct both of these by separating your concerns into two functions. One which reads the input value and writes the output value, and which calls the other function which performs the calculation (recursively). For example:
function getResult() {
let number = document.getElementById("inputN").value;
document.getElementById("result").innerHTML = "Result: " + recurse(number);
}
function recurse(val) {
if (val == 1)
return 0;
if (val == 2)
return 1;
return (val - 1) * (recurse(val - 1) + recurse(val - 2))
}
<label for="inputN">Enter the value of n:</label>
<input type="number" id="inputN" min="1" step="1" value="1">
<button onclick="getResult()">Calculate</button>
<p id="result"></p>
Note how the recurse function only performs the calculation and returns the result. It is not concerned with where the value came from or what is done with the result.
The other function, getResult, is what gets invoked by the UI. That function reads the input value, invokes the calculation, and displays the result.