Cannot get a JavaScript program to add odd numbers - javascript

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.

Related

I want to write javascript code to get a addition countdown

so basically this the prompt:
Addition countdown
you enter a number and the code should be adding a number while countingdown, for example if the user enter 10, then the result should be:
10 + 9 + 8 + 7 + 6 + 5 + 4 +3 +2 +1=55.
This is what I have so far:
var num = Number(prompt("Enter a Number Greater than zero"));
while (num > 0){
first = num;
second = num-=1;
document.write(first + " +" + second + " +");
value = first + num;
document.write(value)
num--;
}
but I keep on getting something like this:
4 +3 +72 +1 +3 (let's say 4 is the number the user inputs)
I'm stuck can someone please help me????!!
You can keep total in one variable outside of while loop.
var num = Number(prompt("Enter a Number Greater than zero"));
var total = 0;
while (num > 0) {
total += num;
document.body.innerHTML += (num == 1 ? num + ' = ' + total : num + ' + ');
num--;
}
You could change the algorithm a bit, because for the first value, you need no plus sign for the output.
var num = Number(prompt("Enter a Number Greater than zero")),
value = 0;
document.body.appendChild(document.createTextNode(num));
value += num;
num--;
while (num > 0) {
document.body.appendChild(document.createTextNode(' + ' + num));
value += num;
num--;
}
document.body.appendChild(document.createTextNode(' = ' + value));

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];
}
}

Extra + in output when looping; javascript

My desired output is: 5 + 6 + 7 + 8 + 9 + 10 = 45
The output I'm getting is: 1 + 2 + 3 + 4 + 5 + = 15 (with an extra + side on the end). I'm not sure how to get it to output without the extra + at the end, and am clearly not searching for the right terms to figure it out. Thanks!
Here's my code:
function exercise7Part2() {
// PART 2: YOUR CODE STARTS AFTER THIS LINE
// Declare variables
var loopStart;
var loopMax;
var total;
// Assignments
loopStart = Number(prompt("Enter a number:"));
loopMax = Number(prompt("Enter a number larger than the last:"));
total = 0;
// Processing
while (loopStart <= loopMax)
{
total += loopStart;
document.write(loopStart + " + ");
loopStart++;
}
document.write(" = " + total);
}
It's because you're printing loopState + "+" which will always print the + at the end. Instead you must check if it's the last value and prevent the + from printing or else, use a ternary operator to print it.
In this example, I'm checking if both loopStart and loopMax are not equal. if they're not equal then am appending + at the end.
It will be like:
document.write(loopStart+ (loopStart!=loopMax ? "+" : ""));
Here (loopStart!=loopMax ? "+" : "") is a ternary operator. The loopStart!=loopMax is an boolean expression. It's evaluated and if it's true the first parameter after ? will be used so in this case + and if its false anythign after : will be used so in this case its "" empty string.
// Declare variables
var loopStart;
var loopMax;
var total;
// Assignments
loopStart = Number(prompt("Enter a number:"));
loopMax = Number(prompt("Enter a number larger than the last:"));
total = 0;
// Processing
while (loopStart <= loopMax)
{
total += loopStart;
document.write(loopStart+ (loopStart!=loopMax ? "+" : ""));
loopStart++;
}
document.write(" = " + total);
With normal if condition block
while (loopStart <= loopMax)
{
total += loopStart;
if(loopStart===loopMax) {
document.write(loopStart);
} else {
document.write(loopStart+ "+");
}
loopStart++;
}
// Declare variables
var loopStart;
var loopMax;
var total;
// Assignments
loopStart = Number(prompt("Enter a number:"));
loopMax = Number(prompt("Enter a number larger than the last:"));
total = 0;
// Processing
while (loopStart <= loopMax)
{
total += loopStart;
document.write(loopStart+ (loopStart!=loopMax ? "+" : ""));
loopStart++;
}
document.write(" = " + total);

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