Sum of two numbers and the numbers between them - javascript
Ask user to enter a number. Then ask the user to enter a number bigger than the first number. Calculate a value that is the sum of all the numbers from the first number to the second number including the end points. For example, if the user enters 5 and 10 then calculate the total of 5 + 6 + 7 + 8 + 9 + 10. Display the results. MUST USE A WHILE LOOP
This is what I have so far. I can't seem to get the sum to be correct. If I enter the numbers from the example above, I get 49 instead of 45. I understand where I went wrong and why it is 49 based on my code but can't figure out how to make it correct.
// declare constants
const INITIAL_VALUE = 0;
const COUNTER_VALUE = 1;
// declare variables
var number1;
var number2;
var sum;
var counter;
var difference;
var middlePoint;
var middlePointSum;
// assigning values
sum = INITIAL_VALUE;
difference = INITIAL_VALUE;
counter = COUNTER_VALUE;
middlePoint = COUNTER_VALUE;
middlePointSum = INITIAL_VALUE;
// prompt user to enter two numbers
number1 = prompt("Enter first number: ");
number2 = prompt("Enter a number bigger than first number: ");
// convert user input into numbers
number1 = Number(number1);
number2 = Number(number2);
// display number1
document.write(number1);
difference = number2 - number1;
middlePoint += number1;
while (counter < difference) {
document.write(" + " + middlePoint);
middlePoint = middlePoint + 1;
counter++;
middlePointSum += middlePoint;
}
// calculate the sum
sum = number1 + middlePointSum + number2;
// display number1, middle points, number2, and sum
document.write(" + " + number2 + " = " + sum);
// prompt user to enter two numbers
var number1 = prompt("Enter first number: ");
var number2 = prompt("Enter a number bigger than first number: ");
// convert user input into numbers
var number1 = Number(number1);
var number2 = Number(number2);
var start_point= number1;
var sum=0;
// display number1
document.write(start_point);
sum += start_point;
start_point++;
while (start_point <=number2) {
document.write(" + " + start_point);
sum += start_point;
start_point++;
}
// display sum
document.write(" = " + sum);
Welcome to StackOverflow!
The cause of error is at this part of the code
while (counter < difference) {
document.write(" + " + middlePoint);
middlePoint = middlePoint + 1; // you are already increasing the middlePoint number
counter++;
middlePointSum += middlePoint;
}
Therefore, the sum is always over by the number of counter - 1. What you should have done, is execute middlePointSum += middlePoint; first before increasing the value of middlePoint and counter.
while (counter < difference) {
document.write(" + " + middlePoint);
middlePointSum += middlePoint;
middlePoint = middlePoint + 1;
counter++;
}
This code should work for you. Variabel sum should contain your desired sum.
var sum = 0;
var firstNumber = 0;
var secondNUmber = 0;
var firstNumberStr = '';
var secondNUmberStr = '';
// prompt user to enter two numbers
firstNumberStr = prompt("Enter first number: ");
while(isNaN(firstNumberStr)){
firstNumberStr = prompt("Enter Correct first number: ");
}
secondNUmberStr = prompt("Enter a number bigger than first number: ");
while(isNaN(secondNUmberStr) || parseInt(firstNumberStr) >= parseInt(secondNUmberStr)){
secondNUmberStr = prompt("Enter a number bigger than first number: ");
}
firstNumber = parseInt(firstNumberStr);
secondNUmber = parseInt(secondNUmberStr);
while(firstNumber <= secondNUmber){
sum += firstNumber;
firstNumber++
}
You did a very small mistake in the code . The bug is in while loop.
while (counter < difference) {
document.write(" + " + middlePoint);
middlePoint = middlePoint + 1;
counter++;
middlePointSum += middlePoint;
}
you are incrementing the middlepoint before middlePointSum is Calculated. It should be incremented after calculating the middlePointSum.
while (counter < difference) {
document.write(" + " + middlePoint);
counter++;
middlePointSum += middlePoint;
middlePoint = middlePoint + 1;
}
Your middlePointSum is starting from 1 intead of 0 so you got: 5 + (7 + 8 + 9 + 10) + 10 to fix your code set middlePointSum to INITIAL_VALUE
For simplification just ignore the difference between the numbers, increment number1 until you reach number 2
var number1 = prompt("Enter first number: ");
var number2 = prompt("Enter a number bigger than first number: ");
var incNumber;
var strResult = [];
number1 = incNumber = Number(number1);
// use incNumber if you need to preserve number1 value or just use number 1 value instead
number2 = Number(number2);
var sum = 0;
while(incNumber <= number2) {
strResult.push(incNumber);
sum += incNumber++;
// this means add incNumber to sum then increment it by 1
}
document.write(`${strResult.join(' + ')} = ${sum}`);
One problem is that your middlePointSum does not take into account the first number after the number1, for example, the 6 in your example. Another problem is that your counter < difference test is inaccurate - you would have to iterate until counter + 1 < difference:
// declare constants
const INITIAL_VALUE = 0;
const COUNTER_VALUE = 1;
// declare variables
var number1;
var number2;
var sum;
var counter;
var difference;
var middlePoint;
var middlePointSum;
// assigning values
sum = INITIAL_VALUE;
difference = INITIAL_VALUE;
counter = COUNTER_VALUE;
middlePoint = COUNTER_VALUE;
middlePointSum = INITIAL_VALUE;
// prompt user to enter two numbers
number1 = prompt("Enter first number: ");
number2 = prompt("Enter a number bigger than first number: ");
// convert user input into numbers
number1 = Number(number1);
number2 = Number(number2);
// display number1
document.write(number1);
difference = number2 - number1;
middlePoint += number1;
middlePointSum = middlePoint;
while (counter + 1 < difference) {
document.write(" + " + middlePoint);
middlePoint = middlePoint + 1;
counter++;
console.log(middlePointSum);
middlePointSum += middlePoint;
}
// calculate the sum
sum = number1 + middlePointSum + number2;
// display number1, middle points, number2, and sum
document.write(" + " + number2 + " = " + sum);
But this seems far, far more complicated than it needs to be - why not simply iterate from number1 to number2, adding to sum along the way?
const number1 = Number(prompt("Enter first number: "));
const number2 = Number(prompt("Enter a number bigger than first number: "));
document.write(number1);
let sum = number1;
for (let i = number1 + 1; i <= number2; i++) {
sum += i;
document.write(' + ' + i);
}
document.write(' = ' + sum);
Or, create an array of the numbers, join by plus signs, and calculate the sum with reduce:
const number1 = Number(prompt("Enter first number: "));
const number2 = Number(prompt("Enter a number bigger than first number: "));
const nums = Array.from(
{ length: number2 - number1 + 1 },
(_, i) => i + number1
);
const sum = nums.reduce((a, b) => a + b);
document.write(nums.join(' + ') + ' = ' + sum);
var num1 = Number(prompt("Enter a number"));
var num2 = Number(prompt("Enter a larger number"));
document.write(num1 + "+" + num2 + "=" + (num1+num2));
// now lets find the sum of numbers between these two numbers.
document.write("<br>"); // new line
var counter = num1; // we will start countring from the smaller number
var sum = 0;
//keep looping until we reach the bigger number (num2)
while(counter<=num2) {
sum += counter;
// print the current number
document.write(counter);
//print a plus sign
if(counter<num2) {
// only put a (plus sign) if we are not yet reached num2
document.write("+");
}
//increment to control the loop
counter ++;
}
//finally put the result
document.write("=" + sum);
You are setting counter to the constant COUNTER_VALUE which is 1.
Then, in your program, you are entering 5 and 6 as input. The difference is 6-5 which is 1.
Your while loop has a condition to only execute when counter<difference . In your case, counter=1 and difference=1. This means that they are equal, and thus, the loop will not execute.
I hope this sheds light on what needs to be done from your side to fix this bug.
Related
Taking two mathrandom values and adding them on loop
I have to make a game of dice where I add the values of both the dice and give the sum. You get another turn if both the dice end up on the same number (such as 2 and 2 which is 4) then you roll the dice again and the 2 new numbers get added to the previous sum (like 4 mentioned earlier). For example - 1st try 3 and 3, sum is 6. 2nd try 4 and 5, sum is 6 + 4 + 5 = 15 I'm able to get the first sum right, but the subsequent numbers are getting messed up sometimes even giving twice as much. function oneRandom(){ var my1 = Math.floor(Math.random() * 6 ) +1 ; var my2 = Math.floor(Math.random() * 6 ) +1 ; var num1 = Number(my1); var num2 = Number(my2); var sum = num1 + num2; console.log(sum); var resultfield = document.getElementById("total").innerHTML = "<h1>"+sum+"</h1>"; document.getElementById("cilc").style.display = "none"; if (getImage.src == get2.src){ document.getElementById("cilc").style.display = "block"; var sum2 = num1 + num2; var total = sum2 + sum; var resultfield = document.getElementById("total").innerHTML = "<h1>"+total+"</h1>"; } } The getImage and get2 are arrays to match dice images to give another turn in case of same numbers loading.
You can try this, function rollDice (times) { var num1 = Math.floor(Math.random() * Math.floor(6)); var num2 = Math.floor(Math.random() * Math.floor(6)); console.log(times, num1, num2); var total = num1 + num2; return num1 === num2 ? total + rollDice(times + 1) : total; } console.log(`result is ${rollDice(0)}`);
Factorial will not multiply
When I run the code it doesn't multiply my number it just outputs in a loop until it reaches 1 I have tried multiple different ways and this one is the closest i've gotten ...................................... var BR="<br />"; //html line break function factorial(Num) { document.write("The factorial of your number is" +Num +BR); if (Num == 1 ) return 1; else return (Num * factorial(Num-1)); } ..................................................... ....................................... var Num; //users number var Numfactorial; var ES=""; var factorial Num=prompt("Enter a number between 1-20" +ES); Numfactorial=factorial(Num); ......................................... It's supposed to take the number and multiply it down, so say you put in 20 it should go 19*18*17... down until it multiplies 1 and then outputs the product.
Place the document.write outside your function, and just print the result (Numfactorial) to the page. You also need to parse Num to a number, and remove var factorial: var BR = "<br />"; function factorial(Num) { if (Num == 1) return 1; else return Num * factorial(Num - 1); } var Num; var Numfactorial; var ES = ""; Num = parseInt(prompt("Enter a number between 1-20" + ES)); Numfactorial = factorial(Num); document.write("The factorial of your number is " + Numfactorial + BR);
Well, that is the expected output of your code. Your function factorial is returning your value which you aren't using to display the value. You should instead write it like this: .................................................... var BR="<br />"; //html line break function factorial(Num) { if (Num == 1 ) return 1; else return (Num * factorial(Num-1)); } ..................................................... ....................................... var Num; //users number var Numfactorial; var ES=""; var factorial Num=prompt("Enter a number between 1-20" +ES); Numfactorial=factorial(Num); document.write("The factorial of your number is" +Numfactorial +BR); .........................................
while loop test case errors
The question as per the practice course is : Write a JavaScript program to find the maximum integer n such that (1 + 2 + ... + n <= given integer ) is true. For eg. If a given integer is 10, value of maximum integer n is 4 so that 1+2+3+4 <= 10 is true. Your output code should be in the format console.log("Value of n is ", variableName) My code is : var num = prompt("Enter a number"); function test(x) { var sum = 1, n = 1, a = 0; while (sum <= x) { sum += n; n = n + 1; a += 1; } return a; } var output = test(num); console.log("Result is :", output); I'm getting the correct outputs as per the test cases I've entered(10-4,15-5,16-6,17-6) but the website says there is something wrong with the program. What am i doing wrong?
Better answer than looping: exploit maths. Starting with Triangular number formula: 1 + 2 + ... + n = n * (n + 1) / 2 Thus, for input x, you need to find n such that n * (n + 1) / 2 <= x To solve this, we need to clean up the inequality, then use the quadratic equation formula: n^2 + n <= 2x n^2 + n - 2x <= 0 n <= (-1 + sqrt(1 + 8x)) / 2 as the final solution. e.g. for x = 10: n <= (-1 + sqrt(81)) / 2; n <= 4 x = 16: n <= (-1 + sqrt(128)) / 2; n <= 5.156854249492381 Round the upper limit down, and you have the largest allowed integer. Translated into JavaScript: function test(x) { return Math.floor((Math.sqrt(8 * x + 1) - 1) / 2); } var num = prompt("Enter a number"); console.log("Result is :", test(num));
Consider if the passed value is 11. Then, the maximum integer n should be 4, because 1+2+3+4 < 11 is true, while 1+2+3+4+5 < 11 is false. Your current code outputs 5 for an input of 11, though, which is incorrect; your while loop is sometimes overshooting sum. You also need to initialize sum to start at 0, not at 1. Subtract one from a before returning it: function test(x) { var sum = 0, n = 1, a = 0; while (sum <= x) { sum += n; n = n + 1; a += 1; console.log(a, sum); } return a - 1; } console.log(test(10)); console.log(test(11)); var num = prompt("Enter a number"); var output = test(num); console.log("Result is :", output);
The code below should work for you. Basically, what I did was that if the input is 10, and your sum is 9, it will still go into the while loop. Then it will add n again and now your number is greater than your input (which is 10), but you still return it. Here what I did is that at the end of the while loop, if your sum is greater than your input, subtract one from a. That way it will still execute, but it will fix the problem. Also another error I noticed was that sum started at 1, and n started at 1. You wanted 1+2+3+...+n, however using your previous method, you got 1+1+2+3+...+n. var num = prompt("Enter a number"); function test(x) { var sum = 0, n = 1, tempSum = 1, a = 0; while (sum <= x) { sum += n; n++; a++; if (sum > x) { a--; } } return a; } var output = test(num); console.log("Result is :", output);
Your order of operation is a little funky; all you have to do is add the incrementor. The while false case will make sure the sum only passes over the number once. So when you return, reduce the number by one: var num = prompt("Enter a number"); var output = test(num); console.log("Result is :", output); function test(num){ let sum = 0 let inc = 0 while(sum<=num) sum+=++inc return --inc; }
This is a reduced version of your code, basically we increment first the number to add (n) in each iteration, and then we add it to the variable holding the sum. When the loop conditions evaluates to false you need to decrement one to n to get your value: var num = prompt("Enter a number"); function test(x) { var sum = 0, n = 0; while (sum <= x) { sum += (++n); } return --n; } var output = test(num); console.log("Result is :", output);
I think this will work for you: var num = prompt("Enter a number"); function test(x) { var sum = 1, n = 0; while ((sum+n) <= x) { n = n + 1; sum += n; } return n; } var output = test(num); console.log("Result is :", output);
Try below function to find max Number function maxNumber(a){ var i=1,sum=0,maxNumber=0; while(sum<=a) { sum=sum+i; if(sum<=a) { maxNumber=i; } i+=1; } return maxNumber; } doubled checked condition sum<=a to preserve the previous loop value and if condition not satisfied that means current loop value is not useful so returned preserved value of previous loop Output tested :
Below will help you get the job done. var num = prompt("Enter a number"); function findMaxNumber(num){ var sum = 0; var counter = 0; while(sum < num){ if(sum + counter > num){ break; // Exit loop } sum = sum + counter; counter++; } return --counter; // Loop will cause this to be 1 higher than the max int. } console.log('Result is: ' + findMaxNumber(num));
How to combine these specific Javascript statements?
1.I include what the two lines i want to combine in the first comment of the code. If you can point me to what i need to do it would really help. I just started javascript a couple days ago. If u can recommend any books please tell me. im currently reading the murach series of books and its really helping. /*The two statements i want to combine are entry = parseInt(entry); var score1 = entry; */ <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Average Test Scores</title> <script> var entry; var average; var total = 0; //get 3 scores from user and add them together entry = prompt("Enter test score"); entry = parseInt(entry); var score1 = entry; total = total + score1; entry = prompt("Enter test score"); entry = parseInt(entry); var score2; total = total + score2; entry = prompt("Enter test score"); entry = parseInt(entry); var score3 = entry; total = total + score3; //calculate the average average = parseInt(total/3); </script> </head> <body> <script> document.write("<h1>The Test Scores App</h1>"); document.write("Score 1 = " + score1 + "<br>" + "Score 2 = " + score2 + "<br>" + "Score 3 = " + score3 + "<br><br>" + "Average score = " + average + "<br><br>"); </script> Thanks for using the Test Scores application! </body> </html>
Addition assignment, The addition assignment operator adds the value of the right operand to a variable and assigns the result to the variable. Unary plus (+), The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already. Simplified version: var total = 0; var score1 = +prompt("Enter test score"); //Cast it to Number total += score1; //Add it to total var score2 = +prompt("Enter test score"); total += score2; var score3 = +prompt("Enter test score"); total += score3; var average = parseInt(total / 3); document.write("<h1>The Test Scores App</h1>"); document.write("Score 1 = " + score1 + "<br>" + "Score 2 = " + score2 + "<br>" + "Score 3 = " + score3 + "<br><br>" + "Average score = " + average + "<br><br>");
Average of input prompt numbers
I am having an issue with getting the average of the numbers that are inputted through a prompt window. I need to display the numbers like i have so far, but I can't seem to get them to add together to get the average. here is my code so far. <html> <body> <script type="text/javascript"> function show_prompt() { i = 0; do { var number = prompt("Please Enter a Number"); var number = parseInt(number); i++; document.write("Number: " + number); document.write("<br>"); } while (i < 5); } show_prompt(); var avrg = number + number + number + number + number document.write('Average of scores : ' + avrg); </script> </body> </html>
You have to move calculation inside function. Also you can do it simplier: function show_prompt() { var i = 0; var sum = 0;//declare a variable to keep the sum of numbers do { var number = prompt("Please Enter a Number"); sum += parseInt(number); //sum the numbers here i++; document.write("Number: " + number); document.write("<br>"); } while (i < 5); document.write('Average of scores : ' + sum / i);//use the sum of the numbers divide by the the numbers the user enters } show_prompt(); Tried to comment your old code with the mistakes: function show_prompt() { i = 0; do { //there is no need to declare number twice //also you don't sum somewhere the numbers you get from the user var number = prompt("Please Enter a Number"); var number = parseInt(number); i++; document.write("Number: " + number); document.write("<br>"); } while (i < 5); } show_prompt(); //number is out of scope of function show_prompt so is undefined var avrg = number + number + number + number + number //to get an avg you have to divide the sum by the number document.write('Average of scores : ' + avrg);
Notice your var number is scoped within show_prompt(), it is not visible outside of it. You need to have your show_prompt function not loop, and return the number, and have another function that calls show_prompt multiple times, takes the returns and calculate the average.. Also, your code is just calculating the sum, not the average I'm not going to show you the exact code, but here's the idea calc_average: var sum=0; loop 5 times: sum = sum + show_prompt(); average = sum/5; show_prompt: var number = prompt('blah blah'); return number