i got the next exercise in Javascript:
Receive whole numbers from the user, until he enters a number that % 7 with no remainder.
For each number received, state whether it is positive, negative or 0.
when inserting a number % by 7 with no remainder, end the program.
here is my code:
let num = +prompt("give us a number")
while (num % 7 != 0) {
if (num > 0){
document.write("positive ")
num = +prompt("give us a number" )
} else if (num < 0) {
document.write("negative ")
num = +prompt("give us a number" )
} else if (num === 0) {
document.write("zero ")
num = +prompt("give us a number" )
}
The thing is, when the user enter 0 ,obviously i wont get output "zero", cause 0 % 7 is 0 remainder, so it dosent even get into the loop..so how can i output "zero" when the user enter 0?
let num = +prompt("give us a number")
while (num % 7 != 0) {
if (num > 0){
document.write("positive ")
if(num % 7 == 0) {
break;
} else {
num = +prompt("give us a number")
}
} else if (num < 0) {
document.write("negative ")
if(num % 7 == 0) {
break;
} else {
num = +prompt("give us a number")
}
} else if (num === 0) {
document.write("zero ")
if(num % 7 == 0) {
break;
} else {
num = +prompt("give us a number")
}
}
}
Either bring out the else if (num == 0) part before while loop
since 0 % 7 == 0 is true it should satisfy the excersise even if it's not in the loop.
if (num == 0) {
// do stuff
}
while (/* condition */) {
// do other stuff
}
Or add num == 0 constraint in while condition.
while (num == 0 || num % 7 != 0) {
// do stuff
}
The former will not get into the loop, the latter will cause the loop to exit on num == 0 because both implies that it's a correct modulo division.
You can do both if you want to optimize memory usage (obviously it wouldn't be a problem in this scale).
This may be one possible way to achieve the desired objective.
Code Sample
This sample uses alert to pop-up the result, instead of document.write.
let num = 1;
while (!num || num % 7) {
num = +prompt('enter a number');
if (num && num % 7) {
alert(
`${num} is ${num > 0
? 'positive'
: 'negative'
}`
);
} else if (!num) alert('num is zero');
};
Explanation
Set an initial value of num to 1
Set a while loop which will execute as long as num is not 0 (falsy, technically) and num % 7 is not 0.
Get the user-input using prompt into the variable num
If num is truthy (ie, non-zero) and num % 7 is truthy (ie, non-zero), pop an alert whether num is positive (if > 0) or negative (otherwise). This is achieved by using ` backtick symbol / template literal and ?: ternary-operator.
Else, if num is zero, then pop-up corresponding alert
Code Snippet
let num = 1;
while (!num || num % 7) {
num = +prompt('enter a number');
if (num && num % 7) {
alert(
`${num} is ${num > 0
? 'positive'
: 'negative'
}`
);
} else if (!num) alert('num is zero');
};
it turned out, this this the simplest answer:
let num = +prompt("give us a number")
while (**num == 0| num % 7 != 0**) {
if (num > 0){
document.write("positive ")
num = +prompt("give us a number" )
} else if (num < 0) {
document.write("negative ")
num = +prompt("give us a number" )
} else if (num === 0) {
document.write("zero ")
num = +prompt("give us a number" )
}
}
Related
new to JS. In the following code, the isNaN isn't working. If you enter a number in the prompt, the FizzBuzz rules work fine. However, if you enter a random string, I expect the isNaN condition to be met. What am I doing wrong?
let number = parseInt(prompt("Enter a number"));
for(let i = 1; i < number; i++) {
if(isNaN(number)) {
console.log("Is not a number")
} else 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)
}
}
When parseInt can't parse the string to an integer if will return NaN. In your for loop you use number in the condition i < number. If NaN is compared to a number using a comparison operator such as < or > the result will always be false and the loop will not run at all, this is why nothing happens when you enter a random string.
To get the result you are expecting You could put the isNaN check outside the for loop and only run the loop if number is not equal to NaN.
let number = parseInt(prompt("Enter a number"));
if (isNaN(number)) {
console.log("Is not a number")
} else {
for(let i = 1; i < number; 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)
}
}
}
As #RobinZigmond correctly pointed out, when you enter an arbitrary string, number will be NaN.
For loop basically consists of:
for (Initialization, Condition, Increment)
Your condition: let i = 1 is run one time, then your condition: i < number is checked, in this case 1 < NaN which is clearly false, as the condition here is not met, you never enter your for loop.
One way to do what you're trying to do is:
let number;
while (!isNaN(number)) {
number = parseInt(prompt("Enter a number"));
}
for(let i = 1; i < number; 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)
}
}
let userInput = prompt("Enter a number");
if(isNaN(userInput)) {
console.log("Is not a number")
} else {
let number = parseInt(userInput);
for(let i = 1; i < number; 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 works as expected (putting the isNaN check outside of the loop.
Move your first if statement out of the loop. It never gets read, because the expression parseInt(string) < number will always return false.
let number = parseInt(prompt("Enter a number"));
if (isNaN(number)) {
console.log("Is not a number")
}
for (let i = 1; i < number; 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)
}
}
I'm busy with a udacity excercise and the following question:
A while loop that:
Loop through the numbers 1 to 20
If the number is divisible by 3, print "Julia"
If the number is divisible by 5, print "James"
If the number is divisible by 3 and 5, print "JuliaJames"
If the number is not divisible by 3 or 5, print the number
I keep submitting the answer but it tells me that my while loop condition is incorrect, Is there anything im doing wrong?
var x = 1;
while (x <= 20) {
if (x/3 === 0) {
console.log("julia" );
} // check divisibility
else if (x/5 === 0) {
console.log("james");
}
else if (x/5 === 0 && x/3 === 0 ) {
console.log("juiliajames");
} // print Julia, James, or JuliaJames
else {
console.log(x);
}
x= x + 1;// increment x
}
You need to use Modulus (%) instead of divide (/). And make x % 5 === 0 && x % 3 === 0 as your first condition.
Change your code like following.
var x = 1;
while (x <= 20) {
if (x % 5 === 0 && x % 3 === 0) {
console.log("juiliajames");
} // print Julia, James, or JuliaJames
else if (x % 3 === 0) {
console.log("julia");
} // check divisibility
else if (x % 5 === 0) {
console.log("james");
} else {
console.log(x);
}
x = x + 1; // increment x
}
var x = 1;
while (x <= 20) {
if(x%3 === 0 && x%5 === 0 ){
console.log("juiliajames" );
} // check divisibility
else if(x%3 === 0){
console.log("juilia");
}
else if (x%5 === 0){
console.log("james");
} // print Julia, James, or JuliaJames
else{
console.log(x);
}
x= x + 1;// increment x
}
If you want to check divisibility, you should use the % operator instead of / operator.
Check x divisible by 5 AND 3 at the begining or it will never been done because if it is divisible by 3 your loop won't go to the else if statment.
To check divisibility use modulo (x/3 === 0 only for x = 0)
var x = 1;
while (x <= 20) {
if(x%5 === 0 && x%3 === 0){
console.log("juiliajames" );
}
else if(x%5 === 0){
console.log("james");
}
else if (x%3 === 0 ){
console.log("juilia");
}
else{
console.log(x);
}
x= x + 1;// increment x
}
My approach works by setting bitwise flags on an integer. If it's divisible by three (value % 3 === 0, where % is 'modulo' which gives an integer remainder from division) The first bit is set and if it's divisible by five the second bit is set. That gives a result that could have three binary values 01, 10 or 11, or in decimal 1, 2 & 3 (The three comes about when both bits are set).
var DIVISABLE_BY_THREE = 1;
var DIVISABLE_BY_FIVE = 2;
var DIVISABLE_BY_THREE_AND_FIVE = 3;
var value = 0;
while(value++ < 20) {
var modulo_3 = (value % 3 === 0) | 0;
var modulo_5 = ((value % 5 === 0) | 0) << 1;
switch(modulo_3 | modulo_5) {
case DIVISABLE_BY_THREE:
console.log("Julia");
break;
case DIVISABLE_BY_FIVE:
console.log("James");
break;
case DIVISABLE_BY_THREE_AND_FIVE:
console.log("JuliaJames");
break;
default:
console.log(value);
break;
}
}
var x = 1;
while (x <= 20) {
var name ="";
if (x % 3 == 0) {
name = name + "julia";
}
if (x % 5 == 0) {
name = name + "james";
}
if(name.length > 0)
console.log(name);
else
console.log(x);
x++;
}
I'm trying to solve the famous FizzBuzz quiz but I decided to use the logical operator or instead of else to provide fullback.
for (var num = 1; num <= 100; num++) {
var output;
if (num % 5 === 0 && num % 3 === 0) {
output = "FizzBuzz";
} else if (num % 5 === 0) {
output = "Buzz";
} else if (num % 3 === 0) {
output = "Fizz";
}
console.log(output || num);
}
This was supposed to print all the numbers from 1 to 100, with some exceptions. For numbers divisible by 3, print "Fizz" instead of the number, and for numbers divisible by 5, print "Buzz" instead and "FizzBuzz", for numbers that are divisible by both 3 and 5.
But it doesn't print any numbers.
The output declaration could be num like :
var output = num;
So you don"t have to use the || operator and just print the output directly :
console.log(output);
for (var num = 1; num <= 100; num++) {
var output = num;
if (num % 5 === 0 && num % 3 === 0) {
output = "FizzBuzz";
} else if (num % 5 === 0) {
output = "Buzz";
} else if (num % 3 === 0) {
output = "Fizz";
}
console.log(output);
}
I will say that Zakaria's answer is correct, but for exposure's sake, here is my answer
for (var i = 1; i <= 100; i++) {
var output = "";
if (!(i % 3)) output += "Fizz";
if (!(i % 5)) output += "Buzz";
console.log(output || i);
}
My logic here:
set the output value to be equal to "", which evaluates to a falsey value.
If a number is divisible by 3, then i % 3 will be 0, this is also a falsey value so we flip it by using the ! operator. Assume that i=9, then ! (i%3) = !(9%3) = !(0) = !(false) = true.
Therefore, if !(i%3) becomes true we append our empty string with "Fizz", then we use the same sort of logic for i%5, but instead appending "Buzz"
Note the order of these two if statements is important -- flip them around and you'll get BuzzFizz instead of FizzBuzz.
If output is not the empty string we set it to originally, output || i will return the value of output, giving us "Fizz", "Buzz", or "FizzBuzz" depending.
If ouput is empty, then output || i will return the value for i
Use let to fix the output's scope:
for (var num = 1; num <= 100; num++) {
let output;
if (num % 5 === 0 && num % 3 === 0) {
output = "FizzBuzz";
} else if (num % 5 === 0) {
output = "Buzz";
} else if (num % 3 === 0) {
output = "Fizz";
}
console.log(output || num);
}
Also, the || could be removed if you initialize output with num:
for (var num = 1; num <= 100; num++) {
let output = num;
if (num % 5 === 0 && num % 3 === 0) {
output = "FizzBuzz";
} else if (num % 5 === 0) {
output = "Buzz";
} else if (num % 3 === 0) {
output = "Fizz";
}
console.log(output);
}
please I'm stuck in this question below since yesterday. Below is the question:
Write a program that uses console.log to print all the numbers from 1
to 100, with two exceptions. For numbers divisible by 3, print "Fizz"
instead of the number, and for numbers divisible by 5 (and not 3), print
"Buzz" instead.
When you have that working, modify your program to print "FizzBuzz",
for numbers that are divisible by both 3 and 5 (and still print "Fizz" or
"Buzz" for numbers divisible by only one of those).
I only got the first two conditions but not the the third. I don't know how to go about it anymore, I've tried many options. Below is my code:
<html>
<head/head>
<body>
<script type="text/javascript">
for (i = 1; i <= 100; i++)
if (i % 3 == 0) {
document.write("Fizz");
document.write("<br />");
} else if (i % 5 == 0 && i % 3 != 0) {
document.write("Buzz");
document.write("<br />");
} else if (i % 3 && 5 == 0 && i % 3 != 0 && i % 5 != 0) {
document.write("FizzBuzz");
document.write("<br />");
} else {
document.write(+i);
document.write("<br />");
}
</script>
</body>
</html>
Check the most specific (FizzBuzz) condition first.
function fizzBuzz() {
for(var i = 1; i <= 100; i++){
if(i % 5 === 0 && i % 3 === 0){
console.log('FizzBuzz');
} else if(i % 3 === 0){
console.log('Fizz');
} else if(i % 5 === 0){
console.log('Buzz');
} else {
console.log(i);
}
}
}
here is an updated version of your code, I keep it as you write it with some changes, I made it work without touch it's logic, you can see that the problem was in the first comparison and in the second "if else" (5 will never be equal to 0). you can optimize the code more than that, good luck.
<html>
<head/head>
<body>
<script type="text/javascript">
for (i = 1; i <= 100; i++)
if (i % 3 == 0 && i % 5 != 0) {
document.write("Fizz");
document.write("<br />");
} else if (i % 5 == 0 && i % 3 != 0) {
document.write("Buzz");
document.write("<br />");
} else if (i % 3 == 0 && i % 5 == 0) {
document.write("FizzBuzz");
document.write("<br />");
} else {
document.write(+i);
document.write("<br />");
}
</script>
</body>
</html>
Since everyone is contributing, I might as well give you an interesting solution:
var i = 101;
while(i --> 0){ // as i goes to 0... wat
var state = !!(i % 3) << 1 | !!(i % 5), // compute state?
output = ["FizzBuzz", "Fizz", "Buzz", i]; // hmm...
console.log(output[state]); // output correct string
}
1st - Instead of document.write use console.log like the question says
2nd - You have a syntax error in the head section. it should be <head></head>
3rd - for the 1st part of the question all you need is this:
for (i = 1; i <= 100; i++) {
// if i is divisible by 3
if (i % 3 == 0) {
console.log("Fizz");
}
// if i is divisible by 5 (no need to check for 3 again)
else if (i % 5 == 0) {
console.log("Buzz");
}
// else
else {
console.log(i);
}
}
4th - For the 2nd part you need to add an extra if on top of what you have already:
for (i = 1; i <= 100; i++) {
// if i is divisible by 3 and 5
if (i % 3 == 0 && i % 5 == 0) {
console.log("FizzBuzz");
}
// if i is divisible by 3
else if (i % 3 == 0) {
console.log("Fizz");
}
// if i is divisible by 5 (no need to check for 3 again)
else if (i % 5 == 0) {
console.log("Buzz");
}
// else
else {
console.log(i);
}
}
working fiddle: https://jsfiddle.net/tedmanowar/amapqcLL/
You can use a while loop, than use a nested if statements to check the conditions.
let number = 0;
while (number <= 100) {
if(number % 3 === 0 && number % 5 === 0){
console.log("FizzBuzz");
}else if(number % 3 === 0){
console.log("Fizz");
}else if(number % 5 === 0){
console.log("Buzz");
}else{
console.log(number);
}
number++;
}
This solution is the easiest and simplest. There are multiple ways to solve the question though.
for (n=1; n<=100; n++){
let output = "";
if(n % 3=== 0) output += "Fizz"
if(n % 5=== 0) output += "buzz"
console.log(output || n);
}
I don't recommend this answer - since it is very hard to maintain - but it does do it in very few lines. It also relies on the two numbers only having a common factor of 1.
for(let i=1; i<=100; i++) {
console.log(`${i%15?i%5?i%3?i:'Fizz':'Buzz':'FizzBuzz'}`)
}
This is using the ternary operator and backquote template strings.
You should just use a loop that starts at 1 and is less than 101 (so up to 100) and test for the %n === 0. In other words, make sure there is no remainder.
function startConsoleDemo(){
for(var i=1,r; i<101; i++){ // loop from 1 to 100
r = i; // default value of r
if(i % 3 === 0 && i % 5 === 0){ // if i/3 and 1/5 do not produce a remainder
r = 'FizzBuzz'; // reassign r
}
else if(i % 3 === 0){ // we knew i % 5 !== 0 so see if i/3 does not produce a remainder
r = 'Fizz'; // reassign r
}
else if(i % 5 === 0){ // we already knew i % 3 !== 0 - you know the drill
r = 'Buzz'; // reassign r
}
console.log(r); // console at each step of the loop no matter what
}
}
startConsoleDemo(); // without () you can use like a var then () later
I have a solution and I'm pretty sure it'll work for you.
for (let i = 1; i <= 100; i++) {
if (i % 3 === 0 && i % 5 === 0) {
document.write(`${i} FizzBuzz`);
} else if (i % 3 === 0 && i % 5 !== 0) {
document.write(`${i} Fizz`);
} else if (i % 5 === 0 && i % 3 !== 0) {
document.write(`${i} Buzz`);
} else {
document.write(`${i}`);
}
}
Write a javascript program that displays the numbers from 10 to 100. But for multiples of 4 print "Penny" instead of the number and for multiples of 6 print "Leonard". For numbers which are multiples of both 4 and 6 print "Bazzinga"
I know how to do two parts struggling to print 6 and 4;
function baZzinga (number) {
for (var number = 10; number <= 101; number++)
if(number % 4 == 0) {
console.log("penny");
}
else if (number % 6 == 0) {
console.log("Leonard");
} else if ( not sure what goes here) {
help help help
} else {
console.log(number");
}
You want the and condition first. Try this
var result = document.getElementById("result");
function baZzinga (number) {
for (var number = 10; number <= 101; number++) {
if (number % 4 == 0 && number % 6 == 0) {
result.innerHTML += "Bazinga";
}
else if(number % 4 == 0) {
result.innerHTML += "penny";
}
else if (number % 6 == 0) {
result.innerHTML += "Leonard";
}
else {
result.innerHTML += number;
}
}
}
baZzinga()
<p id="result"></p>
I changed console.log to result.innerHTML because I wanted to demonstrate it in a snippet.
I have a few comments on your code -- constructive criticism, I hope! First, you don't need the number parameter in your bazzinga function. Next, the indentation of the code you posted makes it hard to read. Finally, you should almost always use === instead of ==. The === tests for strict equality, whereas == tries to do some type conversions first (and can therefore produce unexpected results). See the official docs.
To answer you question: check for divisibility by 6 AND 8 first. That way, it will override the individual cases. I believe you want something like this:
function bazzinga() {
for (var number = 10; number <= 100; number++) {
if (number % 4 === 0 && number % 6 === 0) {
console.log("Bazzinga");
} else if (number % 4 === 0) {
console.log("Penny");
} else if (number % 6 === 0) {
console.log("Leonard");
}
}
}
Here is a solution using the format you posted:
for (var number = 10; number <= 100; number++) {
if(number % 4 === 0 && number % 6 === 0){
console.log("bazzinga");
} else if(number % 4 === 0) {
console.log("penny");
} else if (number % 6 === 0) {
console.log("Leonard");
} else {
console.log(number);
}
}
Or use the ternary operator to be even more succinct!
for (var i = 10; i <= 100; i++){
var penny = i % 4 === 0;
var leonard = i % 6 === 0;
console.log(penny ? (leonard ? "bazzinga" : "penny"): leonard ? "leonard" : i);
}
function process_num(num) {
return num % 4 == 0 ? num % 6 == 0 ? "Bazzinga" : "Penny" : num % 6 == 0 ? "Leonard" : num;
}
for (x = 10; x <= 100; x++) { console.log( x + ': is ', process_num(x)) }
Nested Ternary operator for conciseness
If it passes outer ternary test it is divisible by 4:
Enter into nested termary one to test if num is also divisible by 6 for the BaZzinga prize!!
If it fails the BaZzinga challenge, we know it previously passed the divisible by 4 test so print "penny"
Failing the outer ternary condition, we know it's not divisible by 4:
Enter nested ternary two to consider if divisible by 6. If so print "Leonard".
If not it's failed both the outer (div by 4) and inner (div by 6) so return the number unchanged.
Now that the logic is contained in the function, we can just create a for loop to iterate over the required numbers printing out the correct values.