adding a number to an array in JavaScript [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I want to add a number to an array in JS, but only if the number is a multiple of three. Here's my code:
var numbers = [];
for (i = 1; i <= 200; i++) {
if i % 3 === 0 {
numbers.push(i);
}
}
alert(numbers);
But the code does not print anything. It works fine without the if statement though, when I just add the numbers between 1 and 200...
Can you find the error?
Thanks!

The quick fix is if (i % 3 === 0) {
But why don't you write for (i = 3; i <= 200; i += 3) instead and remove the modulus check?

You need some brackets for the if statement.
var numbers = [];
for (i = 1; i <= 200; i++) {
if (i % 3 === 0) {
// ^ ^
numbers.push(i);
}
}
console.log(numbers);

var numbers = [];
for (var i = 1; i <= 200;i++) {
if (i % 3 == 0) { // () execution brackets necessary
numbers.push(i);
}
}
// better way to do
var numbers = [];
var i = 3; // better to declare it here
for (; i <= 200; i += 3) {
// if (i % 3 == 0) { not required as Bathsheba's answer
numbers.push(i);
// }
}

Related

How to trace/understand an algorithm given the JavaScript source code? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 18 days ago.
Improve this question
I am trying to gain some JavaScript knowledge and I found this code challenge and its solution, but I don't quite understand the solution. I would like to get an explanation.
The Problem
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to n? (smallestMult(5) should return 60)
The Solution
function smallestMulT(num) {
let res = 0;
let i = 1;
let found = false;
while (found === false) {
res += num;
while (res % i === 0 && i <= num) {
if (i === num) {
found = true;
}
i++;
}
i = 1;
}
return res;
}
The solution works, I just want to understand how it works. For example, why was it necessary to repeat i = 1; inside the while loop?
Its because the function checks for each number between 1 and x (num) if its divisible by that number.
So what it basically does when you put in 5 is:
It checks if 1 is divisible by 1 (i)
it checks if 1 is divisible by 2 (i)
it checks if 1 is divisible by 3 (i)
it checks if 1 is divisible by 4 (i)
it checks if 1 is divisible by 5 (i)
Sets i back to 1
checks next number
It checks if 2 is divisible by 1 (i)
and so on....
function smallestMulT (num){
let res = 0;
let i = 1;
let found = false;
while (found === false) {
res += num;
while (res % i === 0 && i <= num) {
if (i === num) {
found = true;
};
i++;
};
i = 1;
};
return res;
};
console.log(smallestMulT(5));

Finding the outlier in an array [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have written a function which given an array full of all odd numbers and one even number, it returns the one even number. Given an array full of all even numbers and one odd number, it returns the one odd number.
ex : findOutlier([2,6,8,10,3]) will return 3, since it is the only odd number in the array
I have gotten this to work, but for some reason it will not work with certain large negative numbers? It returns undefined instead of the outlier number.
Here is my code:
function findOutlier(integers){
let testingForOdds = true;
let evenCounter = 0;
let oddCounter = 0;
for (let i = 0; i < 3; i++){
if (integers[i] % 2 === 0){
evenCounter = evenCounter + 1
if (evenCounter === 2){
testingForOdds = true;
}
}
else if (integers[i] % 2 === 1){
oddCounter = oddCounter + 1
if (oddCounter === 2){
testingForOdds = false;
}
}
}
if (testingForOdds){
for (let i = 0; i < integers.length; i++){
if (integers[i] % 2 === 1){
return integers[i]
}
}
} else {
for (let i = 0; i < integers.length; i++){
if (integers[i] % 2 === 0){
return integers[i]
}
}
}
}
findOutlier([-100000000007, 2602, 36]);
For some reason, findOutlier([-100000000007, 2602, 36]); returns undefined. However, findOutlier([2,6,8,10,3]) will successfully return 3. Why is this happening?
As Michael has pointed out, you get the issue because -100000000007 % 2 evaluates to -1. As a side note, you can optimize your logic to reduce the number of comparisons done like so:
function findOutlier(arr) {
let isEven = true;
const a = arr[0];
const b = arr[1];
if (([-1, 1].includes(a % 2) && [-1, 1].includes(b % 2))) {
isEven = false;
} else if (!(a % 2 === 0 && b % 2 === 0)) {
const c = arr[2];
if (c % 2 === 1) isEven = false;
}
for (let i = 0; i < arr.length; i += 1) {
const even = arr[i] % 2 === 0;
if (even !== isEven) return arr[i];
}
}

FizzBuzz with a for loop switch statement [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I have recently been following a Javascript course on CodeCademy and have got through Switch Statements and For Loops, I then tried to create a FizzBuzz game that prints to the console using a combination of the two. I can not figure out what I have done wrong.
I have tried removing the variables using their plain text counterparts and still achieved nothing. I don't even get any errors.
let fizzCalc = (i % 3 === 0);
let buzzCalc = (i % 5 === 0);
for ( var i = 0; i >= 100; i++) {
switch(true) {
case fizzCalc:
console.log('Fizz');
break;
case buzzCalc:
console.log('Buzz');
break;
case fizzCalc && buzzCalc:
console.log('FizzBuzz');
break;
default:
console.log(i);
break;
}
}
Let's look at these two lines of code:
let fizzCalc = (i % 3 === 0);
let buzzCalc = (i % 5 === 0);
You probably get an error here that i is undefined. The thing to keep in mind is that these formulas are all evaluated immediately. They aren't saved to evaluate them when you use the names fizzCalc and buzzCalc at a later time.
To fix the problem, you can move these two lines into your for loop:
for ( var i = 0; i >= 100; i++) {
let fizzCalc = (i % 3 === 0);
let buzzCalc = (i % 5 === 0);
// ...
}
But now you will find that the loop never runs. This is because you have typed >= when you mean <=. So one more change should fix the problem:
for ( var i = 0; i <= 100; i++) {
let fizzCalc = (i % 3 === 0);
let buzzCalc = (i % 5 === 0);
// ...
}
Here are the things you need to do to fix this:
for (var i = 0; i <= 100; i++) { // fixed loop to be less than
let fizzCalc = (i % 3 === 0); // moved vars inside loop to give access to i
let buzzCalc = (i % 5 === 0);
switch (true) {
case fizzCalc && buzzCalc: // moved this case up so it matches first
console.log('FizzBuzz');
break;
case fizzCalc:
console.log('Fizz');
break;
case buzzCalc:
console.log('Buzz');
break;
default:
console.log(i);
break;
}
}

What is wrong in my this Javascript code for writing a Fibonacci series? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
Fibonacci series code goes here
function fibonnica(g) {
var result, n;
if (g == 1) {
return g; //if enterd no is 1 then 1 that is very apparent
} else {
result = g; //7
n = g - 1; //6
while (n > 0) {
result *= n ///7*6 second time 7*5 and so on..
n = n - 1; //n=5
}
return result;
}
}
console.log(fibonnica(7)); //why 7 is the output
please only tell the error not the solution i want to push myself
You need to switch the condition to check greater number, than smaller numbers.
while (n > 0) {
// ^
function fibonnica(g) {
var result, n;
if (g == 1) {
return g;
} else {
result = g;
n = g - 1;
while (n > 0) {
result *= n;
n = n - 1;
}
return result;
}
}
console.log(fibonnica(7)); // 5040

Getting to grips with a basic JS for and if loops [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have a very basic loop that I currently don't understand fully.
for (var i = 1; i <= 100; i++) {
if (i / 3) {
$(".counterWrapper").append("fizz" + "<br>");
}
else {
$(".counterWrapper").append(i + "<br>");
}
}
Basically I am wanting it to only return the word 'fizz' if the variable i's value is divisible by 3. Currently it is only returning the word 'fizz', so it would seem that it is getting stuck in the if loop and running it each time.
This is a very simple loop, but I think it might do with the way I am doing my comparisons. What would be the best way in order for it to work out if the variable i is dividable by 3?
Your conditional is always going to be true. Use the modulus operator
if (i % 3 == 0) {
// print 'fizz'
}
In javascript true and false are treated uniquely. 0 is false, any other number is true. Take a look at:
if (i / 3) {
$(".counterWrapper").append("fizz" + "<br>");
}
What you're saying is if i divided by 3 append fizz. So when looping:
if (0 / 3) // this would be 0 so it would be false
if (1 / 3) // this would not be zero so it is true
if (2 / 3) // this would not be zero so it is true
and so on.
You need to use modulo (%) which checks for remainders and use a comparison.
if (i % 3 === 0)
If you ran through the loop
if (0 % 3 === 0) // remainder is 0, so it is true
if (1 % 3 === 0) // remainder is 1, so it is false
if (2 % 3 === 0) // remainder is 2, so it is false
if (3 % 3 === 0) // remainder is 0, so it is true
The value in your if statement isn't a valid comparison. Try using modulo and equality:
for (var i = 1; i <= 100; i++) {
if (i % 3 == 0) {
$(".counterWrapper").append("fizz" + "<br>");
}
else {
$(".counterWrapper").append(i + "<br>");
}
}
if ( i % 3 === 0 )
This is a very basic question, with a very basic syntax issue.

Categories

Resources