Sample Program and Documentation for UHCL Programming Classes  

/************************************************************************
* Programmer:  your name
*
* Course:  CSCI 2315.01
*
* Date:  January 28, 2015
*
* Assignment:  Number 1
*
* Environment:  Borland C++ running in the PC lab on Windows 2000
*
* Files Included: a:\\program1.c,   a:\\testin.dat,   a:\\testout.dat
*
* Purpose:  To read 5 integers from an input file, calculate the sum, and print the integers
*       and the sum to an output file
*
* Input:  5 integers are in a:\\testin.dat
*
* Preconditions:  Only integers are in the input file
*
* Output:  A sum is calculated and printed to a:\\testout.dat, or an error message is printed
*
* Postconditions:  sum is calculated only if all numbers are in the range of -2345 to +2346
*
* Algorithm:
*          Open file for reading
*          Set sum = 0
*          For each of five integers in the input file
*               Read a number
*               If  the number is in range then
*                   add this number to the sum
*               Else indicate error
*          If all numbers were in range
*               Write the sum to the output file
*          Else print error message
*          Close the input file
***********************************************************************/
#include <stdio.h>
void print_sum (int);    /* include function prototypes */
 main()
{
FILE *infile;
int Neg = -2345;
int Pos = 2346;
int i, error_code = 0, sum = 0, num = 0;

infile = fopen ("a:\\testin.dat", "r");
for (i = 0; i< 5; i ++)                          /* please put comments here if they help with clarity */
   {
    fscanf (infile, "%d", &num);
    if (num >= Neg && num < Pos)    /* if the number is in range*/
           sum = sum + num;                  /* then add it */
    else error_code = 1;
    }

if (error_code == 0)
    print_sum (sum);                           /* all numbers are in range */
else
    printf ("A number is out of range – please check  it ");

fclose (infile);
}
 
 


void print_sum (int sum)
/************************************************************************
* Purpose:  To print a sum to an output file
*
* Parameters:  An integer sum is passed to this routine
*
* Action:  A sum is written to a:\\testout.dat
*
***********************************************************************/
{
FILE *outfile;
outfile = fopen ("a:\\testout.dat", "w");
fprintf (outfile, "The sum is  ",  %4i\n", sum);
fclose (outfile);
}
 



Thanks to Lakshmi V. for her help in preparation of this example.