Algorithm


  1. Generate a Random Number:

    • Generate a random number within a specified range. For example, you can use the Math.random() function to generate a decimal between 0 and 1 and then scale it to your desired range.
  2. Initialize Variables:

    • Initialize variables to keep track of the target random number, the user's guess, and the number of attempts.
  3. Get User Input:

    • Use the prompt() function to get input from the user. Prompt the user to guess the random number.
  4. Validate User Input:

    • Validate the user's input to ensure it's a valid number within the specified range.
  5. Compare Guess with Random Number:

    • Compare the user's guess with the generated random number.
  6. Provide Feedback:

    • Provide feedback to the user based on their guess. Let them know if their guess is too high, too low, or correct.
  7. Repeat or End:

    • If the guess is incorrect, repeat the process by going back to step 3. If the guess is correct, end the program.

 

Code Examples

#1 Code Example- Program to Guess a Number

Code - Javascript Programming

// program where the user has to guess a number generated by a program

function guessNumber() {

    // generating a random integer from 1 to 10
    const random = Math.floor(Math.random() * 10) + 1;

    // take input from the user
    let number = parseInt(prompt('Guess a number from 1 to 10: '));

    // take the input until the guess is correct
    while(number !== random) {
        number = parseInt(prompt('Guess a number from 1 to 10: '));
    }

    // check if the guess is correct
    if(number == random) {
        console.log('You guessed the correct number.');
    }

  }

// call the function
guessNumber();
Copy The Code & Try With Live Editor

Output

x
+
cmd
Guess a number from 1 to 10: 1
Guess a number from 1 to 10: 8
Guess a number from 1 to 10: 5
Guess a number from 1 to 10: 4
You guessed the correct number.
Advertisements

Demonstration


JavaScript Programing Example to Guess a Random Number-DevsEnv

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way