I'm trying to create javascript that will count from 1 to 1000 and push any multiples of 3, 5 into an array called multiples then print that array out using console.log(). For some reason my code isn't working. Does anyone know why?
var n;
var multiples = [];
for(n = 1; n <= 1000; n += 1) {
console.log("Counting");
}
if(n % 3 === 0) {
n.push(multiples);
}
else {
}
if(n % 5 === 0) {
n.push(multiples);
}
else {
}
if(n >= 1000) {
console.log(multiples);
}
else {
}
There are few issues with your code. Using {} in your for block designates the scope of the code executing in each iteration. So in order to access each value for n you need to be placing your conditional statements inside of the {} and not outside of them.
There is a slight syntax error with your multiples array. In order to push a value into an array you would use the arrayname followed by the dot operator and then the push function with the argument being the value pushed. In terms of multiples and n, this means multiples.push(n).
When using an if() block, else is not required.
It is generally best practice to include the variable declaration inside of for loops, and also to use ++ as opposed to += 1.
Overall, your code would need to look more like this
var multiples = [];
console.log("Counting");
for(var n = 1; n <= 1000; n++) {
if(n % 3 === 0) {
multiples.push(n);
}
if(n % 5 === 0) {
multiples.push(n);
}
}
console.log(multiples);
Related
Why does the continue statement print even numbers, but will print odd numbers if replaced by console.log() in the following?
// print even numbers
for (var i = 1; i <= 10; i++) {
if ((i % 2) != 0) {
continue;
}
console.log(i);
}
//print odd numbers
for (var i = 1; i <= 10; i++) {
if ((i % 2) != 0) {
console.log(i);
}
}
In the first example, the loop continues with the next iteration if the number is odd (and therefore the program does not reach console.log()). In this next iteration the number is even and will be printed.
The second example is quite trivial: you only print the number if it is odd.
When the continue statement is executed, the rest of the contents of the loop body are skipped and execution returns to the top of the loop, to start the next iteration of the loop. So this:
if ((i % 2) != 0) {
continue;
}
means "If i is odd, skip back to the top of the loop, don't execute the rest of the loop body." That means the odd number isn't printed.
In your second example, you're only outputting when the condition is true, so you've ended up doing the opposite output, but in a different way: Only calling console.log when the number is odd.
You can make the first one output only even numbers by removing the continue, changing the condition, and moving console.log into the if body:
// print even numbers
for (var i = 1; i <= 10; i++) {
if ((i % 2) === 0) { // *** Changed condition
console.log(i); // *** Moved `console.log`
}
}
That does even numbers in the same basic way the second one did odd numbers.
Or you can change the second one work like the first one, but in general it's best to avoid using continue (there are probably exceptions to that general rule):
// print odd numbers
for (var i = 1; i <= 10; i++) {
if ((i % 2) == 0) { // *** Changed condition
continue;
}
console.log(i);
}
This question already has answers here:
Difference between console.log and return in javascript? [closed]
(7 answers)
Closed 1 year ago.
I get different outputs when I use console.log() in my function vs when I use the return statement.
When I run the function with the return statement I get a one word output which is one of the following: 'fizz' 'buzz' or 'fizzbuzz', but when I run the function using console.log the output is counting to the limit and saying 'fizz' 'buzz' or 'fizzbuzz' whenever it comes across a multiple of 3, 5 or both/ why is this so?
input = fizzBuzz(100)
console.log(input)
function fizzBuzz(limit){
for (let i = 0; i <= limit; ++i)
if (i % 3 === 0 && i % 5 === 0)
console.log('fizzbuzz')
else if (i % 3 === 0)
console.log('fizz')
else if (i % 5 === 0)
console.log('buzz')
else console.log(i)
}
input = fizzBuzz(100)
console.log(input)
function fizzBuzz(limit){
for (let i = 0; i <= limit; ++i) {
if (i % 3 === 0 && i % 5 === 0)
return 'fizzbuzz'
else if (i % 3 === 0)
return 'fizz'
else if (i % 5 === 0)
return 'buzz'
else return i
}
}
I think it is because the return statement stops the function from executing anything further but I am not sure, still new and self teaching!
return evaluates its argument (if supplied) and ends the execution of the containing function immediately.
console.log evaluates its argument and prints it, continuing the execution of the function it's called from.
So in your example with return, the fact that you're in a for-loop that goes limit times doesn't matter, because you'll only go through it once and return from fizzBuzz.
Putting it all together with another example:
function print_dog() {
console.log('dog');
return;
console.log('cat');
}
If you then call print_dog(), you'll see the output dog, but you won't see the output cat, because return ends execution of print_dog before it can get to console.log('cat');
You are correct in stating that it is because the return statement exits the function.
This is also the case in python,java, and many other languages.
Cheers!
Here's what each different function does:
function fizzBuzz(limit) {
for (let i = 0; i <= limit; ++i)
if (i % 3 === 0 && i % 5 === 0)
console.log('fizzbuzz')
else if (i % 3 === 0)
console.log('fizz')
else if (i % 5 === 0)
console.log('buzz')
else console.log(i)
}
This iterates through to limit, and console.logs the FizzBuzz test result each time.
function fizzBuzz(limit){
for (let i = 0; i <= limit; ++i) {
if (i % 3 === 0 && i % 5 === 0)
return 'fizzbuzz'
else if (i % 3 === 0)
return 'fizz'
else if (i % 5 === 0)
return 'buzz'
else return i
}
}
This iterates through to limit, and returns a single value from the function - the result of the FizzBuzz test on the first iteration.
So essentially, one function logs all the FizzBuzz results to the console, and the other returns one FizzBuzz result, which you are logging to the console manually.
Yes, you are thinking on the correct lines.
A return statement in a function will return a value and stop further execution. Where as Console.log() is a side effect producing function that will print the arguments supplied to it in the console.
Having a console.log() inside a function is like calling a function within a function.
I'm having some frustration with this code. I may not be seeing it.
I keep getting either an "Unexpected Token" or "ILLEGAL" error (the latter which completely preplexed me, considering I've never seen an error like that before in my life.
I've been double checking the syntax and I'm thinking it may be something I'm just not catching?
function fizzBuzz(n) {
2 for (i = 0; i<=n; i++) {
3 if (n%3===0) {
4 print ("fizz")
5 }
6 if (n%5===0) {
7 print ("buzz")
8 }
9 if (i%3 !== 0 && i%5 !== 0) {
10 return [i];
11 }
12 }
13 }
14
15
16 fizzBuzz(100);
I'd be thankful for the help! <3
You need some changes:
remove line numbers,
check first for 'fizz buzz' value and use console.log for output. Then use continue statement for jumping to top for next loop,
use i instead of n for checking.
function fizzBuzz(n) {
for (i = 0; i <= n; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log("fizz buzz");
continue;
}
if (i % 3 === 0) {
console.log("fizz");
continue;
}
if (i % 5 === 0) {
console.log("buzz");
continue;
}
console.log(i);
}
}
fizzBuzz(100);
function fizzBuzz(n) {
2 for (i = 0; i<=n; i++) {
3 if (n%3===0) { You're checking if the maximum number (n) is divisible by 3.
4 print ("fizz") You should be checking i.
5 }
6 if (n%5===0) { You're checking if the maximum number (n) is divisible by 5.
7 print ("buzz") You should be checking i.
8 }
9 if (i%3 !== 0 && i%5 !== 0) {
10 return [i]; You're returning an array with a single element: i.
11 } You should print i instead.
12 }
13 }
14
15
16 fizzBuzz(100);
The line numbers are what's causing the "ILLEGAL" error. Remove them.
print in JavaScript opens the print dialog to literally print paper out of a printer. Use console.log
If a number is divisible by both 3 and 5, fizzbuzz should be printed. Your code prints fizz and buzz on separate lines.
Working version ( https://www.youtube.com/watch?v=QPZ0pIK_wsc ) :
function fizzBuzz(n) {
for (var i = 0; i <= n; i++) {
var printVal = "";
if (i % 3 === 0) {
printVal += "fizz";
}
if (i % 5 === 0) {
printVal += "buzz";
}
if (printVal === "") {
printVal = i;
}
console.log(printVal);
}
}
fizzBuzz(100);
Lets decrease number of if statements, I have seen many fizzbuzzs - I would like to try another approach
const fizzBuzz = (i = 0, ret) => {
while (++i, ret = '', i <= 100) {
if (i % 3 === 0) {
ret += `fizz`
}
if (i % 5 === 0) {
ret += `buzz`
}
console.log(ret || i)
}
}
fizzBuzz()
The most important part is console.log(ret || i) - empty string is falsy value, so console will log ret if there is some value or current i value
If you're trying to print to your browser's console, use console.log() instead of print(), since print() will open the printer preview in a browser. I'm using Chrome. Remember to check the console by pressing F12 and clicking on "console" in case you've created a html file that includes your javascript script.
Since you are iterating i until it reaches the value of n, you if statements should look like:
if(i%3===0){
// your code...
}
Based on your code, it seems like you want to check for a value that is not a multiple of 3 && a multiple of 5. However, the fizzbuzz challenge requires to print fizzbuzz when encountering a number that is both a multiple of 3 && a multiple of 5. So, you'll need to add the following condition:
if (i%3 === 0 && i%5 === 0) {
console.log("fizzbuzz");
continue; /* Continue may or may not be necessary depending on your program's logic. Continue allows to re-enter the loop
without checking for the remaining if statements. If you use continue, this condition must be the first if statement inside the loop */
}
Your function doesn't need to return anything, since you're using console.log() to visualize the values in each loop iteration. That's why you need to change return [i] for console.log(i).
Don't give up and keep trying!
If you have further questions, I'll be glad to help you.
I'm trying to do a function that'll print the numbers between 1-27 in my console.log.
When a number can be divided by 3, it should replace the number with "Fizz"
When a number can be divided by 5, replace it with "Buzz".
If the number can be divided by both 3 and 5, replace it with "Fizzbuzz"
Reference: http://en.wikipedia.org/wiki/Fizz_buzz)
This is my code:
var fizzbuzz = function(start,stop) {
for (var x=1;x <= stop; x++)
var string =',';
if (x%3 == 0) {
string += 'Fizz';
}
if (x%5 == 0){
string += 'Buzz';
}
if (x%5 && x%3){
string += 'Fizzbuzz';
}
return string;
};
Console.log is giving me "," and I'm not sure what I've done wrong.
Just to clarify.
I want my answer to print out 1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,Fizz Buzz,16,17,Fizz,19,Buzz,Fizz,22,23,Fizz,Buzz,26,Fizz and so on depending on 'stop' in the If-statement.
Valentins comment is correct, you do need to add brackets around your loop.
You are however also redefining the string var in every iteration of the loop.
The last if also makes the output a bit wrong as for example 15 would hit all 3 statements and print FizzBuzzFizzBuzz
so go with something like
var fizzbuzz = function(start,stop) {
var string = '';
var addComma = false;
for (var x=1;x <= stop; x++){
addComma = false;
if (x%3 == 0) {
string += 'Fizz';
addComma = true;
}
if (x%5 == 0){
string += 'Buzz';
addComma = true;
}
if(addComma && x!== stop){
string+=','
}
}
return string;
};
This is not the best way to keep track of where to add a comma, but it does the job.
for(let x = 0; x <=30; x++) {
if (x % 15 === 0) {
console.log('Fizzbuzz')
} else if (x % 5 === 0) {
console.log('Buzz')
} else if (x % 3 === 0) {
console.log('Fizz')
} else {
console.log(x)
}
}
this is how i dealt with it
You need to correct your for loop
You have
for (var x=1;x <= stop; x++)
var string =',';
being executed up until x <= stop.
Javascript allows you to avoid using brackets if you want to execute one line statements like so.
if (a===true)
alert(a); // This is executed when a === true
alert(b); // This is always executed no matter what a is
Indentation here was to make a point but the if statement would execute everything until the first semicolon.
On the other hand if you wanted to perform multiple lines of code if a === true you would choose to use curly braces like so
// Alert a and alert b are only executed if a is true
if (a===true) {
alert(a);
alert(b);
}
The if statement would execute everything in the curly braces.
Its important to note that return stops execution and exits the function. Once you reach a return statement the loop will be exited. That is why you should return the whole string after the for loop.
This is a better implementation but you should definitely try implementing it yourself
var fizzbuzz = function(start,stop) {
var string = '';
for (var x=1;x <= stop; x++) {
var status = x.toString(); //Each time the loop executes a new variable `status`is created and set to the value `x` for that loop.
// x is checked as to whether it is divisible by 3 or 5 or both, if it is divisible its status is set to a that value
if (x%3 === 0) {
status = 'Fizz';
}
if (x%5 === 0){
status = 'Buzz';
}
if (x%5 === 0 && x%3 === 0){
status = 'Fizzbuzz';
}
string += status; // Append status to the end
if (x !== stop){ // If x is not equal to the value of stop add a comma
string += ',';
}
}
return string; //This returns the string value which has had statuses and commas appended to it.
};
There are multiple problems with this:
(1) The construct
for (var x=1;x <= 10; x++)
statement;
otherstatement;
will execute statement 10 times before it executes other statement. Without braces, Javascript assumes that the next statement is the contents of the for loop;
(2) The string variable is redefined in every loop which gets rid of the preceding version, so the return statement only prints out the last value of string.
(3) The logic of the fizzBuzz if statements are wrong. If you follow this for a statement that divides by 15, it executes all three statements. The third iff statement is therefore completely redundant.
A solution would look like:
var fizzBuzz = function(x){
if(x%15==0){
return "Fizzbuzz";
}
if(x%3==0){
return "Fizz";
}
if(x%5==0){
return "Buzz";
}
return x;
};
var mainFunction = function(start,stop){
var str="";
for(var i=start; i < stop; i++){
str += fizzBuzz(i) + ", ";
}
return str;
};
Note that the third if statement for %15 is necessary only if this version demands that you print Fizzbuzz, rather than FizzBuzz.
Have the function DashInsert(num) insert dashes ('-') between each two odd numbers in num. For example: if num is 454793 the output should be 4547-9-3. Don't count zero as an odd number.
Here is my code (not working). When I run it, I get the same response as an infinite loop where I have to kill the page but I can't see why. I know there are ways to do this by keeping it as a string but now I'm wondering why my way isn't working. Thanks...
function DashInsert(num) {
num = num.split("");
for (i = 1; i < num.length; i++) {
if (num[i - 1] % 2 != 0 && num[i] % 2 != 0) {
num.splice(i, 0, "-");
}
}
num = num.join("");
return num;
}
Using num.splice you are inserting new entries into the array, therefor increasing its length – and that makes the value of i “running behind” the increasing length of the array, so the break condition is never met.
And apart from that, on the next iteration after inserting a -, num[i-1] will be that - character, and therefor you are practically trying to check if '-' % 2 != 0 … that makes little sense as well.
So, when you insert a - into the array, you have to increase i by one as well – that will a) account for the length of the array having increased by one, and also it will check the next digit after the - on the next iteration:
function DashInsert(num) {
num = num.split("");
for (i = 1; i < num.length; i++) {
if (num[i - 1] % 2 != 0 && num[i] % 2 != 0) {
num.splice(i, 0, "-");
i++; // <- this is the IMPORTANT part!
}
}
num = num.join("");
return num;
}
alert(DashInsert("454793"));
http://jsfiddle.net/37wA9/
Once you insert a dash -, the if statement is checking this '-'%2 != 0 which is always true and thus inserts another dash, ad infinitum.
Here's one way to do it with replace using a regex and function:
function DashInsert(n) {
var f = function(m,i,s) { return m&s[i+1]&1 ? m+'-' : m; };
return String(n).replace(/\d/g,f);
}
DashInsert(454793) // "4547-9-3"
When you are adding a dash, this dash will be processed as a number on the next iteration. You need to forward one step.
function DashInsert(num) {
var num = num.split("");
for (var i = 1; i < num.length; i++) {
if ((num[i - 1] % 2 != 0) && (num[i] % 2 != 0)) {
num.splice(i, 0, "-");
i++; // This is the only thing that needs changing
}
}
num = num.join("");
return num;
}
It's because there are cases when you use the % operator on dash '-' itself, e.g. right after you splice a dash into the array.
You can correct this behavior by using a clone array.
function DashInsert(num) {
num = num.split("");
var clone = num.slice(0);
var offset = 0;
for (i = 1; i < num.length; i++) {
if (num[i - 1] % 2 != 0 && num[i] % 2 != 0) {
clone.splice(i + offset, 0, "-");
offset++;
}
}
return clone.join("");
}
alert(DashInsert("45739"));
Output: 45-7-3-9
Demo: http://jsfiddle.net/262Bf/
To complement the great answers already given, I would like to share an alternative implementation, that doesn't modify arrays in-place:
function DashInsert(num) {
var characters = num.split("");
var numbers = characters.map(function(chr) {
return parseInt(chr, 10);
});
var withDashes = numbers.reduce(function(result, current) {
var lastNumber = result[result.length - 1];
if(lastNumber == null || current % 2 === 0 || lastNumber % 2 === 0) {
return result.concat(current);
} else {
return result.concat("-", current);
}
}, []);
return withDashes.join("");
}
It's longer, but IMHO reveals the intention better, and avoids the original issue.