Create a program that asks the user for a number greater than 0, then prints out a countdown starting at that number and going down when it reaches 0: instead of printing 0, it prints "BLASTOFF!"

For example, if the user types in 5, the program will print:

5

4

3

2

1

BLASTOFF!

Do This

At the start of the loop, update the conditional statement for the while loop runs as long as the counter is greater than 0.
Inside the loop, add code that:
Prints the number in the countdown
Decreases the value stored in the variable counter by 1
After the loop, add code to print "Blastoff!" after the loop is done running.

// Create and assign variable based on user input
var counter = promptNum("Enter a number");

//TO DO #1: Update the conditional statement so that the loop runs
//as long as the counter is greater than 0
while(counter){
//TO DO #2: Add code to print the number in the countdown and
//then decrease the value of the counter by 1 each time
}

//TO DO #3: Add code to print "Blastoff!" after the loop is done running

1 answer

Here's a JavaScript program that fulfills your requirements. It prompts the user for a number greater than 0 and then countdowns to "BLASTOFF!".

// Function to get a valid number greater than 0 from the user
function promptNum(message) {
    let num;
    do {
        num = parseInt(prompt(message), 10);
    } while (isNaN(num) || num <= 0); // Keep prompting until a valid number is given
    return num;
}

// Create and assign variable based on user input
var counter = promptNum("Enter a number greater than 0:");

// Update the conditional statement so that the loop runs
while (counter > 0) {
    // Print the number in the countdown
    console.log(counter);
    // Decrease the value of the counter by 1 each time
    counter--;
}

// Print "BLASTOFF!" after the loop is done running
console.log("BLASTOFF!");

How the Code Works:

  1. The promptNum function ensures that the user inputs a valid number greater than 0. If the user enters an invalid input (either a non-number or a number less than or equal to 0), they will be prompted again until a valid number is entered.

  2. The variable counter is assigned the valid number from the user.

  3. The while loop checks if counter is greater than 0. Inside the loop:

    • The current value of counter is printed to the console.
    • The value of counter is then decreased by 1.
  4. Once the loop finishes, "BLASTOFF!" is printed to the console.

You can run this code in any JavaScript environment (like a web browser’s console) to see it in action!