...

View Full Version : Continue Function error



larrywongm
05-08-2009, 06:30 AM
Hi ALL,

I am here whit some javascript error in my program. Yesterday I created a small program. I used Continue function and wanted print some number after 5 but when I executed program it displayed serial number 1 to 10.

Please check this code and let me show how can I print serial number after any number.

Here is my code.

<html>
<body>
<script type="text/javascript">
var i=0
do
{
if (i==5)
{continue}
document.write("Het getal is " + i)
document.write("<br />")
i++
}
while(i<=10);
</script>
</body>
</html>

Thanks,
Larry M. Wong
Acai (http://www.acai.fm/)

Old Pedant
05-08-2009, 07:00 AM
You only did the continue when i is *EXACTLY* 5.

But then, when i is exactly 5, you do *NOT* do the i++ statement, and so after that the do loop will LOOP FOREVER.

SHOW us the output you need.

Don't use words. Show us exactly.

****************

when I executed program it displayed serial number 1 to 10.
No, that code did *NOT* do that. That code showed the numbers 0 to 4 and then looped forever.

If you had code that displayed 1 to 10, it's not that code.

Philip M
05-08-2009, 07:55 AM
The problem is that you should have incremented the loop counter before the continue condition is tested, as otherwise you create an infinite loop.

Try this:-


<html>
<body>
<script type="text/javascript">
var i=-1; // as i is incremented at the outset
do
{
i++;
if (i==5) {continue}
document.write("Het getal is " + i);
document.write("<br />");
}
while(i<=9); // again, one lower than the final number as loop will increment one more time.
</script>
</body>
</html>

Result is numbers 0,1,2,3,4,6,7,8,9,10.
The continue statement is rarely used in practice.

A better way is to use a for loop rather than do...while:-


<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0; i<=10; i++) {
if (i==5) {continue } // i.e jump over that iteration
document.write("Het getal is " + i);
document.write("<br />");
}
</script>
</body>
</html>


All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum