JavaScript – Exercise 11 – The Do-While Loop

In this example, you will learn about a different kind of JavaScript loop control structure. All other loops do not let the loop execute if the condition of the loop is false. However, the do-while loop make sure that the loop execute at least once before it fails.

Advertisements

Structure of do-while loop

int i = 10;

do {
    
       execute statements;
       
     } while (i < 10);

In the example above the loop executes at least once before the i = 11. For the sake of do-while example. We will do the following things.

  • Create an HTML page.
  • Write JavaScript code that will sum all the elements of a two dimensional array.
  • Output the result in browser console.

HTML Example: do-while.html

Open any text editor and write the following code and save it as do-while.html.

Advertisements
<!DOCTYPE html>
<html>
<head>
    <title>JavaScript - Do-While Loop </title>
</head>
<body>


</body>
</html.

At this moment do not add anything in the body section. Leave it empty. Save the document as do-while.html .

Add JavaScript Code

In this section, you will add your JavaScript code to the HTML file created previously. Add the following code in the body section of the HTML document.

  function myArrTotal(arr) {      

       var sum = 0;       
       var i = 0;       
       
             do {                
                          for(var j=0;j < arr[i].length;j++)                 
                            {                         
                                       sum = sum + arr[i][j];                 
                               }                  
                           i++;                        
                   }while(i < arr.length); 
                  return sum;
                } 
console.log("Sum =" + myArrTotal([[2],[4],[5]]));

Output : do-while loop

Output – Do-While Loop

Advertisements

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.