For....Next loops - adding 10 numbers
Back to Main Page
Many computer programs will include code that needs to be repeated several, or indeed, many times. If we wrote a program which allowed the user to add ten numbers without a for...next loop, the algorithm would look something like this:


Ask user for first number
Add first number to total
Ask user for second number
Add second number to total
Ask user for third number
Add third number to total
......and so on until the tenth number was added.


What if we wanted to input marks for 100 National diploma students? We would have to write hundreds of lines and type them all in - time-consuming and prone to errors.
The answer is to use a For...Next loop which allows us to repeat a section of code as many times as we wish, but write it only once. We use a variable - usually called
COUNT to keep count of the number of ITERATIONS or repeats we have completed.



The structure of the For...Next loop for adding ten numbers is as follows:


For Count = 1 to 10                                                           - sets count to go from 1 to 10
       Number = InputBox("Please enter a number")     
- asks the user to type a number
       Total = Total + Number                                             
- adds the new number to total
Next Count                                                                     
  - returns to first line until count = 10



Task 1

Type the following code into VB and test it with ten numbers:
Task 2

Write a program which will calculate the average score for a student sitting 5 end-of-year exams. You can assume that all marks will be an integer (whole number)
The algorithm should work as follows:

- ask the user to enter the mark
- add the mark to the total
- loop until all 5 marks have been entered
- calculate the average mark - i.e. divide the total by 5
- display the average mark with an appropriate message
Hosted by www.Geocities.ws

1