Nested For Loop In TypeScript

Introduction

Nested For loop means "A For loop inside another For loop". The syntax is as follows:

For ( Initialization ; Condition ; Increment/Decrement )
{
  For ( Initialization ; Condition ; Increment/Decrement )
  {
    //write the code here
   }
}

When the condition of the first for loop is true, execution proceeds to the second loop and the second loop continues until the condition of the second loop becomes false then it will goes to the first loop again and the process continues. To see how it works let's use the following steps.

Step 1

Open Visual Studio 2012 and click on "File" -> "New" -> "Project...".

Step 2

A window is opened. In it select HTML Application for TypeScript under Visual C# and then give the name of your application that you want to give and then click ok.

Step 3

The TypeScript file contains the app.ts file (TypeScript file) , app.js file (Java script file ) and the default.htm file (HTML file). In this open the app.ts file.

Step 4

Write the following code in this app.ts file:

class triangle {

    x: number;

    constructor (x: number, ) {

        document.getElementById("one");

        for (var i = 1; i <= 10; i++) {

            for (var j = 0; j <= i; j++) {

                var y = x * i;

                var span = document.createElement("span");

                span.innerText = "*";

                document.body.appendChild(span);

            }

            span.innerText = "\n";

            document.body.appendChild(span);

        }

    }

}

var p = new triangle(1);

Step 5

Write the code in the app.js file as:
 

var triangle = (function () {

    function triangle(x) {

        document.getElementById("one");

        for (var i = 1; i <= 10; i++) {

            for (var j = 0; j <= i; j++) {

                var y = x * i;

                var span = document.createElement("span");

                span.innerText = "*";

                document.body.appendChild(span);

            }

            span.innerText = "\n";

            document.body.appendChild(span);

        }

    }

    return triangle;

})();

var p = new triangle(1);

Step 6

Write the following code in the default.htm file:
 

<!DOCTYPEhtml>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">

<head>

    <meta charset="utf-8" />

    <title>Example Of Print Triangle</title>

    <link rel="stylesheet" href="app.css" type="text/css" />

</head>

<body>

    <h1 id="one">Print Triangle</h1>

    <div style="color: #0094ff" id="content">

        <script src="app.js"></script>

    </div>

</body>

</html>

Step 7

Now run the application and the output will look like:

Nested-for-loop-in-typescript.jpg

Summary

In this article I explained how to use a nested for loop in TypeScript.

Up Next
    Ebook Download
    View all
    Test
    Read by 16 people
    Download Now!
    Learn
    View all