Back to DFS's C Page


Commenting on Input

Program users are (supposedly) normal people -- they don't read instructions all of the time and they frequently make mistakes. Programmers need to take this into account.

Even a naive mathematician realizes that a triangle should not have any dimensions that are negative or equal to zero. The TriangleIf program checks to see if the data being entered is reasonable. Note that the actions taken by the program are different. If the value given by the user for the base is not acceptable, the program makes a comment and stops -- if it is OK, it just continues on, asking for the height. Again, the program terminates if the data provided is inappropriate, but otherwise it says that the value is OK.

Note that for each if statement, the statement for true is a compound statement (more than a single statement) which must be bracketted by a { } combination, while the else statement for the second if is only a single statement. In other words, if the condition is true in either instance, two things are to be done, but if the second condition is false, only one thing (the printing of the message) will occur.

#include <stdio.h>  /* standard I/O header file */
void main()
{
   int b; /* base */
   int h; /* height */
   float A; /* Area */

   /* -------------------Introduction------------------ */
   printf("This program calculates and prints the area of a triangle\n");
   printf("after you enter its dimensions.\n");
   printf("When asked to, type in a dimension and hit the ENTER key.\n");
   printf("\n");
   /* --------------Inputting & Checking Data-------------*/
   printf("What is the length of the triangle's base? ");
   scanf("%d", &b);
   if (b <= 0)
   {
      printf("This would be one weird triangle!\n");
      exit(0);
   }
   printf("What is the triangle's height? ");
   scanf("%d", &h);
   if (h <= 0)
   {
      printf("The height should be positive.\n");
      exit(0);
   }
   else
      printf("That seems reasonable for the height.\n");
   /* -------------------Calculation------------------ */
   A = b * h / 2.0;
   /* -------------------Printing Results------------------ */
   printf("\n");
   printf("The area of a triangle with a base of %d units and\n", b);
   printf("a height of %d units is %.1f square units.\n", h, A);
}

© DFStermole: 3 Oct 98
HTMLified: 3 Oct 98