ASP: Looping Statements

ASP performs several types of repetitive operations, called “looping”. Loops are set of instructions used to repeat the same block of code till a specified condition returns false or true depending on how you need it. To control the loops you can use counter variable that increments or decrements with each repetition of the loop.

The two major groups of loops are For..Next and Do..Loop. The For…Next statements are best used when you want to perform a loop a specific number of times. The Do…Loop statements are best used to perform a loop an undetermined number of times. In addition, you can use the Exit keyword within loop statements.

The For … Next Loop

For…Next loops are used when you want to execute a piece of code a set number of times. The syntax is as follows: 

For counter = initial_value to  finite_value [Step increment]
  statements
Next

The For statement specifies the counter variable and its initial and finite values. The Next statement increases the counter variable by one. Optional the Step keyword allows to increase or decrease the counter variable by the value you specify.

Have a look at the very simple example:

 
<%@ language="vbscript" %>
<%
For i = 0 to 10 Step 2 'use i as a counter
 response.write("The number is " & i & "<br />")
Next
%>

The preceding example prints out even numbers from 0 to 10, the <br> tag puts a line break in between each value.

Next example generates a multiplication table 2 through 9. Outer loop is responsible for generating a list of dividends, and inner loop will be responsible for generating lists of dividers for each individual number:

 
<%@ language="vbscript" %>
<%
response.write("<h1>Multiplication table</h1>")
response.write("<table border=2 width=50%")

For i = 1 to 9             'this is the outer loop
   response.write("<tr>")
   response.write("<td>" & i & "</td>")
 
   For j = 2 to 9          'inner loop
        response.write("<td>" & i * j & "</td>")
   Next 'repeat the code and move on to the next value of j   

   response.write("</tr>")
Next 'repeat the code and move on to the next value of i

response.write("</table>")
%>

Back to top

The For Each … Next Loop

The For Each…Next loop is similar to a For…Next loop. Instead of repeating the statements a specified number of times, the For Each…Next loop repeats the statements for each element of an array (or each item in a collection of objects).

The following code snippet creates drop-down list where options are elements of an array:

 
<%
Dim bookTypes(7) 'creates first array
bookTypes(0)="Classic"
bookTypes(1)="Information Books"
bookTypes(2)="Fantasy"
bookTypes(3)="Mystery"
bookTypes(4)="Poetry"
bookTypes(5)="Humor"
bookTypes(6)="Biography"
bookTypes(7)="Fiction" 
 
Dim arrCars(4) 'creates second array
arrCars(0)="BMW"
arrCars(1)="Mercedes"
arrCars(2)="Audi"
arrCars(3)="Bentley"
arrCars(4)="Mini"

Sub createList(some_array) 'takes an array and creates drop-down list
  dim i
  response.write("<select name=""mylist"">" & vbCrLf) 'vbCrLf stands for Carriage Return and Line Feed
  For Each item in some_array
     response.write("<option value=" & i & ">" & item & "</option>" & vbCrLf)
     i = i + 1
  Next 'repeat the code and move on to the next value of i
  response.write("</select>")
End Sub

'Now let's call the sub and print out our lists on the screen
Call createList(bookTypes) 'takes bookTypes array as an argument
Call createList(arrcars) 'takes arrCars array as an argument
%>

Back to top

The Do … Loop

The Do…Loop is another commonly used loop after the For…Next loop. The Do…Loop statement repeats a block of statements an indefinite number of times. The statements are repeated either while a condition is True or until a condition becomes True. The syntax looks as follows:

Do [While|Until] condition 
  statements
Loop

Here is another syntax:

Do  
  statements
Loop [While|Until] condition

In this case  the code inside this loop will be executed at least one time. Have a look at the examples:

The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 10. i will increase by 1 each time the loop runs.

 
<%
Dim i 'use i as a counter
i = 0 'assign a value to i

Do While i<=10 'Output the values from 0 to 10
  response.write(i & "<br \>")
  i = i + 1 'increment the value of i for next time loop executes
Loop
%>

Now let’s consider a more useful example which creates drop-down lists of days, months and years. You can use this code for registration form, for example.

 
<%
'creates an array
Dim month_array(11)
month_array(0) = "January"
month_array(1) = "February"
month_array(2) = "March"
month_array(3) = "April"
month_array(4) = "May"
month_array(5) = "June"
month_array(6) = "July"
month_array(7) = "August"
month_array(8) = "September"
month_array(9) = "October"
month_array(10) = "November"
month_array(11) = "December"

Dim i 'use i as a counter

response.write("<select name=""day"">" & vbCrLf)
i = 1
Do While i <= 31  
   response.write("<option value=" & i & ">" & i & "</option>" & vbCrLf)
   i = i + 1
Loop
response.write("</select>")

response.write("<select name=""month"">" & vbCrLf)
i = 0
Do While i <= 11 
   response.write("<option value=" & i & ">" & month_array(i) & "</option>" & vbCrLf)    
   i = i + 1
Loop
response.write("</select>")

response.write("<select name=""year"">")
i = 1900
Do Until i = 2005    
   response.write("<option value=" & i & ">" & i & "</option>" & vbCrLf)    
   i = i + 1
Loop
response.write("</select>")
%>

Note: Make sure the condition in a loop eventually becomes false; otherwise, the loop will never terminate.

Back to top

The Exit Keyword

The Exit keyword alters the flow of control by causing immediate exit from a repetition structure. You can use the Exit keyword in different situations, for example to avoid an endless loop. To exit the For…Next loop before the counter reaches its finite value you should use the Exit For statement. To exit the Do…Loop use the Exit Do statement.

Have a look at the example:

 
<%
response.write("<p><strong>Example of using the Exit For statement:</strong><p>")

For i = 0 to 10  
   If i=3 Then Exit For  
   response.write("The number is " & i & "<br />")
Next

response.write("<p><strong>Example of using the Exit Do statement:</strong><p>")

i = 5
Do Until i = 10
  i = i - 1
  response.write("The number is " & i & "<br />")
  If i < 10 Then Exit Do
Loop
%>

Back to top

admin

admin

Leave a Reply

Your email address will not be published.

JavaScript: Loops

JavaScript performs several types of repetitive operations, called “looping”. Loops are set of instructions used to repeat the same block of code till a specified condition returns false or true depending on how you need it. To control the loops you can use counter variable that  increments or decrements with each repetition of the loop.

JavaScript supports two loop statements: for and while. The For statements are best used when you want to perform a loop a specific number of times. The While statements are best used to perform a loop an undetermined number of times. In addition, you can use the break and continue statements within loop statements. 

The For Loop

The For loop is executed till a specified condition returns false. It has basically the same syntax then in other languages. It takes 3 arguments and looks as follows: 

for (initialization; condition; increment) 
{           
   // statements
}

When the For loop executes, the following occurs:

  • The initializing expression is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity.
  • The condition expression is evaluated. If the value of condition is true, the loop statements execute. If the value of condition is false, the for loop terminates.
  • The update expression increment executes.
  • The statements execute, and control returns to step 2.

The following example generates a multiplication table 2 through 9. Outer loop is responsible for generating a list of dividends, and inner loop will be responsible for generating lists of dividers for each individual number:

 
<script type="text/javascript">

document.write("<h1>Multiplication table</h1>");
document.write("<table border=2 width=50%");

for (var i = 1; i <= 9; i++ ) {   //this is the outer loop
  document.write("<tr>");
  document.write("<td>" + i + "</td>");
 
   for ( var j = 2; j <= 9; j++ ) { // inner loop
        document.write("<td>" + i * j + "</td>");
    }

   document.write("</tr>");
}

document.write("</table>");

</script>

Next example creates a function containing the For statement that counts the number of selected options in a list. The For statement declares the variable i and initializes it to zero. It checks that i is less than the number of options in the Select object, performs the succeeding if statement, and increments i by one after each pass through the loop.

 
<script type="text/javascript">

function howMany (selectItem) {
  var numberSelected=0

  for (var i=0; i < selectItem.options.length; i++) {
     if (selectItem.options[i].selected == true)
       numberSelected++;
  }

  return numberSelected
}

</script>

<form name="selectForm">
<p>Choose some book types, then click the button below:</p>
<select multiple name="bookTypes" size="8">
<option selected> Classic </option>
<option> Information Books </option>
<option> Fantasy </option>
<option> Mystery </option>
<option> Poetry </option>
<option> Humor </option>
<option> Biography </option>
<option> Fiction </option>
</select>
<input type="button" value="How many are selected?"
onclick="alert ('Number of options selected: ' + howMany(document.selectForm.bookTypes))">
</form>

Choose some book types and click the button below to see what the script in the preceding example does:

At last let's consider the example that uses 2 variables. One to add all the numbers from 1 to 10. The other to add only the even numbers.

 
<script type="text/javascript">

var total = 0;
var even = 0;

for ( x = 1, y = 1; x <= 10; x++, y++ ) {
  if ( ( y % 2 ) == 0 ) {
    even = even + y;
  }
  total = total + x;
}

document.write ( "The total sum: " + total + "<br>");
document.write ( "The sum of even values: " + even );


</script>

Back to top

The While Loop

The While loop is another commonly used loop after the For loop. The while statement repeats a loop as long as a specified condition evaluates to true. If the condition becomes false, the statements within the loop stop executing and control passes to the statement following the loop. The while statement looks as follows:

while (condition) 
{
  // statements
}

The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 10. i will increase by 1 each time the loop runs.

 
<script type="text/javascript">

var i=0;

while (i<=10) //Output the values from 0 to 10
{
  document.write(i + "<br>")
  i++;
}

</script>

Now let's consider a more useful example which creates drop-down lists of days, months and years. You can use this code for registration form, for example.

 
<script type="text/javascript">

var month_array = new Array();

month_array[0] = "January";
month_array[1] = "February";
month_array[2] = "March";
month_array[3] = "April";
month_array[4] = "May";
month_array[5] = "June";
month_array[6] = "July";
month_array[7] = "August";
month_array[8] = "September";
month_array[9] = "October";
month_array[10] = "November";
month_array[11] = "December";

document.write('<select name="day">');
var i = 1;
while ( i <= 31 ) {
   document.write('<option value=' + i + '>' + i + '</option>');
    i++;
}
document.write('</select>');

document.write('<select name="month">');
var i = 0;
while ( i <= 11 ) {
   document.write('<option value=' + i + '>' + month_array[i] + '</option>');   
   i++;
}
document.write('</select>');

document.write('<select name="year">');
var i = 1900;
while ( i <= 2005 ) {   
   document.write('<option value=' + i + '>' + i + '</option>');   
   i++;
}
document.write('</select>');

</script>

Note: Make sure the condition in a loop eventually becomes false; otherwise, the loop will never terminate.

Back to top

Break and Continue Statements

Sometimes you may want to let the loops start without any condition, and allow the statements inside the brackets to decide when to exit the loop. There are two special statements that can be used inside loops: break and continue. The break statement terminates the current while or for loop and continues executing the code that follows after the loop (if any). A continue statement terminates execution of the block of statements in a while or for loop and continues execution of the loop with the next iteration.

Example below shows how to use these statements:

 
<script type="text/javascript">

document.write("<p><b>Example of using the break statement:</b></p>");

var i = 0;
for (i=0; i<=10; i++) {
   if (i==3){break} 
   document.write("The number is " + i);
   document.write("<br />");
}

document.write("<p><b>Example of using the continue statement:</b><p>");

var i = 0;
for (i=0; i<=10; i++) {
   if (i==3){continue}
   document.write("The number is " + i);
   document.write("<br />")
}

</script>

Back to top

      admin

      admin

      Leave a Reply

      Your email address will not be published.

      PHP: Looping Statements

      In programming it is often necessary to repeat the same block of code a given number of times, or until a certain condition is met. This can be accomplished using looping statements. PHP has two major groups of looping statements: for and while. The For statements are best used when you want to perform a loop a specific number of times. The While statements are best used to perform a loop an undetermined number of times. In addition, you can use the Break and Continue statements within looping statements.

      The While Loop

      The While statement executes a block of code if and as long as a specified condition evaluates to true. If the condition becomes false, the statements within the loop stop executing and control passes to the statement following the loop. The While loop syntax is as follows:

      while (condition) 
      {
        code to be executed;
      }

      The block of code associated with the While statement is always enclosed within the { opening and } closing brace symbols to tell PHP clearly which lines of code should be looped through.

      While loops are most often used to increment a list where there is no known limit to the number of iterations of the loop. For example:

      while (there are still rows to read from a database) 
      {
         read in a row;
         move to the next row;
      }

      Let’s have a look at the examples. The first example defines a loop that starts with i=0. The loop will continue to run as long as the variable i is less than, or equal to 10. i will increase by 1 each time the loop runs:

      <?php
      $i=0;
      while ($i <= 10) { // Output values from 0 to 10
         echo "The number is ".$i."<br />";
         $i++;
      }
      ?>

      Now let’s consider a more useful example which creates drop-down lists of days, months and years. You can use this code for registration form, for example.

      <?php

      $month_array = array( "January", "February", "March", "April", "May", "June",
                            "July", "August", "September", "October", "November", "December");

      echo "<select name=\"day\">";
      $i = 1;
      while ( $i <= 31 ) {
         echo "<option value=".$i.">".$i."</option>";
         $i++;
      }
      echo "</select>";

      echo "<select name=\"month\">";
      $i = 0;
      while ( $i <= 11 ) {
         echo "<option value=".$i.">".$month_array[$i]."</option>";   
         $i++;
      }
      echo "</select>";

      echo "<select name=\"year\">";
      $i = 1900;
      while ( $i <= 2007 ) {    
         echo "<option value=".$i.">".$i."</option>";   
         $i++;
      }
      echo "</select>";

      ?>

      Note: Make sure the condition in a loop eventually becomes false; otherwise, the loop will never terminate.

      Back to top

      The Do…While Loop

      The Do…While statements are similar to While statements, except that the condition is tested at the end of each iteration, rather than at the beginning. This means that the Do…While loop is guaranteed to run at least once. The Do…While loop syntax is as follows:

      do 
      {
         code to be exected;
      }
      while (condition);

      The example below will increment the value of i at least once, and it will continue incrementing the variable i as long as it has a value of less than or equal to 10:

      <?php 
      $i = 0;
      do {
         echo "The number is ".$i."<br/>";
         $i++;
      }
      while ($i <= 10);
      ?>

      Back to top

      The For Loop

      The For statement loop is used when you know how many times you want to execute a statement or a list of statements. For this reason, the For loop is known as a definite loop. The syntax of For loops is a bit more complex, though for loops are often more convenient than While loops. The For loop syntax is as follows: 

      for (initialization; condition; increment) 
      {
         code to be executed;
      }

      The For statement takes three expressions inside its parentheses, separated by semi-colons. When the For loop executes, the following occurs:

      • The initializing expression is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity.
      • The condition expression is evaluated. If the value of condition is true, the loop statements execute. If the value of condition is false, the For loop terminates.
      • The update expression increment executes.
      • The statements execute, and control returns to step 2.

      Have a look at the very simple example that prints out numbers from 0 to 10:

      <?php
      for ($i=0; $i <= 10; $i++)
      {
         echo "The number is ".$i."<br />";
      }
      ?>

      Next example generates a multiplication table 2 through 9. Outer loop is responsible for generating a list of dividends, and inner loop will be responsible for generating lists of dividers for each individual number:

      <?php
      echo "<h1>Multiplication table</h1>";
      echo "<table border=2 width=50%";

      for ($i = 1; $i <= 9; $i++ ) {   //this is the outer loop
        echo "<tr>";
        echo "<td>".$i."</td>";
       
         for ( $j = 2; $j <= 9; $j++ ) { // inner loop
              echo "<td>".$i * $j."</td>";
          }

         echo "</tr>";
      }

      echo "</table>";
      ?>

      At last let’s consider the example that uses 2 variables. One to add all the numbers from 1 to 10. The other to add only the even numbers.

      <?php
      $total = 0;
      $even = 0;

      for ( $x = 1, $y = 1; $x <= 10; $x++, $y++ ) {
        if ( ( $y % 2 ) == 0 ) {
          $even = $even + $y;
        }
        $total = $total + $x;
      }

      echo "The total sum: ".$total."<br />";
      echo "The sum of even values: ".$even;


      ?>

      Back to top

      The Foreach Loop

      The Foreach loop is a variation of the For loop and allows you to iterate over elements in an array. There are two different versions of the Foreach loop. The Foreach loop syntaxes are as follows:

      foreach (array as value)
      {
         code to be executed;
      }
         
      foreach (array as key => value)
      {
         code to be executed;
      }

      The example below demonstrates the Foreach loop that will print the values of the given array:

      <?php
      $email = array('[email protected]', '[email protected]');
      foreach ($email as $value) {
         echo "Processing ".$value."<br />";
      }
      ?>

      PHP executes the body of the loop once for each element of $email in turn, with $value set to the current element. Elements are processed by their internal order. Looping continues until the Foreach loop reaches the last element or upper bound of the given array.

      An alternative form of Foreach loop gives you access to the current key:

      <?php
      $person = array('name' => 'Andrew', 'age' => 21, 'address' => '77, Lincoln st.');
      foreach ($person as $key => $value) {
         echo $key." is ".$value."<br />";
      }
      ?>

      In this case, the key for each element is placed in $key and the corresponding value is placed in $value.

      The Foreach construct does not operate on the array itself, but rather on a copy of it. During each loop, the value of the variable $value can be manipulated but the original value of the array remains the same.

      Back to top

      Break and Continue Statements

      Sometimes you may want to let the loops start without any condition, and allow the statements inside the brackets to decide when to exit the loop. There are two special statements that can be used inside loops: Break and Continue.

      The Break statement terminates the current While or For loop and continues executing the code that follows after the loop (if any). Optionally, you can put a number after the Break keyword indicating how many levels of loop structures to break out of. In this way, a statement buried deep in nested loops can break out of the outermost loop.

      Examples below show how to use the Break statement:

      <?php
      echo "<p><b>Example of using the Break statement:</b></p>";

      for ($i=0; $i<=10; $i++) {
         if ($i==3){break;} 
         echo "The number is ".$i;
         echo "<br />";
      }

      echo "<p><b>One more example of using the Break statement:</b><p>";

      $i = 0;
      $j = 0;

      while ($i < 10) {
        while ($j < 10) {
          if ($j == 5) {break 2;} // breaks out of two while loops
          $j++;
        }
        $i++;
      }

      echo "The first number is ".$i."<br />";
      echo "The second number is ".$j."<br />";
      ?>

      The Continue statement terminates execution of the block of statements in a While or For loop and continues execution of the loop with the next iteration:

      <?php
      echo "<p><b>Example of using the Continue statement:</b><p>";

      for ($i=0; $i<=10; $i++) {
         if (i==3){continue;} 
         echo "The number is ".$i; 
         echo "<br />";
      }
      ?>

      Back to top

          admin

          admin

          Leave a Reply

          Your email address will not be published.