The Modula-2 Programming Language:

Sum and Average Example Program


Click below to go directly to a specific section:
Description | Source Code | Sample Run | Program Notes

Description

This program reads from an input file, calculates the sum of all the integers in the file, and calculates the average. The program demonstrates how to open a file, read from a file, and to print the results to an output file. The data file that was used to run the program consisted of the numbers 0 to 10 and the output is shown under the Sample Run.

Source Code


MODULE SumAndAverage;

FROM InOut IMPORT ReadInt, WriteString, WriteLn, WriteInt, 
		  OpenInput, OpenOutput, CloseInput, 
		  CloseOutput, Done;

VAR

     N:INTEGER;
     X:INTEGER;
     SUM:INTEGER;
     AVERAGE:INTEGER;

BEGIN
     WriteString('Enter the names of the output, input files');
     WriteLn;
     OpenOutput("OUT");
     IF NOT Done THEN
	WriteString('Output file cannot be opened');
	WriteLn;
	HALT;
	END;
     OpenInput("IN");
     IF NOT Done THEN
	CloseOutput;
	WriteString('Input file cannot be opened');
	WriteLn;
	HALT;
	END;

     N:=0;
     SUM:=0;
     ReadInt(X);
     WHILE Done DO
	WriteInt(X,3);
	WriteLn;
	N:=N+1;
	SUM:=SUM+X;
	ReadInt(X);
	END;

WriteString('The Sum is ');
WriteInt(SUM, 1);
WriteLn;
AVERAGE:=SUM DIV N;
WriteString('The Average is ');
WriteInt(AVERAGE, 1);
WriteLn;
CloseOutput;
CloseInput;

END SumAndAverage.



Sample Run

   0
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
The Sum is 55
The Average is 5


Program Notes

This program was written with the help of A Guide to Modula-2 by Kaare Christian and Modula-2 Text and Reference by John Moore and Kenneth McKay. It was compiled, tested, and run on Modula-2 compiler version 2.0a
[Back] [Home]

Last modified: 03:39 PM on 11/22/1996