Learn JavaScript: Loops. Do...While Statements
This is an exersise from a Codecademy course, which I've made today
In some cases, you want a piece of code to run at least once and then loop based on a specific condition after its initial run. This is where the do...while statement comes in.
A do...while statement says to do a task once and then keep doing it until a specified condition is no longer met. The syntax for a do...while statement looks like this:
let countString = '';
let i = 0;
do {
countString = countString + i;
i++;
} while (i < 5);
console.log(countString);
In this example, the code block makes changes to the countString variable by appending the string form of the i variable to it. First, the code block after the do keyword is executed once. Then the condition is evaluated. If the condition evaluates to true, the block will execute again. The looping stops when the condition evaluates to false.
Note that the while and do...while loop are different! Unlike the while loop, do...while will run at least once whether or not the condition evaluates to true.
const firstMessage = 'I will print!';
const secondMessage = 'I will not print!';
// A do while with a stopping condition that evaluates to false
do {
console.log(firstMessage)
} while (true === false);
// A while loop with a stopping condition that evaluates to false
while (true === false){
console.log(secondMessage)
};
Instructions
1. We'd like a program to simulate part of the cake-baking process. Depending on the recipe, a different number of cups of sugar is required. Create the variable cupsOfSugarNeeded, and assign it a number value of your choosing. The cups of sugar must be added to the batter one at a time. Declare the variable cupsAdded and assign it the value 0.
const cupsOfSugarNeeded = 4;
const cupsAdded = 0;
2. We have a sweet tooth, so we want to add at least one cup of sugar to the batter even if the value of cupsOfSugarNeeded is 0. Create a do...while loop which increments cupsAdded by one while cupsAdded is less than cupsOfSugarNeeded.
let cupsOfSugarNeeded = 4;
let cupsAdded = 0;
do {
cupsAdded = (cupsAdded + 1);
} while (cupsAdded < cupsOfSugarNeeded);
Комментарии
Отправить комментарий