Why is my Javascript for loop concatenating numbers rather than adding? - javascript

I'm trying to write a little snippet where prompts ask the user for 5 numbers and computes the total of the numbers.
So far I have this:
var counter, number, total;
for(counter = 0; counter < 5; counter++) {
number = parseFloat(prompt("Enter a number:"));
total += number;
}
document.write("The total is " + total + ".");
However the 'total' returns " " for example, rather than a sum of 15.
How do I fix this?
Thanks in advance!

You should initialize your total var to 0:
var counter, number, total = 0;
for(counter = 0; counter < 5; counter++) {
number = parseFloat(prompt("Enter a number:"));
total += number;
}
document.write("The total is " + total + ".");

You have to set total to 0, like this:
var counter, number, total = 0;
for(counter = 0; counter < 5; counter++) {
number = parseFloat(prompt("Enter a number:"));
total += number;
}
document.write("The total is " + total + ".");

Related

I don't seem to get how the loop is working so that the answer is 55, how the increment is being done?

This is the actual code from the book Eloquent Javascript:
var total = 0;
var count = 1;
while (count <= 10) {
total += count;
count += 1;
}
console.log(total) 55
Under are the things that I tried so I could understand but it all seems too weird for me.
var total = 0;
var count = 1;
while (count <= 1) {
total += count;
count += 1;
}
console.log(total) 1
var total = 0;
var count = 1;
while (count <= 2) {
total += count;
count += 1;
}
console.log(total) 3
var total = 0;
var count = 1;
while (count <= 3) {
total += count;
count += 1;
}
console.log(total) 6
var total = 0;
var count = 1;
while (count <= 4) {
total += count;
count += 1;
}
console.log(total) 10
var total = 0;
var count = 1;
while (count <= 5) {
total += count;
count += 1;
}
console.log(total) 15
Can someone tell me how this is working bc I don't get it?
Follow it through with pencil and paper (or the debugger built into your IDE and/or browser):
total starts at 0
count starts at 1
The loop continues as long as count <= 10 is true
On each loop iteration
total's value is increased by count. (value += count is basically total = total + count).
count is increased by 1.
So the first time, total (0) + count (1) = 1, which is put back in total. The second time, total (1) + count (2) = 3, which is put back in total. Etc.
If you follow it through until count is 11, you'll see you get 55 in total.
This is a bit of a confusing example, but we can step through it. As you can guess when the while loop ends, the variable count will have the value 11. However total is equal to 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55. Every time the loop runs the count value will be added to the total value.
Try to run this code and understand each print statement:
var total = 0;
var count = 1;
while (count <= 10) {
console.log(total)
console.log(count)
total += count;
count += 1;
console.log(count)
console.log(total)
}
console.log(total)
you're doing
total += count
which is the same as
total = total + count
You're then doing
count += 1
which is the same as
count = count + 1
What you're essentially doing is a cumulative count. Total = 0, then total = 1 + 0, then total = 2 + 1 + 0... all the way up to 10 + 9 + 8... + 1 + 0 which is 55.

Finding the factorial using a loop in 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);

Cannot get a JavaScript program to add odd numbers

Here's the problem:
Create a sum program that calculates the sum of all odd numbers between 1 and the number entered by the user. For example if the user enters in the number 7 the program would calculate 1 + 3 + 5 + 7. The total and the expression should be displayed on the document. The answer would be 16.
My code so far
//declare the variables
var sternum = prompt("enter a number");
var tantalum = 1;
var increase = 1;
var expression = "+";
//finding the sum
document.write(" the sum of all numbers are: ");
do {
if(sternum % 2 == 0) {
}
else{
document.write(increase + expression);
increase = increase + 1;
tantalum = tantalum + increase;
}
}while(increase < sternum);
document.write(sternum + " = " + tantalum);
You have created an infinite loop. Make sure you increment increase every iteration:
var sternum = prompt("enter a number");
var tantalum = 0;
var increase = 1;
var expression = "+";
//finding the sum
document.write(" the sum of all numbers are: ");
do {
if(increase % 2 == 0) {
}
else{
document.write(increase + expression);
tantalum = tantalum + increase;
}
increase = increase + 1;
}while(increase <= sternum);
document.write(" = " + tantalum);
To make it more efficient you could change increase = increase + 1; to increase = increase + 2;. No need to process even numbers. Also tantalum should be set to 0 to start.

How are these operators affecting this simple javascript program?

This is probably embarrassingly obvious but I can't seem to figure it out: I've researched what all of these operators mean and commented out what I think they're doing. Apparently total = 55. I thought it would = 11. Where am I going wrong? Thanks a lot.
var total = 0;
var count = 1;
while (count <= 10) { // while "count" is less than or equal to 10 do...
total += count; // total = total + count (total = 0 + count)
count += 1; // count = 1 + 1 (adding 1 to count every loop until count is equal to 11)
};
console.log(total); -> 55
// total is 0 + count
// when the program ends count = 11
// 0 + 11 = 11
Like others have stated in the comments. You are incrementing your count and total. Do one or the other.
Here's what your code is currently doing:
var total = 0;
var count = 1;
var iteration = 0;
var div = document.getElementById("div");
while (count <= 10) {
total += count;
count += 1;
iteration++;
div.innerHTML += "Iteration " + iteration + ": ";
div.innerHTML += "count = " + count + "; ";
div.innerHTML += "total = " + total + ";<br /><br />"
};
<div id="div"></div>
There's several ways you can do this.
One way would be to just increment the count and total by one at each iteration:
var total = 0;
var count = 1;
while (count <= 10) { // while "count" is less than or equal to 10 do...
total++ // Increase the total by 1
count++ // Increase the count by 1
};
document.getElementById("result").innerHTML = total
<div id="result"></div>
but this only gives you a result of 10 because your count is starting at 1
Another way would be to just increment your count, then assign your count to your total outside of the loop:
var total = 0;
var count = 1;
while (count <= 10) { // while "count" is less than or equal to 10 do...
count++ // Increase the count by 1
};
total = count;
document.getElementById("result").innerHTML = total
<div id="result"></div>
Or, remove count altogether:
var total = 0;
while (total <= 10) {
total++;
};
document.getElementById("result").innerHTML = total
<div id="result"></div>
Or, my preferred method, would be to change your loop from a while to a for loop
var total = 0;
for (var i = 0; i <= 10; i++) {
total++;
}
document.getElementById("result").innerHTML = total
<div id="result"></div>
To understand what is happening, try to write:
console.log(total);
console.log(count);
Inside of the while loop body.
You will see how it behaves on every iteration.
count += 1;
means:
count = count + 1;

If Statement? Don't add numbers into total variable if they are negative

Question, how do I make it so when an user-inputted number is negative, it isn't added to the total variable that will be ouput?
Code below!
function lab10logicInLoopsPart1()
{
lCounter = 1;
var total = 0;
userNumber = 0;
while(lCounter < 6) {
lCounter++;
userNumber = prompt("Enter a number.");
total += +userNumber;
document.write("Entered number was: " + userNumber + "\n");
}
document.write("\nTotal: " + total);
}
After prompting the user to enter a number, just check it's not a negative with an if statement:
if(userNumber >=0)
{ //do your stuff here}

Categories

Resources