C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1

As a real-world example, suppose a teacher wrote a program to average the 25 students’ test scores.
The following program keeps a running total of the 25 students. However, if a student or two missed
the test, the teacher wouldn’t want to average the entire 25 student scores. If the teacher enters a -
1.0 for a test score, the -1.0 triggers the break statement and the loop terminates early.


Click here to view code image


// Example program #1 from Chapter 16 of Absolute Beginner's Guide
// to C, 3rd Edition
// File Chapter16ex1.c
/* This program will ask users to input test grades for the 25 students in a class and
then compute an average test grade. If fewer than 25 students took the test, the user
can enter -1 as a grade and break the loop, and only those entered grades will be used
to compute the average. */
#include <stdio.h>
main()
{
int numTest;
float stTest, avg, total = 0.0;
// Asks for up to 25 tests
for (numTest = 0; numTest < 25; numTest++)
{
// Get the test scores, and check if -1 was entered
printf("\nWhat is the next student's test score? ");
scanf(" %f", &stTest);
if (stTest < 0.0)
{
break;
}
total += stTest;
}
avg = total / numTest;
printf("\nThe average is %.1f%%.\n", avg);
return 0;
}

Before discussing the program, take a look at a sample run of it:


Click here to view code image


What is the next student's test score? 89.9
What is the next student's test score? 92.5
What is the next student's test score? 51.0
What is the next student's test score? 86.4
What is the next student's test score? 78.6
What is the next student's test score? -1
The average is 79.7%
Free download pdf