HappyHands31 HappyHands31 - 2 years ago 69
Javascript Question

"Even Steven" While Statement That Prints Out Odd Numbers, "Steven" In-Place of Even Numbers

For each number between 1 and 100...

If the number is odd, print it out.
But if the number is even, print the word "Steven" instead.

When we run the program, we should see the following output:




The program needs to start at 1 (not 0) and the number 100 must be included - the last number should be 100, not 99.

I'm still learning Javascript, so my first instinct is to create an While Statement:

var Number
var Counter = 1;

While (Number == even
Number <= 100) {
print ("Steven");
} else {
print (Number);

Should this even be a while loop though? How can I fix this statement so that it prints out odd numbers and "Steven" in-place of even numbers?

Edit: Tried to run in JSFiddle but nothing happened.

Answer Source

In JavaScript - Use a for loop and loop through 1 - 100. Check the remainder when dividing by two. If the remainder is 0, we know it's even, so console.log "Steven", otherwise the current number.

for (i = 1; i <= 100; i++){
  if (i % 2 == 0) console.log("Steven")
  else console.log(i)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download