while loop

 

While loop



                    In Javascript,there are three loop control statements i.e for,while and do..while.

                    Loop control statements are used for repeat the execution of code or block of statements until condition is true or till upto fixed number of times.

while loop-

                while loop is loop control statement.It executes the statements as long as condition is true.When condition becomes false control comes out of loop.

                While loop is also called as entry controlled or top tested loop,because here the condition is checked at the top or entry of the loop.

Syntax-

            initialization;

            while(condition)

            {

                loop statement/s;

                incr/decr;

            }

Example-

        var i;

        i=1;

        while(i<=10)

        {

            document.write(i+" ");

            i++; 

        }

Example-Write a Javascript program to display first 10 numbers.

<!DOCTYPE html>

<html>

<head>

<title>Javascript Program</title>

</head>

<body>

<h1>Use of While Loop</h1>

<script type="text/javascript"> 

document.write("First 10 Numbers are=");

var i;

i=1;

while(i<=10)

{

document.write(i+" ");

i++; 

}

</script>

</body></html>

Output-

Use of While Loop

First 10 Numbers are=1 2 3 4 5 6 7 8 9 10

Example-Write a Javascript program to display sum of first 10 numbers.

<!DOCTYPE html>

<html>

<head>

<title>Javascript Program</title>

</head>

<body>

<h1>Use of While Loop</h1>

<script type="text/javascript"> 

var i,sum;

i=1;

sum=0;

while(i<=10)

{

sum=sum+i;

i++; 

}

document.write("Sum of First 10 Numbers is="+sum);

</script>

</body></html>

Output-

Use of While Loop

Sum of First 10 Numbers is=55

Example-Write a Javascript program to print all numbers from 10 to 50.

<!DOCTYPE html>

<html>

<head>

<title>Javascript Program</title>

</head>

<body>

<h1>Use of While Loop</h1>

<script type="text/javascript"> 

document.write("Numbers From 10 to 50 are=");

var i;

i=10;

while(i<=50)

{

document.write(i+"  ");

i++; 

}

</script>

</body></html>

Output-

Use of While Loop

Numbers From 10 to 50 are=10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50


Example-Write a Javascript program to print all numbers from 10 to 1 i.e.10 9 8 7 6 5 4 3 2 1

<!DOCTYPE html>

<html>

<head>

<title>Javascript Program</title>

</head>

<body>

<h1>Use of While Loop</h1>

<script type="text/javascript"> 

document.write("Numbers are="); 

var i;

i=10;

while(i>=1)

{

document.write(i+"  ");

i--; 

}

</script>

</body></html>

Output-

Use of While Loop

Numbers are=10 9 8 7 6 5 4 3 2 1

Previous
Next Post »

Please Comment and Share. ConversionConversion EmoticonEmoticon