JavaScript Program to Guess a Random number between 1 to 100.

JavaScript Program to Guess a Random number between 1 to 100.

 

in this article, we will create Number guessing game by using JavaScript program. in this game user randomly enter the number till he can guess the exact number

to create a guessing number game you have knowledge of HTML and JavaScript:

first you have to install the visual studio code and then create a folder to store the below two Files:

  • after creating the new folder then create a file name Index.html and copy the below code then save it

Html Code:

<!DOCTYPE html>
<html lang=”en”>
<head>
    <meta charset=”UTF-8″>
    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
    <title>Document</title>
</head>
<body>
    <script src =”script.js”></script>
</body>
</html>
  • Create a second file name script.js and copy the below code then save it:

JavaScript Code:

// Generate a random number between 1 and 100
const randomNumber = Math.floor(Math.random() * 100) + 1;

// Function to start the game
function startGame() {
let attempts = 0;
let guess;

while (guess !== randomNumber) {
guess = parseInt(prompt(“Guess a number between 1 and 100:”));

if (isNaN(guess)) {
alert(“Please enter a valid number.”);
} else {
attempts++;

if (guess < randomNumber) {
alert(“Too low! Try again.”);
} else if (guess > randomNumber) {
alert(“Too high! Try again.”);
} else {
alert(`Congratulations! You guessed the number ${randomNumber} in ${attempts} attempts.`);
}
}
}
}

// Start the game
startGame();

  • after saving the file click on Go live button in visual studio and now your game is start.

Visit more Blog’s:

History of C and C++ Languages and There Difference.

Website Development using WordPress