Friday, 31 May 2024

Java Script: The While Loop and A for loop

 A for loop allows you to carry out a particular operation a fixed number of times.

The for loop is controlled by setting three values:

  - an initial value

  - a final value

  - an increment

The format of a for loop looks like this:

  for (initial_value; final_value; increment)

  {

  statement(s);

  }

Here,


  1. The initial_value initializes and/or declares variables and executes only once.

  2. The condition is evaluated.

    1. If the condition is false, the for loop is terminated.

    2. if the condition is true, the block of code inside of the for loop is executed.

  3. The increment updates the value of initial_value when the condition is true.

  4. The condition is evaluated again. This process continues until the condition is false.

To learn more about the conditions, visit JavaScript Comparison and Logical Operators.

EXAMPLE:

// program to display text 10 times

const n = 5;


// looping from i = 1 to 5

for (let i = 1; i <= n; i++) {

    console.log(`I love JavaScript.`);

}


OutPut

I love JavaScript.

I love JavaScript.

I love JavaScript.

I love JavaScript.

I love JavaScript.


The While Loop

Like the for loop, the while loop allows you to carry out a particular operation a number of times.


The format of a while loop is as follows:

  while (condition)

  {

  statement(s);

  }

Here,

  1. A while loop evaluates the condition inside the parenthesis ().

  2. If the condition evaluates to true, the code inside the while loop is executed.

  3. The condition is evaluated again.

  4. This process continues until the condition is false.

  5. When the condition evaluates to false, the loop stops.

Flowchart of while Loop


 A practical while loop might look like this:

EXAMPLE:

var x = 500000;

     alert("Starting countdown...");

     while (x > 0)

    {

        x--;

    };

    alert("Finished!");


In this example, x is initially set to a high value (500,000). It is then reduced by one each time through the loop using the decrement operator (x--). So long as x is greater than zero the loop will continue to operate, but as soon as x reaches zero the loop condition (x > 0) will cease to be true and the loop will end.

The effect of this piece of code is to create a delay which will last for as long as it takes the computer to count down from 500,000 to 0. Before the loop begins, an 'alert' dialog-box is displayed with the message "Starting Countdown...". When the user clicks the 'OK' button on the dialog-box the loop will begin, and as soon as it finishes another dialog-box will be displayed saying "Finished!". The period between the first dialog box disappearing and the second one appearing is the time it takes the computer to count down from 500,000 to 0.


No comments:

Post a Comment

Interactive Report: Introduction to the Internet of Things (IoT) ...

Popular Posts