Sunday, May 17, 2015

Introduction to Loops - For Loop

There are several methods used for repetition within structured algorithms; the first that we will be learning is Loops.

The three types of Loops that we will be covering are:
For Loop (also known as Do Loop or Counter Controlled Loop)
While Loop
Repeat Until Loop

The For loop is used to repeat code for a specified number of times.  It falls under the control structure of repetition control structure.

First we take a look at the For Loop.  This is used when the number of repetition is known.  The syntax is as follows:





Example:
Problem Statement:  Calculate and output the sum of ten numbers.

  1. total = 0
  2. For x = 1 to 10
  3.      Print "Enter a number"
  4.      Input num
  5.      total = total +1
  6. Next
  7. Print "The sum of ten numbers entered is", total
  8. Input key

Line 1 is an example of initializing a variable.  That means that we are giving it a starting value.
Line 2 indicates that we will repeat lines 3-5 for ten times.
Line 3 is an output statement hosting a prompt.
Line 4 is an input statement whereby the value entered will be stored in the variable num.
Line 5 allows a tally to be kept each time a number is entered.
Line 6 terminates the loop.  The syntax states End For, however, the compiler uses the command Next.
Line 7 displays the total of the ten numbers with a suitable label.
Line 8 terminates the algorithm

Now, you try one:  Calculate and output the average current GPA of the students in your class based on their first, second and third form GPA.  Ask the user to enter the number of students in the class, store it in the variable Class; that variable becomes your terminating value.