Which of the following loop is best to use when the number of iteration is not fixed?

The while loop is used to repeat a section of code an unknown number of times until a specific condition is met. For example, say we want to know how many times a given number can be divided by 2 before it is less than or equal to 1. If we know a specific number, such as 32, we can say 5 times, but for a given symbolic variable "NUMBER" which represents any number in the world, how many times is not known a priori (before hand). In this case, we could use a while loop to determine that answer:

The "pseudocode" for such an algorithm is: while the number is bigger than one keep dividing it by two. additionally, keep a count of how many times we do the division.

Pseudocode

            
                get our number
                set our initial count to 0
                while our number is greater than 1
                  divide the number by 2
                  increase our count by 1
                end
            
          

Matlab

            
                count = 0;
                while (number > 1)
                  number = number / 2; %  must "move" toward end of loop
                  count  = count + 1; 
                end
            
          

C, C++, or Java

            
                int count = 0;
                while (number > 1)
                {
                  number = number / 2;
                  count++; // the same as count = count + 1;
                }
            
          

Actionscript

            
                var count:int = 0;
                while (number > 1)
                {
                  number = number / 2;
                  count++; // the same as count = count + 1;
                }
            
          


Why While Loops?

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

  2. The advantage to a while loop is that it will go (repeat) as often as necessary to accomplish its goal.

  3. Generic Syntax:

                
      while ( condition is true )
        do something
        % Note: the "something" should eventually result
        % in the condition being false
      end
                
              
  4. Infinite loops:

    If the action inside the loop does not modify the variables being tested in the loops condition, the loop will "run" forever. For example:

                
      while ( y < 10 )
        x = x + 1;
      end
                
              
                
      while (  true )
        printf('hello');
      end
                
              

Example 1: How to assure proper input

  1. Ask the user to input a value.
  2. while the input is incorrect.
  3. ask the user to input another value.
  4. go back to line 2 (the while)

Matlab

            
% MATLAB
%
% Using a while loop to ask the user to input a number
% between 1 and 10 (inclusive).
%
%   Variables:
%        value  : variable to store the input 
%

value = input ('Please Enter a Number between 1 and 10 (1-10)');

while ( value < 1 || value > 10)

  fprintf('Incorrect input, please try again.\n');
  value = input ('Enter a Number between 1 and 10 (1-10)');

end % while
            
          

C

            
/*
 * C
 * Using a while loop to ask the user to input a number
 * between 1 and 10 (inclusive).
 *
 *   Variables:
 *        value  : variable to store the input 
 */
printf("Please Enter a Number between 1 and 10 (1-10): ");
scanf("%d", &value);

while ( value < 1 || value > 10)
  {

    printf("Incorrect input, please try again.\n");
    printf("Enter a Number between 1 and 10 (1-10): ");
    scanf("%d", &value);

  }

            
          


Design Pattern:

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 while loop is:

Matlab

            
            while ( some condition is true )
              % Do this code 
              % Something here should modify the condition above 
            end
            
          

C, Java, or Actionscript

            
          while ( some condition is true )
            {
              // Do this code 
              // Something here should modify the condition above 
            }
            
          


Back to Topics List

Which LOOP should I use????

  • while:  the loop must repeat until a certain "condition" is met.  If the "condition" is FALSE at the beginning of the loop, the loop is never executed.  The "condition" may be determined by the user at the keyboard.  The "condition" may be a numeric or an alphanumeric entry.  This is a good, solid looping process with applications to numerous situations.

  • do-while:  operates under the same concept as the while loop except that the do-while will always execute the body of the loop at least one time.  (Do-while is an exit-condition loop -- the condition is checked at the end of the loop.)  This looping process is a good choice when you are asking a question, whose answer will determine if the loop is repeated.

  • for:  the loop is repeated a "specific" number of times, determined by the program or the user.  The loop "counts" the number of times the body will be executed.  This loop is a good choice when the number of repetitions is known, or can be supplied by the user.

The following program fragments print the numbers 1 - 20.  Compare the different looping procedures.  Remember, there are always MANY possible ways to prepare code!

do-while:

int ctr = 1;
do
{
    cout<< ctr++ <<"\n"; 
}
while (ctr <= 20);


for:

int ctr;
for(ctr=1;ctr<=20; ctr++)
{
     cout<< ctr <<"\n";

 

while:

int ctr = 1;
while (ctr < = 20)
{
     cout<< ctr++ <<"\n";
}

What type of loop is used when the number of iteration is not fixed?

The while loop is used to perform an indefinite number of iterations, as long as a certain condition remains true. Pros: If the number of iterations is not known up front, then this is a case where a for loop can't be used. The while loop is quite simple.

Which types of the loop can be used if the number of iteration is not fixed and have to execute the loop at least once?

do-while: operates under the same concept as the while loop except that the do-while will always execute the body of the loop at least one time.

Which of the following loop is used for fixed number of iterations in Python?

For-loops are typically used when the number of iterations is known before entering the loop. For-loops can be thought of as shorthands for while-loops which increment and test a loop variable.

Which loop is best when you exactly know the number of iterations?

For Loop: A for loop is an iteration method that is best used when you know the number of iterations ahead of time. It's always followed by the initialization, expression and increment statements.