Finding the factorial using a loop in javascript - javascript

I need to use a loop to find the factorial of a given number. Obviously what I have written below will not work because when i = inputNumber the equation will equal 0.
How can I stop i reaching inputNumber?
var inputNumber = prompt('Please enter an integer');
var total = 1;
for (i = 0; i <= inputNumber; i++){
total = total * (inputNumber - i);
}
console.log(inputNumber + '! = ' + total);

here is an error i <= inputNumber
should be i < inputNumber
var inputNumber = prompt('Please enter an integer');
var total = 1;
for (i = 0; i < inputNumber; i++){
total = total * (inputNumber - i);
}
console.log(inputNumber + '! = ' + total);

you can keep this:
i <= inputNumber
and just do this change:
total = total * i;
then the code snippet would look like this:
var inputNumber = prompt('Please enter an integer');
var total = 1;
for (i = 1; i <= inputNumber; ++i){
total = total * i;
}
console.log(inputNumber + '! = ' + total);

var inputNumber = prompt('Please enter an integer');
var total = 1;
for (i = 0; i < inputNumber; i++){
total = total * (inputNumber - i);
}
alert(inputNumber + '! = ' + total);

You could use the input value and a while statement with a prefix decrement operator --.
var inputNumber = +prompt('Please enter an integer'),
value = inputNumber,
total = inputNumber;
while (--value) { // use value for decrement and checking
total *= value; // multiply with value and assign to value
}
console.log(inputNumber + '! = ' + total);

Using total *= i; will set up all of your factorial math without the need of extra code. Also, for proper factorial, you'd want to count down from your input number instead of increasing. This would work nicely:
var inputNum = prompt("please enter and integer");
var total = 1;
for(i = inputNum; i > 1; i--){
total *= i;
}
console.log(total);

function factorialize(num) {
var result = num;
if(num ===0 || num===1){
return 1;
}
while(num > 1){
num--;
result =num*result;
}
return result;
}
factorialize(5);

Related

How to find the average in javascript?

So I'm fairly new to JavaScript but I cannot seem to find the average in my code. I want to understand why my average is not working. Any help you guys?
function getEvenOdd() {
var oddSum = 0;
var evenSum = 0;
var num = 0;
var evenAvg = 0;
var oddAvg = 0;
while (true) {
num = parseInt(prompt("Enter a number(-1 to exit)"));
if (num == -1) {
break;
}
if (num % 2 == 0) {
evenSum += num;
} else {
oddSum += num;
}
evenAvg = evenSum / num;
oddAvg = oddSum / num;
}
alert("Sum of all even numbers is: " + evenSum);
alert("Sum of all odd numbers is: " + oddSum);
alert("Average of all even numbers is : " + evenAvg);
alert("Average of all odd numbers is: " + oddAvg);
}
On your code, to calculate the oddAvg and evenAvg, you have divided evenSum and oddSum by num variable (which is input from prompt).
And as you know, average = total sum / total count, so it's not right to divide the sum by the input number variable.
Instead of that, you need to calculate the count of odd and even numbers and divide the even and odd sum by the even and odd number counts as follows.
function getEvenOdd() {
var oddSum = 0;
var evenSum = 0;
var num = 0;
var evenAvg = 0;
var oddAvg = 0;
var evenCount = 0;
var oddCount = 0;
while (true) {
num = parseInt(prompt("Enter a number(-1 to exit)"));
if (num == -1) {
break;
}
if (num % 2 == 0) {
evenSum += num;
evenCount ++;
} else {
oddSum += num;
oddCount ++;
}
}
evenAvg = evenSum / evenCount;
oddAvg = oddSum / oddCount;
alert("Sum of all even numbers is: " + evenSum);
alert("Sum of all odd numbers is: " + oddSum);
alert("Average of all even numbers is : " + evenAvg);
alert("Average of all odd numbers is: " + oddAvg);
}
getEvenOdd();
These operations are dividing the evenSum or oddSum by the last input num.
evenAvg = evenSum / num;
oddAvg = oddSum / num;
You should divide the sum by the number of even or odd inputs.
Instead of evenSum / num use evenSum/Count of Numbers entered.
How about this solution? It is aiming to store odd and even numbers into oddList and evenList.
function getEvenOdd() {
var evenAvg = 0;
var oddAvg = 0;
var oddList = [];
var evenList = [];
var num = 0;
while (true) {
num = parseInt(prompt("Enter a number(-1 to exit)"));
if (num == -1) {
break;
}
if (num % 2 == 0) {
evenList.push(parseInt(num));
} else {
oddList.push(parseInt(num));
}
evenAvg = evenList.reduce((p, c) => p + c, 0) / evenList.length;
oddAvg = oddList.reduce((p, c) => p + c, 0) / oddList.length;
}
alert("Sum of all even numbers is: " + evenList.length);
alert("Sum of all odd numbers is: " + oddList.length);
alert("Average of all even numbers is : " + evenAvg);
alert("Average of all odd numbers is: " + oddAvg);
}
getEvenOdd();

How to display average from list using javascript?

I just want to show their average from the list when the user stored a value in the list
But I try to use document.write(); but it's doesn't work for me
I want to show the average below the list
function listtable()
{
var score;
var scoreArray = [];
var scoreOutput;
var slenght;
var sum = 0;
do
{
score = prompt("Please enter score and Enter -1 to stop
entering");
score = parseInt(score);
if (score >=0 )
{
scoreArray[scoreArray.length] = score;
}
} while (score != -1);
scoreOutput = "<ul>";
for (i = 0; i < scoreArray.length; i++)
{
scoreOutput += "<li>" + scoreArray[i] + "</li>";
}
scoreOutput += "</ul>";
for (i = 0; i < scoreArray.Length; i++)
{
sum += parseInt(score[i]);
}
var avarage = sum/scoreArray.length;
document.getElementById("display").innerHTML = scoreOutput;
document.write("The Avarage Score is: " + average);
}
You have a couple of typos in your code:
parseInt(score[i]) should be parseInt(scoreArray[i])
i < scoreArray.Length should be scoreArray.length with a lowercase l
The variable should be average not avarage
function listtable() {
var score;
var scoreArray = [];
var scoreOutput;
var slenght;
var sum = 0;
do {
score = prompt("Please enter score and Enter -1 to stop entering ");
score = parseInt(score);
if (score >= 0) {
scoreArray[scoreArray.length] = score;
}
}
while (score != -1);
scoreOutput = "<ul>";
for (i = 0; i < scoreArray.length; i++) {
scoreOutput += "<li>" + scoreArray[i] + "</li>";
}
scoreOutput += "</ul>";
for (i = 0; i < scoreArray.length; i++) {
sum += parseInt(scoreArray[i]);
}
var average = sum / scoreArray.length;
document.getElementById("display").innerHTML = scoreOutput;
document.write("The Avarage Score is: " + average);
}
listtable()
<span id="display" />
(Please search how to debug javascript code using degbugger; and dev tools. You can avoid trivial errors)
Try this:
function listtable() {
var score;
var scoreArray = [];
var scoreOutput;
var slenght;
var sum = 0;
var i;
do {
score = prompt("Please enter score and Enter -1 to stop entering");
score = parseInt(score);
if (score >=0 ) {
scoreArray[scoreArray.length] = score;
}
} while (score != -1);
scoreOutput = "<ul>";
for (i = 0; i < scoreArray.length; i++) {
console.log(scoreArray[i])
sum += parseInt(scoreArray[i]);
scoreOutput += "<li>" + scoreArray[i] + "</li>";
}
scoreOutput += "</ul>";
var average = sum / scoreArray.length;
document.getElementById("display").innerHTML = scoreOutput;
document.write("The Average Score is: " + average);
}
listtable();
<div id="display"></div>
I have made the following changes in your code:
You have used 2 for loop which is not needed, I have added the code in the single for loop. (Optimized, Not an issue)
The variable name is defined as average but you used avarage in the document.write.
You didn't define the var i in your code and directly initializing it in the loop.
There are multiple issue in your code,
You need to store elements in an array with incremental counter instead of storing it in an array length i.e Intested of scoreArray[scoreArray.length] = score; you need to store value at particular index.
Like.
var index = 0;
do
{
score = prompt("Please enter score and Enter -1 to stop
entering");
score = parseInt(score);
if (score >=0 )
{
scoreArray[index++] = score;
//Use index with incremental operator
}
} while (score != -1);
While calculating sum you need to read value from scoreArray not from score. In your code scoreArray is an array not score variable.
correct code,
for (i = 0; i < scoreArray.Length; i++)
{
sum += parseInt(scoreArray[i]);
//Use scoreArray instead of score
}
Now calculate average and print in HTML DOM
Like,
document.write("The Avarage Score is: " + avg);
Here is sample piece of code to print average.
//Declaration of variables
var scoreArray = [1, 2, 3, 4, 5];
var i, index = 0, sum = 0;
//Calculate sum
for(i = 0; i < scoreArray.length; i++)
sum += scoreArray[i];
//Calculate average
var avg = sum/scoreArray.length;
document.write("The Avarage Score is: " + avg);

Calculate the sum of positive values smaller or equal to a number

I am trying to calculate the sum of positive values smaller or equal to the entered number, for ex: 5 -> 1+2+3+4+5 = 15
I came up with this:
var num = Number(prompt("Enter a number "));
sum = 0;
i = num;
do {
sum = sum += i;
i--
document.write(sum);
} while (i > 0);
I don't understand what I am doing wrong.
i think this is correct code:
var num = Number(prompt("Enter a number "));
sum = 0;
i = num;
do
{
sum += i;
i--;
}
while (i > 0);
document.write(sum);
and i suggest you to use this formula : document.write((num * (num + 1)) / 2);
If you look closer to your task, you'll find out, that:
If Num = 1, the sequence to be summed is [1]
if Num = 2, the sequence is [1, 2]
if Num = 3, the sequence is [1, 2, 3]
You can imagine, that you have a square with sides equal to num, for example, when num = 4:
****
****
****
****
And you need to summ 1, 2, 3, 4:
***#
**##
*###
####
See? It's a square of a triangle.
It could be calculated by formula: num * (num + 1) / 2
So, you code could be:
var num = Number(prompt("Enter a number "));
document.write(num * (num + 1) / 2)
You are writing the sum on each loop instead you have to print it finally. If you want to print the numbers then keep it an array and join them with + symbol before writing. To make it in ascending order change the loop condition.
var num = Number(prompt("Enter a number "));
sum = 0;
i = 1;
nums = [];
do {
sum = sum += i;
nums.push(i++);
}
while (i <= num);
document.write(nums.join(' + ') + ' = ' + sum);
Do with increment instead of decrements.And also show result of sum outside of loop .Not with in loop.And create array to append increment value.Finally print with document.write
var num=Number(prompt("Enter a number "));
sum = 0;
i = 1;
var a=[];
do {
sum +=i;
a.push(i)
i++;
}
while (num >= i);
document.write(a.join('+')+'='+sum)
You should write the answer at the end of loop and make this simple sum += i;.
var num = Number(prompt("Enter a number"));
sum = 0;
i = num;
do {
sum += i;
i--;
}
while (i > 0);
document.write(sum);
var number = 5, // Your number
result = 0;
while ( number !== 0 ) {
result += number;
number--;
}
document.write(result);
Fast and precious solution.
Here is the case with complete check and display as you need: JAVA
public static void main ( String arg[]) {
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
System.out.println("Number entered : " + number);
int sum =1 ;
if(number > 1) {
int nextNumber = 1;
System.out.print(nextNumber);
do {
// sum of all the positive numbers
nextNumber++ ;
sum = nextNumber + sum;
System.out.print( " + " + nextNumber);
}while(nextNumber < number);
System.out.print(" = " + sum);
}
}
var num = Number(prompt("Enter a number"));
sum = 0;
for (i = num; i > 0; i--) {
sum += i;
}
document.write(sum);

Unbalanced tree from document.write and variable un-defined

I am writing a program to display total test grades and avg with a loop. however when I try to test it, I cant get the final message "Good Job" to show up and I am getting a error for unbalanced tree and undefined "Avg" variable. I dont see how "avg" is undefined when it works during the loop just not after
var Testscore = 0;
var Testcount = 0;
var Total = 0;
var Avg = 0;
do {
Testscore = prompt("Enter the test score ", 0);
Testcount = (Testcount + 1);
Total = parseFloat(Testscore) + parseFloat(Total);
Avg = (Total / Testcount);
document.write("Total test score is " + Total + "<br>");
document.write("Average test score is " + Avg + "<br>" + "<br>");
} while (Testcount < 4)
Avg = (Total / Testcount);
if (avg > 80) {
document.write("Good Job!");
} else {
documet.write("Try harder..");
}
You just had a few typos in your code!
avg and Avg are different, as variables are case sensitive.
Additionally, there's a documet instead of document
var Testscore = 0;
var Testcount = 0;
var Total = 0;
var Avg = 0;
do
{
Testscore = prompt("Enter the test score ",0);
Testcount = (Testcount + 1);
Total = parseFloat(Testscore) + parseFloat(Total);
Avg = (Total / Testcount);
document.write("Total test score is " + Total + "<br>");
document.write("Average test score is " + Avg + "<br>" + "<br>");
} while (Testcount < 4)
Avg = (Total / Testcount);
if (Avg > 80)
{
console.log("Good Job!");
}
else
{
console.log("Try harder..");
}

Javascript find average from user's input

I know there are similar questions on here to mine but I don't see the answer there.
Where am I going wrong with this JS code to find the average number from the user's input?
I want to keep entering numbers until -1 is entered. I think -1 is being counted as an input/
var count = 0;
var input;
var sum = 0;
while(input != -1){
input = parseInt(prompt("Enter a number"));
count++;
sum = sum + input;
sum = parseInt(sum);
average = parseFloat(sum/count);
}
alert("Average number is " + average);
This is the right order (without all the unnecessary parsing...)
var count = 0;
var input;
var sum = 0;
input = parseInt(prompt("Enter a number"));
while (input != -1) {
count++;
sum += input;
average = sum / count;
input = parseInt(prompt("Enter a number"));
}
alert("Average number is " + average);
DEMO
Note that you can calculate the average once outside of the loop and save some CPU.
You need to check after you take the input from the user.
while(input != -1){
input = parseInt(prompt("Enter a number"));
//The user enters -1 but still inside the while loop.
if(input != -1)
{
count++;
sum = sum + input;
}
sum = parseInt(sum);
average = parseFloat(sum/count);
}
Here is the function code you need.
var count = 0;
var input;
var sum = 0;
while(true){
input = parseInt(prompt("Enter a number"));
if(input != -1)
{
count++;
sum = sum + input;
sum = parseInt(sum);
}
else
break;
}
average = parseFloat(sum/count);
alert("Average number is " + average);
This will grab the average...Simply accumulate the values and then divide the total 'sum' by the number of 'inputs made'(in our case we just use the count++)
var count = 0;
var input;
var sum = 0;
while(input != -1){
count++;
input = prompt("Enter a number");
sum += input;
sum = parseInt(sum);
}
average = (sum/count);
alert("Average number is " + average);

Categories

Resources