Example

while Loops

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <link name="favicon" type="image/x-icon" href="https://skillzam.com/uploads/system/e353194f3b7cd1b75d69c3ab88041985.png" rel="shortcut icon" />
    <title>while Loops</title></head>
</head>
<body>
<!--
    while loop : It loops through a block of code as long as a specified condition is true.
    break : statement "jumps out" of a loop.
    continue : statement "jumps over" one iteration in the loop.
-->  

    <h1>Demo: JavaScript while loop </h1>

    <div>
        <h2>while loop : sum of all single digit numbers</h2>
        <p id="para1"></p>
    </div>

    <div>
        <h2>while loop with break keyword: <BR> A minimum of how many numbers, starting from 1, will be required to make their sum greater than 1000 ?</h2>
        <p id="para2"></p>
        <p id="para3"></p>
    </div>
    

    <!-- JavaScript code Starts here -->
    <script>

        /************************************************/
        // while loop 
        // Example : sum of all the single digit numbers
        //
        let counter = 0;
        let total = 0;
        while (counter < 10) {
            total += counter;
            counter++; 
        }
        document.getElementById('para1').innerHTML = 
        `The sum of all the single digit numbers  = ${total}`;


        /************************************************/
        // while Loop with break keyword
        // Example : A minimum of how many numbers, starting from 1, will be required to make their sum greater than 1000.
        //
        let sum = 0; 
        let highNum = 0;
        let i = 0;
        while (i < 100) {
            sum += i;
            highNum = i;
            if (sum >= 1000) break;
            i++;
        }
        document.getElementById('para2').innerHTML = 
        ` A minimum of ${highNum} numbers, starting from 1, will be required to make their sum greater than 1000.`;
        document.getElementById('para3').innerHTML = 
        `The sum of first ${highNum} numbers = ${sum}`;

    </script>
    <!-- JavaScript code Ends here -->

</body>
</html>

Output

View original