Programming in C

(Barry) #1
The ifStatement 67

The program was run twice to verify that it is functioning properly. Of course, it might
be desirable to run the program several more times to get a higher level of confidence so
that you know it is indeed working correctly, but at least you know that you have
checked both possible outcomes of the decision made by the program.
After a message is displayed to the user and the integer value that is entered is stored
in number, the program tests the value of numberto see if it is less than zero. If it is, the
following program statement, which negates the value of number, is executed. If the
val ue of numberis not less than zero, this program statement is automatically skipped. (If
it is already positive, you don’t want to negate it.) The absolute value of numberis then
displayed by the program, and program execution ends.
Look at Program 6.2, which uses the ifstatement. Imagine that you have a list of
grades for which you want to compute the average. But in addition to computing the
average, suppose that you also need a count of the number of failing grades in the list.
For the purposes of this problem, assume that a grade less than 65 is considered a failing
grade.
The notion of keeping count of the number of failing grades indicates that you must
make a decision as to whether a grade qualifies as a failing grade. Once again, the if
statement comes to the rescue.


Program 6.2 Calculating the Average of a Set of Grades and Counting the Number of
Failing Test Grades


/ Program to calculate the average of a set of grades and count
the number of failing test grades
/


#include <stdio.h>


int main (void)
{
int numberOfGrades, i, grade;
int gradeTotal = 0;
int failureCount = 0;
float average;


printf ("How many grades will you be entering? ");
scanf ("%i", &numberOfGrades);

for ( i = 1; i <= numberOfGrades; ++i ) {
printf ("Enter grade #%i: ", i);
scanf ("%i", &grade);

gradeTotal = gradeTotal + grade;
Free download pdf