LOOPS
While loop:
The Power of While Loops in Programming
Imagine you're playing a game where you need to
keep rolling a dice until you get a six. You wouldn't
know in advance how many rolls it would take, but
you'd keep rolling until you reach your goal. This is
similar to how a while loop works in programming.
A while loop is a control structure that allows you to
execute a block of code repeatedly as long as a
certain condition is true. The loop will continue to run
until the condition is met, at which point the loop will
exit.
The Basic Syntax
The basic syntax of a while loop is as follows:
while (condition) {
// code to be executed
}
The condition is a boolean expression that is
evaluated at the beginning of each iteration. If the
condition is true, the code inside the loop will be
executed. If the condition is false, the loop will exit.
Step-by-Step Calculation
, Let's consider an example where we want to print the
numbers from 1 to 5 using a while loop.
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
Here's how the loop would work:
• i is initialized to 1.
• The condition i <= 5 is evaluated, which is
true.
• The code inside the loop is executed,
printing 1 to the console.
• i is incremented by 1, so i becomes 2.
• Steps 2-4 are repeated until i is greater than
5.
Code Samples
Here are a few more examples of using while loops:
• Printing the numbers from 10 to 1:
let i = 10;
while (i >= 1) {
console.log(i);
i--;
}
While loop:
The Power of While Loops in Programming
Imagine you're playing a game where you need to
keep rolling a dice until you get a six. You wouldn't
know in advance how many rolls it would take, but
you'd keep rolling until you reach your goal. This is
similar to how a while loop works in programming.
A while loop is a control structure that allows you to
execute a block of code repeatedly as long as a
certain condition is true. The loop will continue to run
until the condition is met, at which point the loop will
exit.
The Basic Syntax
The basic syntax of a while loop is as follows:
while (condition) {
// code to be executed
}
The condition is a boolean expression that is
evaluated at the beginning of each iteration. If the
condition is true, the code inside the loop will be
executed. If the condition is false, the loop will exit.
Step-by-Step Calculation
, Let's consider an example where we want to print the
numbers from 1 to 5 using a while loop.
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
Here's how the loop would work:
• i is initialized to 1.
• The condition i <= 5 is evaluated, which is
true.
• The code inside the loop is executed,
printing 1 to the console.
• i is incremented by 1, so i becomes 2.
• Steps 2-4 are repeated until i is greater than
5.
Code Samples
Here are a few more examples of using while loops:
• Printing the numbers from 10 to 1:
let i = 10;
while (i >= 1) {
console.log(i);
i--;
}