DAT2322 - Course Notes

Introduction to Computer Programming

Prepared by Maitang Mark
March, 2000

Lesson 4

The Iteration Control Structure (DOWHILE)

    In this lesson, you will
  • learn about the iteration control structure
  • learn about the control variable and loops
  • learn about looping for a fixed number of times
  • learn about looping for a variable number of times
The statements we have been working on so far are either executed once or not executed at all. Often, we would like to have a block of code to be repeated many times without having to code it over and over again. The repeating of a block of code is also known as looping. The repeated block of code is called a loop. The power of the computer increases when we can make it repeat tasks many times and perform consistently and accurately. The iteration control structure in combination with the selection control structure is what makes computer programs useful.
    The Table of Contents

The DOWHILE Structure

  We start with a simple application to count the numbers from 1 to 5.
The while statement is used to construct a loop.

Program 4-1 Counting from 1 to 5.


#   count5.pl	Counting from 1 to 5		# line 1
#						# line 2
      $count= 1;				# line 3
      while   ($count <= 5)			# line 4
	{					# line 5
	     print $count, "\n";		# line 6
	     $count = $count + 1;		# line 7
	}					# line 8
      print "Completed.";			# line 9
 
The result of the above program:
1
2
3
4
5
Completed.
  The while statement has a block of code (from line 4 through line 8) that is structurally similar to the if statement as it has a conditional expression for testing and a block of code enclosed in a pair of braces { }. However, it works in a slightly different way. Here's how:
  • First, the conditional expression located between the parentheses is tested.

  • If the conditional expression is evaluated true, the statement block between the braces { } on line 5 and line 8 is executed. If the conditional expression is false, the statement block is skipped, and the control jumps to line 9 which is located right after the while statement. (This is called exiting the loop.)

  • Once the statement block (line 5 through line 8) is executed, the control jumps back to the start of the while statement and tests the conditional expression over again to see if it should repeat the loop.
The statement block in the while statement is repeated until the conditional expression becomes false. Then the control jumps to the line (line 9 here) immediately following the block.
 
  A good loop construct depends on a proper coordination among three factors. A loop construct must have a unique variable to control the logic flow. We shall call it the control variable. In Program 4-1, the control variable is $count. The first factor is that the control variable must have an initial stage ($count starts with 1.) The second factor is that the control variable must have an ending stage (when $count exceeds 5.) The ending stage is clearly stated in the conditional expression. The third factor is that there should be a way for $count to incrementally advance from the initial stage to the ending stage. (Line 7 serves this purpose.)
    The value in the control
      variable determines
      loop continuation.
  Once the program is running correctly, it can be made to count to 10 with very little effort. All we have to do is change the 5 in the conditional expression to 10 (see Line 4 below). We can make it to count to 1000, 5000, or a million just as easily.

      $count= 1;				# line 3
      while   ($count <= 10)			# line 4
	{					# line 5
	     print $count, "\n";		# line 6
	     $count = $count + 1;		# line 7
	}					# line 8
      print " Completed.";			# line 9
 
| To top |

Saying hello 5 times

 

Program 4.2. Saying hello 5 times. The hello program in Lesson 1 says hello once per each program run. Once you learned how to loop, it is easy to make it say more.


#   hello5.pl	Saying hello 5 times		# line 1
#						# line 2
    $count= 1;					# line 3
    while   ($count <= 5)			# line 4
	{					# line 5
	  print  "Hello! \n";			# line 6
	  $count = $count + 1;			# line 7
	}					# line 8
Instead of the counted numbers 1, 2, 3, 4, and 5, we will have "Hello!" in their places.
Hello!
Hello!
Hello!
Hello!
Hello!
| To top |

Repeating tasks

  Some of the computer functions are very repetitious. A loop is perfect for such a situation. The following is a program that draws 10 asterisks (*) in 6 lines to make a square.

Program 4.3. Drawing a square.


# square.pl	It draws a solid 6 x 10 square in *. 
#		Program 4.3 of Lesson 4
#
  $line=1;			# initialize the line to one
  $dot="*";			# give "*" a variable name

  while ($line <= 6)		# loop from line 1 to line 6
   {
      print $dot x 10, "\n";	# print "*" 10 times
      $line = $line + 1;	# ready for the next line
   }
This program introduced a new string operator, the times operator x. It is a lowercase x letter. It will repeat the string before it with the number of times indicated by the number that follows it. So "*" x 10 means "**********". and " Hello! " x 5 means five Hello! in a row.

The result of the above program displays the 6 x 10 square:

**********
**********
**********
**********
**********
**********
| To top |

Looping with Variations

  There are situations when a slight bit of variation to a repetitious task is needed. For example, if we want to draw a hollow square with four sides of asterisks and notice that the top and the bottom sides of the square are different from the lines in the middle, we can loop to draw only those in the middle and take care of the top and bottom sides separately in the following program.
**********
*                *
*                *
*                *
*                *
**********

Program 4.4. The hollow square.


# square2.pl	It draws a hollow 6 x 10 square in *. 
#		Program 4.4 of Lesson 4
#
  $line=2;		   # initialize the line to two
  $dot="*";		   # give "*" a variable name

  print $dot x 10, "\n";   # draw the first line
  while ($line <= 5)	   # loop from line 2 to line 5
   {			   # print the middle lines
      print $dot, "        ", $dot, "\n";	 
      $line = $line + 1;   # ready for the next line
   }
  print $dot x 10, "\n";   # draw the last line
The Squre2.pl program displays a hollow square.
| To top |

More Uses of the Control Variable

  The line count variable $line varies from 2 to 5 or 1 to 6 as shown in the previous two programs. This variable is useful when we want to draw positional varying shapes like a triangle.

Program 4.5. The triangle program.


# triangle.pl	It draws a triangle in 8 lines. 
#		Program 4.5 of Lesson 4
#
  $line=1;		 	  # initialize the line to one
  $dot="*";			  # give "*" a variable name

  while ($line <= 8 )	  	  # loop from line 1 to 8
   {
      print $dot x $line, "\n";	  # print "*" by $line times
      $line = $line + 1;	  # ready for the next line
   }
The result of the above program displays the triangle:
*
**
***
****
*****
******
*******
********
While $line is 1, the print statement in the loop draws one asterisk. When it is 2, it draws 2 asterisks, and so on. The line number assists in determining how many asterisks are needed.
| To top |

The User-determined Triangle

  The above program will display a triangle of a fixed size. The next program displays a triangle of a variable size depending on the user's request. It asks the height of the triangle the user wishes to draw and then proceeds to draw the requested size.

Program 4.6. The User-determined Triangle.


# triangle2.pl	It prompts for the height of the 
#		triangle to draw from the user. 
#		Program 4.6 of Lesson 4
#
  $line=1;		# initialize the line to one
  $dot="*";		# give "*" a variable name

  print "Enter a number and I will draw a triangle of that height:";
  $height = <>;		# accept a number in height
  chomp($height);	# chop out the Enter key if any

  while ($line <= $height)	  # loop from line 1 to $height
   {
      print $dot x $line, "\n";	  # print "*" by $line times
      $line = $line + 1;	  # ready for the next line
   }
A possible interaction between the user and the program is shown below:
Enter a number and I will draw a triangle of that height: 3
*
**
***
The user keyed in 3 when prompted. A 3-line triangle is drawn.
| To top |

Adding More Numbers

  The adding program, Program 2.6 of Lesson 2, adds two input numbers and displays the sum. With loops, we can have the user enter many more numbers with very little additional code. The following program adds five numbers.

Program 4.7. Adding more numbers.


# add5.pl	It prompts for 5 numbers and displays their sum.
#		Program 4.7 of Lesson 4
#
  $sum=0;			# initialize the sum to zero
  $count=1;			# set the count to one

  print "Enter five numbers, one per line. \n";
  while ($count <= 5)		# loop from 1 to 5
   {
     $num = <>;			# accept a number
     $sum = $sum + $num;	# add the input number to sum
     $count = $count + 1;	# ready for the next number
   }
  print "Sum = ", $sum;		# print the final sum
This program initializes the variable $sum to zero and the loop control variable $count to 1. When it goes through the steps of a loop, it tests for the $count value to be within 5, then it accepts a number, adds it to $sum, adds one to $count, then jumps back to test for the next loop. It exits the loop when the $count exceeds 5. The statement following the block prints the sum accumulated in $sum.

The sum depends on the numbers entered. One possible user interaction is shown below:

Enter five numbers, one per line.
4
6
3
7
5
Sum = 25
| To top |

Using A Sentinel Value

  It is possible now to modify the program to accept 10, or 100 numbers with very little effort. What if we will let the user decide when enough is enough? The following program does just that. When the user finishes inputting all the numbers, enter a # sign to signal the end. A sign which serves to signal the end is called a sentinel value.

Program 4.8 Controlling loop with a sentinel value.


# adds.pl	It prompts for as many numbers as the user input
#		until a # sign is received. 
#		Program 4.8 of Lesson 4
#
  $sum=0;			# initialize the sum to zero
  $inputNumber=0;		# the variable to store numbers

  print "Enter numbers, one per line. Use the symbol # to end.\n";
  $inputNumber=<>;		# accept the first number
  chomp($inputNumber);		# chop off the Enter key

  while ($inputNumber != "#" )	# loop till # is accepted
   {
     $sum = $sum + $inputNumber;# add the input number to sum
     $inputNumber=<>;		# accept the next number
     chomp($inputNumber);	# chop off the Enter key
   }
  print "Sum = ", $sum;		# print the final sum
The program is more complicated because the code for accepting the first number is separated from that for accepting the subsequent numbers. This is necessary to cover the rare occasion in which a user shall decide that the first number is #. In that case, the while statement tests the condition ($inputNumber != "#") to be false. It skips over the loop body and executes the last statement which prints the sum as zero.

The following are possible interactions with the user when running the program:

A:\>perl adds.pl
Enter numbers, one per line. Use the symbol # to end.
5
16
34
#
Sum = 55
a:\>perl adds.pl
Enter numbers, one per line. Use the symbol # to end.
56
34
11
100
#
Sum = 201
A:\>perl adds.pl
Enter numbers, one per line. Use the symbol # to end.
#
Sum = 0
| To top |

Lesson 4 Exercises

 
  1. Write a program which will display all even numbers from 0 to 20 using a while loop.

  2. Write a program which will display all odd numbers from 1 to 19 using a while loop.

  3. Write a program which will count down the numbers from 10 to 0 using a while loop.

  4. Write a program which will add all numbers from 1 to 10 in a loop and display the sum.

  5. Write a program which will display the following triangle using a while loop.
    ********
    *******
    ******
    *****
    ****
    ***
    **
    *
  6. Add a loop routine to exercises 5 of Lesson 2 (or the sample program 3.5 guess.pl) to allow the user to keep on guessing as many times as needed.

  7. Add a loop routine to the sample program 3.2 grade.pl to process many grades until a sentinel value is received. Devise your own sentinel value.

  8. Add a loop routine to the sample program 3.4 payroll.pl to process many payrolls until a sentinel value is received. Devise your own sentinel value.
| To top |
M. Mark, 2002.03.18 | Introduction | Lesson 1 | Lesson 2 | Lesson 3 | Lesson 4 | Appendix |