Introduction
Today I am going to explain how to use a while loop in TypeScript. I give an example of using the while loop to find the reverse of any number. For example if I enter the number 1234 then it will give the result as 4321. The syntax of the while loop is as:
Initialization;
While (Condition)
{
// Statements
Increment/Decrement
}
Now to use the while loop in TypeScript use the following.
Step 1
Open Visual Studio 2012 and click "File" -> "New" -> "Project...".
Step 2
A window is shown. In it select HTML Application for TypeScript under the Visual C# template and give the anme of your applicatiuon that you want to give then click ok.
Step 3
In this application there are three files; they are app.ts (TypeScript file), app.js (JavaScript file) and the defult.htm (HTML file). Open the app.ts file.
Step 4
Write the following TypeScript code in the app.ts file:
class Example_WhileLoop {
constructor () {
}
Reverse() {
var n: number;
var s = 0;
n = parseInt(prompt("Enter any Number"));
var temp = n;
while (temp != 0) {
s = s * 10;
s = s + temp % 10;
temp = Math.floor(temp / 10);
}
var span = document.createElement("span");
span.innerText = "Reverse Number is->" + s;
document.body.appendChild(span);
}
}
window.onload = () =>
{
var greeter = new Example_WhileLoop();
greeter.Reverse();
};
Step 5
Write the following code in the app.js file:
var Example_WhileLoop = (function () {
function Example_WhileLoop() {
}
Example_WhileLoop.prototype.Reverse = function () {
var n;
var s = 0;
n = parseInt(prompt("Enter any Number"));
var temp = n;
while (temp != 0) {
s = s * 10;
s = s + temp % 10;
temp = Math.floor(temp / 10);
}
var span = document.createElement("span");
span.innerText = "Reverse Number is->" + s;
document.body.appendChild(span);
};
return Example_WhileLoop;
})();
window.onload = function () {
var greeter = new Example_WhileLoop();
greeter.Reverse();
};
Step 6
Write the following code in the default.htm file:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>While Loop Example</title>
<link rel="stylesheet" href="app.css" type="text/css" />
<script src="app.js"></script>
</head>
<body>
<h1>While Loop Example</h1>
<div id="content"/>
</body>
</html>
Step 7
Now run the application and the output will be like:
When I click the ok button then the result is displayed as:
Summary
In this article I explained how to use a while loop in TypeScript.