I am new to JS. For fun I want to create an infinite loop that outputs the following way:
1+1=2, 2+2=4, 4+4=8, 8+8=16 and so on...This is what I have so far. I created a For loop to concise my theories/methods for practice, but I still can't get it to work properly.
for (let i = 0; i < 5; i++) {
num1 = i;
sum = i * 2;
answer = sum * 2;
console.log(sum + " + " + sum + " = " + answer * i);
}
At the moment you're just multiplying variables by two when really you want to take the result of adding two numbers together and use it in the next iteration.
Declare a step variable outside of the loop. On each iteration assign the the sum of two steps to an answer variable, log the result, and then assign answer to step.
let step = 1;
for (let i = 1; i < 10; i++) {
let answer = step + step;
console.log(`${step} + ${step} = ${answer}`);
step = answer;
}
Additional documentation
Template/string literals
Related
Trying to create a piece of code that return all numbers below 1000 that are multiples of three. This is the relevant piece of code.
<script>
var i = 1;
var mplesOf3 = [0];
var myNum = 0;
while (myNum < 1000){
(3 * i) = myNum;
mplesOf3.push(myNum);
i++;
};
alert(mplesOf3);
</script>
The code runs in a html page, hence the style tags and alert.
The code basically trying to do 3x1 then 3x2 then 3x3 so on and so forth until the result is over 1000. I came up with the concept days ago and I'm still not sure why its not running properly.
For the record I've seen other solutions to how to do this but because I'm learning and want to improve I want to know why this solution doesn't work.
Thank you in advance
Edit: I should have known the mistake would be something stupid. I wrote (3 x 1) = n on the pseudocode and just didn't spot the mistake because nothing seem wrong to me. Thank to all parties, will accept an answer when I can.
Your JavaScript engine should be telling you you have a syntax error (look in the web console if you're using a browser). You can't have an expression like (3 * i) on the left-hand side of an assignment. In JavaScript, the thing on the right of the = is evaluated, and assigned to the thing on the left.
Your algorithm would also result in 1002 being pushed, because you're not testing the result of setting myNum = 3 * i until after pushing.
Sticking with your original algorithm but fixing those two things:
var i = 1;
var mplesOf3 = [0];
var myNum;
while ((myNum = 3 * i) < 1000){
mplesOf3.push(myNum);
i++;
} // Note: No semicolon here, you don't put semicolons after blocks
// attached to control-flow statements
console.log(mplesOf3);
This bit:
while ((myNum = 3 * i) < 1000){
evaluates 3 * i, assigns the result to myNum, and then checks that that value is < 1000.
That said, it would probably be simpler (fewer variables, less multiplication) to use a for and myNum += 3 in the increment section:
var mplesOf3 = [0];
var myNum;
for (var myNum = 3; myNum < 1000; myNum += 3) {
mplesOf3.push(myNum);
}
console.log(mplesOf3);
There's also no particularly good reason to special-case the 0 like that, so I'd probably leave it out of the array initially and start counting from 0:
var mplesOf3 = [];
var myNum;
for (var myNum = 0; myNum < 1000; myNum += 3) {
mplesOf3.push(myNum);
}
console.log(mplesOf3);
This is invalid:
(3 * i) = myNum;
Instead, do this:
myNum = (3 * i);
I would do it this way, and this takes care that even the last one stays below 1000:
<script>
var i, mplesOf3;
mplesOf3 = [];
for (i=0; i<1000; i++){
if (i % 3 === 0){
mplesOf3.push(i);
}
}
alert(mplesOf3);
</script>
Update (see comments):
For better efficiency your code is better, and here is a complete fix that even takes care of the last value to be below 1000:
var i = 1;
var mplesOf3 = [0];
var myNum = 0;
while (myNum < 1000){
myNum = 3 * i;
myNum < 1000 && mplesOf3.push(myNum);
i++;
};
alert(mplesOf3);
Another improvement would be to avoid the comparison in each loop and always remove the last item from the final array:
var i = 1;
var mplesOf3 = [0];
var myNum = 0;
while (myNum < 1000){
myNum = 3 * i;
mplesOf3.push(myNum);
i++;
};
mplesOf3.pop();
alert(mplesOf3);
maybe your mistake is (3 * i) = myNum;
you just need to: myNum=(3 * i);
First name then assign a value;
I'm learning basics of JavaScript. I try to code a program that logs the following scheme to the console:
*
* *
* * *
* * * *
* * * * *
* * * * *
* * * *
* * *
* *
*
I managed to get first half of the task by the code:
var x = 5;
var line;
for(var i = 0; i<x; i=i+1){
line = "";
for(var j=0; j<x; j=j+1){
if(j <= i){
line = line + " * ";
}
}
console.log(line);
}
So it looks like:
*
* *
* * *
* * * *
* * * * *
Could anybody give me a hint how to get the secod part of the scheme? I'd like to use another loop like the one I have but to revert it's action so that there would be less and less stars in each line.
Hints: You need to decrement i and j in the for loop and turn-around the <. instead of starting var i = 0 start at the end with 5.
With two for loops after another. The first one adds stars and the second one removes stars:
var line = "";
for (var i = 0; i < 5; i += 1) {
line += "*";
console.log(line);
}
for(var j = 5; j > 0; j -= 1) {
line = line.replace(line[j], "");
console.log(line);
}
spoiler:
What about just using a while loop?
var count = 0,
i = 1,
addition = 1,
str = null;
while (i) {
str = new Array(i+1).join('*');
console.log(str);
if (i === 5) {
console.log(str);
addition = -1;
}
i += addition;
}
You can, as one possible solution, put another if clause inside of your loop (read carefully):
If the line index reached half of the pyramid (maximum line length), start printing maximumLineLength * 2 - index - 1 instead.
This will essentially change the behaviour of the loop after the half is reached, so that the number of starts will start to decrease instead of increasing.
Another solution, if you're keeping the number of stars in the string, would be to add them until maxLineLength is reached, and then subtract them until you go back to 0 (you can use a boolean flag for that).
I'm not posting actual code to avoid spoiling the solution.
I think the solution with the conditionals and the one with the two loops are the ones you should use but you can compute the number of asterisks with a bit of modular arithmetic directly:
var x = 5;
var line;
for(var i = 1;i < x * 2;i++){
line = '';
for(var j = 0;j < Math.abs( (i+3) % 8 - 4) + 1;j++){
line = line + ' * ';
}
console.log(line);
}
I used a trick that will most probably be seen here as a little bit dirty but it works. The sequence I use here is 1,2,3,4,5,4,3,2 and to get the last 1 I just run it one more time.
In general:
To get a sequence from 1 to x and back to 1 again (with x > 1) run the outer loop x*2 times with Math.abs( (i+(x - 2)) % (2*x - 2) - (x - 1)) + 1 as the upper limit for the inner loop with i going from 1 to 2x-1.
Proof is left as an exercise for the student.
It's anti-pattern; why would you want this?
Nevertheless - accumulative variable:
var x = 5,
y,
line,
result = [];
while (x--) {
y = 5 - x;
line = '';
while (y--) {
line = line + '*';
}
result.push(line);
}
document.write(result.join('<br>'));
document.write('<br>');
document.write(result.reverse().join('<br>'));
Many solutions are possible but the simplest, like you suggest, is reverting the loop; this is what loop statement should look like:
for(var i = x-1 ; i>=0 ; i--)
Basically you have to change the for-loop conditions that will go backwards starting from the max-value , this is the first statement part and is called initializer ;
the loop must stop/break at 0 , second part of statement called test (until the loop satisfies this condition it will go on in next iteration );
the last part of statement is the iteration update (how the state should change in next loop);
that said changing the statement you should be able to keep your body unchanged :
var x = 5;
for (var i = x - 1; i >= 0; i--) {
line = "";
for (var j = 0; j < x; j = j + 1) {
if (j <= i) {
line = line + " * ";
}
}
console.log(line);
}
To do this you must multiply 6*5*4*3*2*1. To verify your loop is working correctly, the value you are looking for as a result is: 720
var dvDDG = document.querySelector("#ddg");
for(var i = 0; i < 7; i++) {
//remainder..
if( (i*7) == 720 ) {
dvDDG.innerHTML += i + "<br />";
}
}
I'm not entirely certain what you're trying to do with the code you have, it will simply check all numbers zero through six inclusive, and output the value which, when multiplied by seven, is equal to 720.
Since the highest value you'll get is 6 x 7 = 42 (nowhere near 720), you'll see nothing.
The pseudo-code for what you're after would be along the lines of:
fact = 1
for i = 2 to N inclusive:
fact = fact * i
print fact
Turning that into Javascript (or any procedural language for that matter) should be fairly simple, such as with:
function fact(n) {
res = 1
for (var i = 2; i <= n; i++) {
res = res * i;
}
return res
}
alert(fact(6))
It's fairly simple:
var factorial = 1;
var num = 6;
for (var i = 1; i <= num; i++){
factorial *= i;
}
There you go, your answer is the variable factorial. Just copy it into any output function you want. Be careful though, factorial can get pretty huge very fast. Try not to experiment on numbers that much larger that 6.
I'm doing the Euler project problem 2 in which the objective is to sum the even numbers of the fibonacci sequence that have a value of less than 4 million. I've searched a bit and I've seen several solutions using a while loop but nothing simple using a for loop. I'm curious why I'm returning zero with the following code:
var array = [];
array[0] = 0;
array[1] = 1;
var total = 0;
for(var i=2;total<=4000000;i++) {
array[i] = array[i-1] + array[i-2];};
for(var x=0;x<array.length;x++){
if(array[x]%2 === 0){
total += array[x]};};
alert(total);
I'm guessing the problem is in my for loop using the total variable. I couldn't get it to work using array[i]<=4000000 either and I'm really curious behind the why here. Anyone know why this is? What can I change in the for loop condition (second statement) to get a correct total here?
First of all there is an infinite loop at first for. Your condition must be array[i-1] < 4000000. After that your second for loop will find the correct result.
Also for the problem, you don't need to store all fibonacci numbers then find sum of even numbers.
You can calculate sum when calculating fibonacci.
var first = 0;
var second = 1;
var sum = 0;
for(var current=first+second; current < 4000000; current = first+second){
if(current%2 === 0){
sum+=current;
}
first = second;
second = current;
}
I fixed it for you.
var i, data = [ 0, 1 ], total = 0;
for (i = 2; i <= 4000000; i++)
{
data[i] = data[i - 1] + data[i - 2];
if (data[i] % 2 === 0)
{
total += data[i];
}
}
alert(total);
I'm not sure what you termination condition should be like, you say have a value of less than 4 million, but this is ambiguous. Maybe it should be total <= 4000000 or data[i] <= 4000000. Your phrasing is not precise enough.
Sorry but for me your code going in a dead loop. first "for" use total as check but it's never incremented. If you want This is a solution for fibonacci sequence based on dinamic programming with memoization tecnic.
var f1 = 1;
var f2 = 1;
for(var i = 2; i < 40000; i++){
console.info(i, f1, f2);
var temp = f1 + f2;
f1 = f2;
f2 = temp;
}
alert(f2);
This question could also be (depending on how you look at it) - How to use a for loop to do a basic math operation that adds up the sum of the multiples of 3
So I am doing Problem 1 of Project Euler.
I've (already) hit a steel-reinforced wall. I could use some help - with just a specific portion of the problem please (I am not looking for just an answer to the problem, but rather, an answer to my specific problem so I can carry on with trying to solve the remainder problem using any answer you guys provide me here)...
Anyways.
I (think I) created a for loop that will give me the multiples of 3. However, I'm trying to store the result of each iteration of the for-loop so that it adds up to the sum of those multiples i.e. I'm trying to store the result from each iteration of the loop - whether it be into an array or into a variable that takes the sum of the multiples - it doesn't matter to me - I wouldn't mind learning both methods.
I'm sure this sounds kind of confusing so let me paint my picture w/ an example...
I have a for-loop:
for (i = 1; i <= 3; i++) {
var x = 0;
x += (i * 3);
WHAT DO I DO NEXT????
^ So I would think that this gives me x with a value of 3 upon the 1st iteration of the loop, x with a value of 9 on the 2nd loop, and x with a value of 18 on the final loop. That's correct, right? (if this were returning 18 I don't think I would need to store the values of each iteration into an array)
1st iteration:
i = 1; x = 0
Original equation...
(i * 3) + x
So...
(1 * 3) + (x = 0) = 3
So after completion of the 1st loop, x has a value of 3, right???
(Question: How would I store this value of x (which is 3) - how would I store it in an array while in this stage of the for loop?)
2nd iteration of loop:
i = 2; x = 3
(2 * 3) + (x = 3) = 9
(same question as before: how would I add this value to an array?)
3rd iteration:
i = 3; x = 9
(3 * 3) + (x = 9) = 18
Q: shouldn't this be the final value of x upon completion of the for loop??? For some reason, when I run the code, the final value of x is 9, and not 18
So, basically I am trying to add the sum of the 3 values...But what do I do next? I thought my for loop would add the result of the equation after each loop to x, but instead of ending up w/ 18 (the sum of 3 + 6 + 9), x's value was 9???
Should I use an array? If so, I'm thinking I could add the return value to an array, but I'm not sure how to add the result of each iteration of the loop to an array. Maybe the following?...
for (i = 1; i <= 3; i++) {
var array = [];
x = 0;
x += (i *3);
array.push(x);
};
^ I tried running that in jfiddle, but it would only add the last value of x (9) into the array... So how would I add the value of x to an array after each iteration of the for loop??? And I'm not seeing what's wrong with my for-loop to where it's returning a value of x as 9?
Also, I'm assuming the euler problems get significantly more difficult as we progress? If so, I've got a TON of work/practice to do....
THANKS IN ADVANCE...
Just create the array once, and push the result at each iteration to the array:
var array = [];
for (i = 1; i <= 3; i++) {
var x = 0;
x += (i *3);
array.push(x);
}
Or for that matter, just use this:
var array = [];
for (i = 1; i <= 3; i++) {
array.push(i *3);
}
Or to simply get the sum of the factors, use this:
var x = 0;
for (i = 1; i <= 3; i++) {
x += i *3;
}
You are declaring var x = 0 and var array = [] at every step of the loop, try something like:
var array = [], x = 0;
for (i=1; i<4; i++){
x += (i*3);
array.push(x);
}
You can use like this:
and you have to define X out of the loop
var array = [],
x = 0;
for (i=1; i<4; i++){
x += (i*3);
array.push(x);
}