Home > Enterprise >  How to use a loop to loop to the amount of times as a variable
How to use a loop to loop to the amount of times as a variable

Time:12-09

This is my assignment from class, but my professor won't respond to my emails and i'm having trouble.

Write a script that asks for a user's name and age, then prints the user's name and age on the screen over and over until it loops as many times as the user's age. Security Feature: Do not let users named "Raymond" run this program.

Here is my code:

let name = prompt("What is your name?");
let age = prompt("What is your age?");

for (age = 0; age <= 19; age  ) {
  document.write("Your name is "   name   " and your age is "   age   "</br>");
}

CodePudding user response:

The main problem with your attempt is here in the for loop.

for (age = 0; age <= 19; age  )

That will overwrite the age that the user entered, and always loop until it reaches 19. You want to create a new loop variable, then loop until the age the user entered.

let name = prompt("What is your name?");
let age = prompt("What is your age?");

for (i = 1; i <= age; i  ) {
  document.write("Your name is "   name   " and your age is "   age   "</br>");
}

The other issue is that you don't do anything about users named "Raymond" using your program. You can do that with an if..else statement around the loop.

let name = prompt("What is your name?");
let age = prompt("What is your age?");

if (name === "Raymond") {
    document.write("Get out of here, Raymond! You know what you did!");
}
else {
  for (i = 1; i <= age; i  ) {
      document.write("Your name is "   name   " and your age is "   age   "</br>");
  }
}

CodePudding user response:

Mark as answer if helpful

let name = prompt("What is your name?");
    let age = prompt("What is your age?");

    

    for (i = 0; i <= age; i  ) {  
        document.write("Your name is "   name   " and your age is "   age   "</br>");
    }
  • Related