Turbo Pascal 7.0 Guide
Arrays

So far, when we have wanted to enter and process a series of numbers, we have used one variable to accept the input before adding it to a running total. This has been fine for the programs that we have written so far, but does not help if we need our programs to do something else with the individual values after they have been entered. For this we need to use an array.

An array is a list of variables which have the same name. Each individual variable is identified by its index, a number in square brackets after the name.   eg   a[1]   a[2]   a[3]   a[100]

To declare an array at the beginning of a program, use the following notation,

VAR a: array[1..100] of integer;

Example Program

This program uses to arrays to accept the names and scores of 10 students who have completed a test. It then adds up their scores, calculates the mean and prints the names of those students who scored higher than the mean.

PROGRAM testscores;
USES crt;
VAR n, total: integer;
VAR mean: real;
VAR score: array[1..10] of integer;
VAR name: array[1..10] of string;
BEGIN
   clrscr;
   total:= 0;
   FOR n:= 1 TO 10 DO
      BEGIN
         write('Input name ', n, ':');
         readln(name[n]);
         write('Input score ', n, ':');
         readln(score[n]);
         total:= total + score[n];
      END;
   mean:=total/10;
   writeln;
   writeln('Students scoring more than the mean of ', mean:5:2);
   FOR n:= 1 TO 10 DO
      BEGIN
         IF score[n]>mean THEN
            writeln (name[n]:12, ' scored ', score[n]);
      END;
   readln;
END.

Exercises

  1. Read in 10 letters to an array of the type char. Output them to the screen in reverse order of how they were entered.
  2. Write a program to choose 100 random numbers between 1 and 100. Count and display how many numbers are in the range 1-10, 11-20, 21-30 etc.
  3. A prime number is a number that is divisible only by itself and 1. Write a program that finds all of the prime numbers up to 10000. You may be able to solve this problem without using an array.