Monday, April 1, 2013

Birdwatching program (fixed loop & file input)

This program reads a file that contains 12 lines of bird sightings and adds up all the sightings for a year.

/* Birdwatching program (fixed loop / file input) */
#include <stdio.h> int main (void) { FILE *birdfile; int birds, days, total, i, j; birdfile = fopen ("birds.txt", "r"); total = 0; /* loop goes though all 12 months */ for (i=1; i<=12; ++i) { /* reading the number of days of sightings */ fscanf (birdfile, "%d", &days); /* loop varies with number of days of sightings */ for (j=1; j<=days; ++j) { /* reading the number of birds */ fscanf (birdfile, "%d", &birds); total = total + birds; } } fclose (birdfile); printf ("Total number of birds sighted: %d\n", total); return(0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
Total number of birds sighted: 219

birds.txt file contains:
3 4 6 7
3 1 1 1
1 1
0
7 1 5 9 11 5 4 1
2 9 1
1 3
8 2 4 6 9 12 23 4 12
6 4 6 3 9 4 11
3 2 3 7
1 9
2 9 10

No comments:

Post a Comment