Algorithm
-
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.
- Generate a random number within a specified range. For example, you can use the
-
Initialize Variables:
- Initialize variables to keep track of the target random number, the user's guess, and the number of attempts.
-
Get User Input:
- Use the
prompt()
function to get input from the user. Prompt the user to guess the random number.
- Use the
-
Validate User Input:
- Validate the user's input to ensure it's a valid number within the specified range.
-
Compare Guess with Random Number:
- Compare the user's guess with the generated random number.
-
Provide Feedback:
- Provide feedback to the user based on their guess. Let them know if their guess is too high, too low, or correct.
-
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
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.
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.
Demonstration
JavaScript Programing Example to Guess a Random Number-DevsEnv