How are these operators affecting this simple javascript program? - javascript

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;

Related

Counting occurrences of integer from random outcome

I'm fairly new to coding and have this practice that I can't figure out the last part of it.
I'm rolling three dice and supposed to count how many combined value of sevens I get at 1000th roll.
Do I have to create an array? the hint given to me was to create a counter variable. But I can't find any solution. I know it must be something simple. I need your guidance!
var getRandomInt = function(x) {
var result = 0;
result = Math.floor((Math.random() * x) + 1);
return result;
};
//variables I need
var diceOne = 0;
var diceTwo = 0;
var diceThree = 0;
var diceSum = 0;
var roll = 0;
var average = 0;
for (var i = 1; i <= 1000; i++) {
//Simulate a Dice Roll
diceOne = getRandomInt(6);
diceTwo = getRandomInt(6);
diceThree = getRandomInt(6);
roll = roll + 1;
diceSum = diceOne + diceTwo + diceThree;
average += diceSum / 1000;
console.log("Roll #" + roll);
console.log("Value of Dice 1 is " + diceOne);
console.log("Value of Dice 2 is " + diceTwo);
console.log("Value of Dice 3 is " + diceThree);
console.log("The Sum of the Dice is " + diceSum);
// Announce average and count of 7s
if (i == 1000) {
console.log("The Average is " + average);
}
}
If you need to count the times the 3 dice add up to 7, you can create a variable to keep track of this.
Inside your loop, you increase this by one everytime diceSum is 7.
var getRandomInt = function(x) {
var result = 0;
result = Math.floor((Math.random() * x) + 1);
return result;
};
//variables I need
var diceOne = 0;
var diceTwo = 0;
var diceThree = 0;
var diceSum = 0;
var roll = 0;
var average = 0;
var sevenCount = 0;
for (var i = 1; i <= 1000; i++) {
//Simulate a Dice Roll
diceOne = getRandomInt(6);
diceTwo = getRandomInt(6);
diceThree = getRandomInt(6);
roll = roll + 1;
diceSum = diceOne + diceTwo + diceThree;
average += diceSum / 1000;
console.log("Roll #" + roll);
console.log("The Sum of the Dice is " + diceSum);
if(diceSum === 7){
sevenCount = sevenCount + 1;
}
// Announce average and count of 7s
if (i == 1000) {
console.log("The Average is " + average);
console.log("The seven count is " + sevenCount);
}
}
They're teaching you something that's actually really good to know.
You don't have to remember all values in order to calculate the average or number of 7s. You only have to count how many 7s you've seen and keep another variables that's the sum of all the values you've seen.
Edit: if you want to count the number of 7s you've seen, you need to create a variable, say count_7s and every time you see a 7, you increment count_7s = count_7s + 1.
You need no roll count, because you loop the same amount, and you need a counter for sevens. An you could take a variable for sum and calculate later the average. This is better in terms of numerical precision.
At the end show the result of average and count of sevens.
var getRandomInt = function(x) {
return Math.floor((Math.random() * x) + 1);
},
sum = 0,
average = 0,
sevens = 0;
for (var i = 1; i <= 1000; i++) {
let diceSum = getRandomInt(6) + getRandomInt(6) + getRandomInt(6);
sevens += diceSum === 7;
sum += diceSum;
}
average = sum / 1000;
console.log("The Average is " + average);
console.log("The Count of Sevens " + sevens);

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.

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

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 + ".");

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.

javascript: summing even members of Fibonacci series

Yet Another (Project Euler) Fibonacci Question: Using (vanilla) javascript, I'm trying to sum the even numbers <= a given limit:
First, something is wrong with my 'if' statement, as some of the results (below) are wrong:
function fibonacciSum(limit) {
var limit = limit;
var series = [1,2];
var sum = 0;
var counter = 0;
for (var i=1; i<=33; i++) { // 33 is arbitrary, because I know this is more than enough
var prev1 = series[series.length-1];
var prev2 = series[series.length-2];
var newVal = prev1+prev2;
series.push(newVal);
counter ++;
console.log("series "+ counter + " is: " + series);
if (series[i] % 2 === 0 && series[i] <= limit) { // intending to sum only even values less than/equal to arbitrary limit
// sum = sum + series[i];
sum += series[i];
}
/*
var sum = series.reduce(function(a,b) {
/*
possible to filter here for even numbers? something like:
if (a %2 === 0)
*/
return a+b;
});
*/
console.log("SUM " + counter + ": " + sum);
} // for loop
} // fibonacci
fibonacciSum(4000000);
Results:
series 1 is: 1,2,3
SUM 1: 2
series 2 is: 1,2,3,5
SUM 2: 2
series 3 is: 1,2,3,5,8
SUM 3: 2 // looking for a '10' here
series 4 is: 1,2,3,5,8,13
SUM 4: 10
series 5 is: 1,2,3,5,8,13,21
SUM 5: 10
series 6 is: 1,2,3,5,8,13,21,34
SUM 6: 10 // looking for '44' here
Can someone please explain why neither of these working as intended?
if (series[i] % 2 === 0) { ...
... or
if (series[i] % 2 === 0 && series[i] <= limit) { ...
And secondly, as you can see I had also tried to use series.reduce(... but I can't figure how to sum only the even values; is that doable/cleaner?
Thank you,
Whiskey T.
No need for arrays. Use three variables for let's say previous, current and next numbers in fibonacci sequence.
We can also begin the sequence with 2 an 3 because there are no other even numbers that will affect the result.
We initialize the sum of even numbers with 2 because it's the current number and it's even. In a do...while we advance with the numbers in sequence and if the new numbers are even we add them to the sum. Stop when limit is reached.
function fibEvenSum(limit) {
var prev = 1,
current = 2,
next;
var sum = 2;
do {
next = prev + current;
prev = current;
current = next;
if (current >= limit)
break;
if (current % 2 == 0)
sum += current;
} while (true)
return sum;
}
This algorithm can be improved using properties of odd and even numbers:
odd + odd = even
even + even = even
even + odd = odd
This should work for you...
var fibonacciSum = function(limit) {
var nMinus2 = 1, nMinus1 = 2, evensFound = [2], sum = nMinus1;
while (sum <= limit){
var n = nMinus1 + nMinus2;
if (n % 2 == 0){
sum += n;
if (sum > limit){
break;
}
evensFound.push(n);
}
nMinus2 = nMinus1;
nMinus1 = n;
}
console.log("Evens found - " + evensFound);
return evensFound;
};
var evensFound1 = fibonacciSum(4),
evensFound2 = fibonacciSum(10),
evensFound3 = fibonacciSum(60),
evensFound4 = fibonacciSum(1000);
$(evenResults).append(evensFound1
+ "<br/>" + evensFound2
+ "<br/>" + evensFound3
+ "<br/>" + evensFound4);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="evenResults"></div>
A solution in the spirit of the one your attempted — with arrays — though as pointed out, they are not necessary.
var i = 0, sequence = [1, 2], total = 0;
while (sequence.slice(-1)[0] < 4000000) {
sequence.push(sequence.slice(-1)[0] + sequence.slice(-2)[0]);
}
for ( i; i <= sequence.length; i++ ) {
if ( sequence[i] % 2 === 0 ) {
total += sequence[i];
}
}

Categories

Resources