Exercise 2-15 - CBD p. 72

Solution index                   Textual C program


#include <stdio.h>


int main(void) {  
  
  float value1, value2, value3; 
  float average = 0.0;
  int status = 0;

  printf("\nEnter value 1: ");
  scanf("%f",&value1);

  printf("\nEnter value 2: ");
  scanf("%f",&value2);

  printf("\nEnter value 3: ");
  scanf("%f",&value3);

  average = (value1 + value2 + value3)/3.0;

  printf("\nThe average is %f \n", average);
  
  return status;    

} /* END OF MAIN */

The program shown above, and to be discussed below, is a complete rewrite of the program shown on page 72 in CBD. We emphasize the choice of good variable names, consistent indentation, and 'easy to follow steps' in the program.
 

  float value1, value2, value3; 
  float average = 0.0;
  int status = 0;
Declaration of variables.
 

  printf("\nEnter value 1: ");
  scanf("%f",&value1);

  printf("\nEnter value 2: ");
  scanf("%f",&value2);

  printf("\nEnter value 3: ");
  scanf("%f",&value3);
Enter data.
 

  average = (value1 + value2 + value3)/3.0;
The average is calculated. Note that it is important to divide by 3.0, rather than just 3, as we are not interested in an integer division.
 

  printf("\nThe average is %f \n", average);
Print out the result. Notice that newlines are printed both before and after the text.
 

  return status;    
Terminate program.
 


Generated: Wednesday, March 29, 2006, 12:33:16
This program dissection page is generated from an XML-in-LAML source file