CIS 071 Fall 2003 – Sample Code – Find the errors (make a $1)

 

/* This is a short sequence of code designed to illustrate one way to provide a user-friendly interface between software and the user of that software. Here we give the user extra chances to enter correct data. We limit the number of chances to 3. Note how complicated this gets. The code shows examples of the use of:

1.   a while loop structure – the use of initialization, testing and updating of a loop control variable

2.   a multiple alternative decision structure (inside the while loop)

3.   define macros for defining named constants

4.   a “Boolean flag” in a condition controlling a while loop

5.   the use of unary increment operators such as ++

*/

 

// Two defines (for “named constants”) to help make code more readable

#define FALSE = 0

#define TRUE = 1

 

int ft_correct_flag; // Data entry (figure type) correct flag - Boolean

 

printf (“Enter M, m, F, or f to indicate if “);

printf (“male or female is to be drawn – “);

scanf  (“%c”, dchar);

 

// Initialize loop control variable to ensure loop executes once

ft_correct_flag = FALSE;  // initialize loop control variable

// Set counter for number of tries

int count_tries = 0;

 

while (!ft_correct_flag) { // if improper data entry

   if (toupper(dchar) == ‘M’) { 

      draw_Mfig( );

      ft_correct_flag = TRUE;  // updates loop control variable

   }

   else if (toupper(dchar) == ‘F’) {

      draw_Ffig( );

      ft_correct_flag = TRUE;  // updates loop control variable

   }

   else {

      count_tries++;

      if (count_tries <= 3) {

         printf (“Oops – you entered a %c “, dchar);

         printf (“ and not M, m, F, or f.\n”);

         printf (“You will have to try again.”); 

         printf (“Type M, m, F, or f, please. - ”);

         scanf  (“%c”, dchar);

      }

      else {  

         printf (“Sorry.  You had three tries. Get some help.\n”);

         exit ( );

      } end if (on count_tries)

   // end if (on correct character entered)

} // end while