Monday, April 1, 2013

The circle program (from a text file)

A program that reads from a file the diameter of a circle and prints out its circumference and area.


/* The "circle" program (using files) */

#include <stdio.h>
#define PI 3.1416

int
main (void)
{
     double diam, area, circ, r;
     FILE *in, *out;

     /* opening files */
     in = fopen ("diameter.data", "r");
     out = fopen ("report_circle.txt", "w");
 
     /* get diameter from file */
     printf ("Reading data from file...    ");
     fscanf (in, "%lf", &diam);
     printf ("Value read: %lf\n\n", diam);
        
     /* do the computations */
     r = diam / 2;
     area = PI * r * r;
     circ = 2 * PI * r;
 
     /* send results to report file */
     fprintf (out, "%4.2lf %4.2lf\n", area, circ);
     printf ("Sending results to file report_circle.txt...\n\n");

     /* closing files */
     fclose (in);
     fclose (out);
     printf ("Program completed.");
 
     return (0);
}

Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
Reading data from file...    Value read: 10.400000

Sending results to file report_circle.txt...

Program completed.

No comments:

Post a Comment