Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialOwais Ul Haq
2,020 Pointsdo while loop
var randomNumber = getRandomNumber(10); var guess; var guessCount = 0; var correctGuess = false;
function getRandomNumber( upper ) { var num = Math.floor(Math.random() * upper) + 1; return num; }
do {
guess = prompt('I am thinking of a number between 1 and 10. What is it?');
guessCount += 1;
if (parseInt(guess) === randomNumber) {
correctGuess = true;
}
} while ( ! correctGuess )
document.write('<h1>You guessed the number!</h1>'); document.write('It took you ' + guessCount + ' tries to guess the number ' + randomNumber);
Please can some one explain me the do while part in the above program.
3 Answers
Martin Zarate
10,723 PointsWhile loops check if the statement is true before running the code, do while loops run the code once before checking the statement.
Nikica Maksimovski
Full Stack JavaScript Techdegree Student 14,080 PointsThe difference between do while and while is that the code in the {} when we use do while is executed at least once. You ask for a number input and check if the number inserted is equals to the random number.Then you repeat the same until you guess the number.
Owais Ul Haq
2,020 PointsMartin what is true or false in the above program why we used it, can you please explain me this ??
Martin Zarate
10,723 PointsThe statement is: while ( ! correctGuess ), so the do while loop executes once, gets to that statement, checks if that statement is true, meaning check the variable correctGuess, in this case, because it has the ! on front is checking if the variable is NOT equal to the correct answer, if it is, then break out of the loop, if it not, then execute the loop again. It sounds more complicated than it is, I suggest you play a little with the if-else statements and loops with a more simplified example, the simpler the better. Cheers.