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 == 0istrueit 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
num to 1while loop which will execute as long as num is not 0 (falsy, technically) and num % 7 is not 0.prompt into the variable numnum 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.num is zero, then pop-up corresponding alertCode 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');
};