For Loop

A "For" Loop is used to repeat a specific block of code a known number of times. For example, if we want to check the grade of every student in the class, we loop from 1 to that number. When the number of times is not known before hand, we use a "While" loop.

The For Loop

The for loop is used to repeat a section of code known number of times. Sometimes it is the computer that knows how many times, not you, but it is still known. Some examples:

Unknown number of times:

Known number of times:


Design Pattern Quick Reference:

A design pattern is the syntax that you have to memorize in order to do well in programming and on tests.

The design pattern for a for loop is:

Matlab

            
        for index = start_value : increment_value : end_value
           % Do this code 
        end

        % implied increment by 1
        for index = start_value : end_value  
           % Do this code 
        end
            
          

C, Java

            
        for ( int index = start_value; index < end_value; index += increment_value )
          {
             // Do this code 
          }

        // Note: we often will declare the variable i at the
        // same time we write the for loop, but we could declare
        // it above
            
          

ActionScript

            
        for ( var index:int = start_value; index < end_value; index += increment_value )
          {
             // Do this code 
          }

        // Note: we often will declare the variable i at the
        // same time we write the for loop, but we could declare
        // it above
            
          

JavaScript

            
        for ( let index = start_value; index < end_value; index += increment_value )
          {
             // Do this code 
          }

        // Note: we often will declare the variable i at the
        // same time we write the for loop, but we could declare
        // it above
            
          

In the above code, the following variables are used:


Why For Loops?

  1. Like all loops, "for loops" execute blocks of code over and over again.

  2. The advantage to a for loop is we know exactly how many times the loop will execute before the loop starts.

  3. The Syntax of the for loop in several languages is below. Notice how each language captures the "semantics" of a for loop (the meaning) but each has slightly different syntaxes. The variable "i" below is always used as the loop counter. The variables, start_value,by_count,and finish_value all represent numbers. For each language and example of the code to sum the numbers from 1 to 10 is given.

    Matlab

                      
     % design pattern
     for i = start_value:by_count:finish_value
       do something
     end
    
     % example: sum numbers from 1 to 10
     total = 0;
     for i = 1 : 10
       total = total + i;
     end
                      
                    

    C, Java

                      
     // design pattern
     for (int i=start_value; i < finish_value; i = i + by_count )
       {        
         do something
       }
    
     // example: sum numbers from 1 to 10
     int total = 0;
     for (int i=1; i<10; i++)
       {
         total += i;
       }
                      
                    

    ActionScript

                      
     // design pattern
     for (var  i:int = start_value; i < finish_value; i = i + by_count );
       {        
         do something
       }
    
     // example: sum numbers from 1 to 10
     var total:int = 0;
     for (var i:int=1; i<10; i++)
       {
         total = total + i;
       }
                      
                    

Examples:

Our first example is trying to find a specific value in a list (array) of values.

The algorithm is:

  1. Look at the first element in the array
  2. if it is the desired element, you are done
  3. if it is not, then go to the next element of the array and continue.

Matlab

            
  %
  % Using a for loop to find a value in an array.
  %
  %   Variables:
  %        i      : the loop index. Changes from start to finish
  %        start  : the first index of the array. usually one
  %        finish : the last index of the array. ( found with length(array) )
  %        array  : a list of integer numbers
  %        search : the number we are looking for.
  %
        

 start  = 1;              % note you could simply use 1 below
 finish = length(array);  % note you could put length(array) below

 for i = start:finish     % default is to count by 1's

   if (array(i) == search)  % note: for non-integers we would not use ==

     fprintf('found the item\n');   % note: we often would not print
                                   % the value, simply return it (if we
                                   % were in a function).
   end % if

 end % for
            
          

C Language

            
  //
  // Using a for loop to find a value in an array.
  //
  //   Variables:
  //        i      : the loop index. Changes from start to finish
  //        start  : the first index of the array. usually one
  //        finish : the last index of the array. ( found with length(array) )
  //        array  : a list of integer numbers
  //        search : the number we are looking for.
  //
        

 int array[100];              // note: in C, we must specify how large the array is
 int start  = 0;              // note you could simply use the constat 0 below
 int finish = 100;            // must know how many elements in array

 for (int i = start; i < finish; i++)     // ++ means add one to i
   {
     if (array[i] == search)  // note: for non-integers we would not use ==
       {
         printf("found the item\n");  // note: we often would not print
                                     // the value, simply return it (if we
                                     // were in a function).
       }

   }
            
          

ActionScript

            
  //
  // Using a for loop to find a value in an array.
  //
  //   Variables:
  //        i      : the loop index. Changes from start to finish
  //        start  : the first index of the array. usually one
  //        finish : the last index of the array. ( found with length(array) )
  //        array  : a list of integer numbers
  //        search : the number we are looking for.
  //
        

 var array  : Array;         
 var start  : int  = 0;         // note you could simply use the constat 0 below
 var finish : int  = 100;       // must know how many elements in array

 for (var i:int = start; i < finish; i++)     // ++ means add one to i
   {
     if (array[i] == search)  // note: for non-integers we would not use ==
       {
         trace("found the item\n");  // note: we often would not print
                                     // the value, simply return it (if we
                                     // were in a function).
       }

   }
            
          

Example 2: Creating Odd Numbers

See the while loop design pattern to see how to accomplish this using a while loop.

Matlab

            
  %
  % Using a for loop to create and store all the odd numbers
  %      between 1 and 1000
  %
  %   Variables:
  %        i      : the loop index. 
  %        array  : a list of integer numbers
  %

  for i = 1:2:1000    % here we change the default to count by 2
                      % that is what the :2: means (start:by:end)

    array( ceil(i/2) ) = i;

  end  % for 

   % alternatively

  for i = 1:500    % here we change count by 1
                      % and compute the appropriate odd value

    array( i ) = i * 2 - 1;

  end  % for 
            
          

C Language

            
  /** 
   *
   * Using a for loop to create and store all the odd numbers
   *     between 1 and 1000
   *
   *   Variables:
   *        i      : the loop index. 
   *        array  : a list of integer numbers
   */

  for (int i = 1; i<1000; i += 2)    // i += 2 is a  shortcut for saying i = i + 2)
    {
      array[ i/2 ] = i;
    }

  
  // alternatively

  for (int i = 0; i<500; i++)   // i++ means add one to i each time
    {
      array[ i ] = ( (i+1) * 2 ) - 1;
    }

            
          

ActionScript

            
  /** 
   *
   * Using a for loop to create and store all the odd numbers
   *     between 1 and 1000
   *
   *   Variables:
   *        i      : the loop index. 
   *        array  : a list of integer numbers
   */

  for (var i:int = 1; i<1000; i += 2)    // i += 2 is a  shortcut for saying i = i + 2)
    {
      array[ i/2 ] = i;
    }

  
  // alternatively

  for (var i:int = 0; i<500; i++)   // i++ means add one to i each time
    {
      array[ i ] = ( (i+1) * 2 ) - 1;
    }

            
          

Back to Topics List