Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find and fix an error in the factorial program (JavaScript)

I have such a problem, I’ve been struggling with it since yesterday, but I just can’t find an error. The condition is: Find and fix the error in the program for finding the factorial.
And here is the code:

var counter = prompt("Enter the number");
var factorial = 1;

document.write("Factorial of a number: " + counter + "! = ");

do {

     if (counter == 0) {
                factorial = 1;
                break;
     }

     factorial = factorial / counter;
     counter = counter + 1;
}
while (counter > 0);

document.write(factorial);

The tooltips say that something is wrong with the factorial variable itself, but I can’t see anything. I have tried different options, including writing factorial = factorial * counter; instead of factorial = factorial / counter;, but it’s for sure something else. We are talking about a site with automatic checking, so I think that there is something small that needs to be corrected, and there is no need to rewrite everything completely. So, the idea is to make some corrections to the existing code. Help me, please!

I have tried different options, including writing factorial = factorial * counter; instead of factorial = factorial / counter. As well, most probably the while loop is endless, because of this condition while (counter > 0).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  1. In the original code, the line counter = counter + 1; should be
    replaced with counter = counter – 1;. We need to decrement the
    counter by 1 in each iteration of the loop to calculate the
    factorial correctly.
  2. Instead of dividing the factorial by the counter (factorial =
    factorial / counter;), we need to multiply them (factorial =
    factorial * counter;) to calculate the factorial.

this is your fixed code

var counter = prompt("Enter the number");
var factorial = 1;

document.write("Factorial of a number: " + counter + "! = ");

do {
    if (counter == 0) {
        factorial = 1;
        break;
    }

    factorial = factorial * counter;
    counter = counter - 1;
} while (counter > 0);

document.write(factorial);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading