CSC 101 Lecture Notes Week 3

Overall C Program Structure

The char Data Type
More on Conditional Statements
More on Functions


Relevant Reading: Chapters 4 and 6




  1. The overall structure of a simple C program.
    /* #includes for stdio.h and other libraries
    
    /* Function prototypes. */
    
    /* The main function, which calls other functions */
    
    /* Function definitions */
    


  2. The char Data Type

    1. So far we've seen types int and double, representing mathematical types integer and real, respectively.

    2. Another basic type in C is char, which represents any single character value.

    3. It's introduced in Chapter 2, page 56 of the book.

    4. You'll need to use it starting in Program 2, and Lab 4.


  3. Another update to the stats program, illustrating the use of if-else.

    1. In the previous spec, we converted negative inputs to 0, and proceeded with the stats computation.

    2. Now suppose we want to treat any negative input as an error, and not proceed with the computation.

    3. "Not proceed" means that the program outputs an error message, and exists without computing the statistics.

    4. The updated program looks like this (changes shown in red, compared to stats-non-neg.c):

      /****
       *
       * This program computes simple statistics for three real numbers read from
       * standard input.  The statistics computed are the sum of the numbers, the
       * arithmetic mean, and the standard deviation.  The results are output to
       * standard output, in the following form:
       *
       * Sum =
       * Mean =
       * Standard Deviation =
       *
       * The precise formulae for mean and standard deviation are as defined here:
       *
       *    http://www.gcseguide.co.uk/statistics_and_probability.htm
       *
       * Input numbers must be non-negative.  If a negative number is input, it is
       * treated as an error, and the program terminates without computing stats.
       *
       *
       * Author: Gene Fisher (gfisher@calpoly.edu)
       * Created: 31mar11
       * Last Modified: 3apr11
       *
       */
      
      #include <stdio.h>
      #include <math.h>
      
      #define NUM_DATA_POINTS 3               /* Fixed number of data points */
      
      /*
       * Declare the prototypes for functions used in the program.
       */
      double compute_sum(double x1, double x2, double x3);
      double compute_mean(double x1, double x2, double x3);
      double compute_std_dev(double x1, double x2, double x3);
      
      int main () {
      
          /*
           * Declare the variables used in main.
           */
          double x1, x2, x3;                  /* Input variables */
      
          /*
           * Prompt the user for the input.
           */
          printf("Enter three real numbers, separated by spaces: ");
      
          /*
           * Input the numbers.
           */
          scanf("%lf%lf%lf", &x1, &x2, &x3);
      
          /*
           * Consider any negative input to be an error, and do not perform the
           * calculation if one or more negative inputs is received.
           */
          if ((x1 < 0) || (x2 < 0) || (x3 < 0)) {
              printf("\nAll inputs must be non-negative: exiting.\n");
          }
          else {
              /*
               * Compute and output the results.
               */
              printf("Sum = %f\n", compute_sum(x1, x2, x3));
              printf("Mean = %f\n", compute_mean(x1, x2, x3));
              printf("Standard Deviation = %f\n\n", compute_std_dev(x1, x2, x3));
          }
      
          return 0;
      
      }
      
      /*
       * Return the sum of the given three numbers.
       */
      double compute_sum(double x1, double x2, double x3) {
          return x1 + x2 + x3;
      }
      
      /*
       * Return the arithmetic mean of the given three numbers.
       */
      double compute_mean(double x1, double x2, double x3) {
          return compute_sum(x1, x2, x3) / NUM_DATA_POINTS;
      }
      
      /*
       * Return the standard deviation of the given three numbers.
       */
      double compute_std_dev(double x1, double x2, double x3) {
          double mean = compute_mean(x1, x2, x3);
          return sqrt((pow(x1 - mean, 2) +
                       pow(x2 - mean, 2) +
                       pow(x3 - mean, 2)) / (NUM_DATA_POINTS - 1 ));
      }
      

    5. We'll examine this program in detail during lecture.


  4. Highlights of Chapter 4 in the Book

    1. Section 4.1: Control Structures

      1. Explains that a program is a sequence of statements, separated by semi-colons.

      2. We've seen this all over the place in the examples we've looked at.


    2. Section 4.2: Conditions

      1. Talks about the relational and logical operators used in conditional expressions.

      2. These are the kinds expressions that appear in if statements.

      3. Look closely at the descriptions in Tables 4.1 and 4.5.

        1. These tables show the symbols that C uses for conditional operators.

        2. They also show that the true/false value of conditional expressions is represented in C as the integer value 1 for true, and 0 for false.

      4. A particularly important topic is that of operator precedence in Table 4.6 of the book.

        1. This table explains the difference between expressions like
          a + b * c
          
          versus
          (a + b) * c
          

        2. In the first expression, the multiplication is done first, followed by the addition.

        3. In the second expression, the parentheses force the addition to be done before the multiplication.

      5. Another super important topic is the difference between '=' and '==' in C.

        1. The single equals sign means "assign a value to a variable".

        2. The double equals sign means "compare two values".

        3. What this means for now is that you always use == in conditional expressions, not = .

      6. You should definitely read this section of the book.


    3. Sections 4.3 and 4.4: The If Statement

      1. This section has some additional examples and explanation, to complement the examples we've discussed in lecture.

      2. Worth the read.


    4. Sections 4.5: Decision Steps in Algorithms, More Problem Solving

      1. Some useful examples are presented here.

      2. A thorough reading of these sections is as important as the preceding sections.


    5. Section 4.7: Nested if Statements and Multiple-Alternative Decisions

      1. This section covers some important topics on the more advanced use if if statements.

      2. Definitely worth reading.


    6. Section 4.8: The switch Statement

      1. This section explains the switch statement you will need to use in Lab 3.

      2. In the lab, you will use a switch with integer values, instead of the char values use in the book's example.


    7. Section 4.9: Common Programming Errors

      1. A short bit, worth the read.


  5. Using Elseless If Statements with Mid-Function Return Statements

    1. The examples we've seen have shown a number of different ways to use conditional statements.

    2. Another way you might find useful in programming assignment 2 involves the use of a return statement in the middle of a function, instead of just at the end.

    3. Here's a version of the stats program from the beginning of the notes that uses this idea:

      /****
       *
       * This program has exactly the same behavior as ./stats-neg-errors.c, q.v.
       * The only difference between this program and stats-neg-errors.c is in the
       * use of an elseless if statement followed by a return, instead of an if-else
       * statement.
       *
       * Author: Gene Fisher (gfisher@calpoly.edu)
       * Created: 13apr11
       * Last Modified: 13apr11
       *
       */
      
      #include <stdio.h>
      #include <math.h>
      
      #define NUM_DATA_POINTS 3               /* Fixed number of data points */
      
      /*
       * Declare the prototypes for functions used in the program.
       */
      double compute_sum(double x1, double x2, double x3);
      double compute_mean(double x1, double x2, double x3);
      double compute_std_dev(double x1, double x2, double x3);
      
      int main () {
      
          /*
           * Declare the variables used in main.
           */
          double x1, x2, x3;                  /* Input variables */
      
          /*
           * Prompt the user for the input.
           */
          printf("Enter three real numbers, separated by spaces: ");
      
          /*
           * Input the numbers.
           */
          scanf("%lf%lf%lf", &x1, &x2, &x3);
      
          /*
           * Consider any negative input to be an error, and do not perform the
           * calculation if one or more negative inputs is received.
           */
          if ((x1 < 0) || (x2 < 0) || (x3 < 0)) {
              printf("\nAll inputs must be non-negative: exiting.\n");
              return 0;
          }
      
          /*
           * The else is now gone, with the rest of the program just following.  The
           * preceding return makes the else unnecessary, since the program will not
           * reach this point if the return is executed.
           */
      
          /*
           * Compute and output the results.
           */
          printf("Sum = %f\n", compute_sum(x1, x2, x3));
          printf("Mean = %f\n", compute_mean(x1, x2, x3));
          printf("Standard Deviation = %f\n\n", compute_std_dev(x1, x2, x3));
      
          return 0;
      
      }
      
      /*
       * Return the sum of the given three numbers.
       */
      double compute_sum(double x1, double x2, double x3) {
          return x1 + x2 + x3;
      }
      
      /*
       * Return the arithmetic mean of the given three numbers.
       */
      double compute_mean(double x1, double x2, double x3) {
          return compute_sum(x1, x2, x3) / NUM_DATA_POINTS;
      }
      
      /*
       * Return the standard deviation of the given three numbers.
       */
      double compute_std_dev(double x1, double x2, double x3) {
          double mean = compute_mean(x1, x2, x3);
          return sqrt((pow(x1 - mean, 2) +
                       pow(x2 - mean, 2) +
                       pow(x3 - mean, 2)) / (NUM_DATA_POINTS - 1 ));
      }
      


  6. Example Showing Equivalent Alternate Uses of If and Switch Statements.

    1. As the book explains, a switch statement is an alternative form of conditional statement.

    2. It's not a critical part of the C language, but using it can in some cases make a program more clear or efficient.

      1. What's important to know about the switch statement that it's used for the same kind of conditional processing as an if, just done in a different way.

      2. A switch is less flexible than an if, since the conditional expressions used in a switch can only be integer or character data types.

    3. Here is an example illustrating four different forms of conditional in C, where each form does exactly the same computation. The program comments provide further explanatory details.

      /****
       *
       * This program illustrates equivalent uses of if, if_else and switch
       * statements.  The program has four functions, the names of which indicate the
       * kind of logic the functions use: use_if_else(), use_if_return(),
       * use_switch_break(), and use_switch_return().
       *
       * All four of the functions produce exactly the same results.  Viz., they read
       * in an integer between 1 and 3, and perform different processing based on the
       * input.  If the input is not between 1 and 3, the functions output an error
       * message.
       *
       * The actual processing the functions perform is trivial, it's simply a place
       * holder for processing that could be more involved.  The point is that
       * different processing happens based on user input.  Taken together, the
       * functions illustrate alternate approaches to using conditional logic, where
       * each approach produces precisely the same results.
       *
       * Author: Gene Fisher (gfisher@calpoley.edu
       * Created: 12apr11
       * Modified: 14apr11
       *
       */
      
      #include <stdio.h>
      
      /**
       * Function prototypes.
       */
      void use_if_else();
      void use_if_return();
      void use_switch_break();
      void use_switch_return();
      
      /**
       * Call each of the function to produce its result.
       */
      int main() {
          printf("\nRun the use_if_else function:\n");
          use_if_else();
      
          printf("\nRun the use_if_return function:\n");
          use_if_return();
      
          printf("\nRun the use_switch_break function:\n");
          use_switch_break();
      
          printf("\nRun the use_switch_return function:\n");
          use_switch_return();
      
          printf("\n");
      
          return 0;
      }
      
      
      /**
       * Input a number between 1 and 3 from the terminal.  Do some different
       * calculation based on the value of the number.  If the number is not in the
       * range 1 through 3, output an error message and do no calculation.
       *
       * This function uses an if-else statement.
       */
      void use_if_else() {
          int number;
      
          /*
           * Get the number.
           */
          printf("Please input a number between 1 and 3: ");
          scanf("%d", &number);
      
          /*
           * Do selection-specific processing based on the input, or no processing if
           * the input is out of range.
           */
          if (number == 1) {
              printf("Thank you for inputting the value 1.\n");
              printf("I'll now perform the calculation based this value ...\n");
          }
          else if (number == 2) {
              printf("Thank you for inputting the value 2.\n");
              printf("I'll now perform the calculation based this value ...\n");
          }
          else if (number == 3) {
              printf("Thank you for inputting the value 3.\n");
              printf("I'll now perform the calculation based this value ...\n");
          }
          else {
              printf("The value %d is not between 1 and 3.\n", number);
              printf("I'd say you have some issues when it comes to following instructions.\n");
          }
      }
      
      /**
       * Input a number between 1 and 3 from the terminal.  Do some different
       * calculation based on the value of the number.  If the number is not in the
       * range 1 through 3, output an error message and do no calculation.
       *
       * This function uses if statements, with multiple returns.
       */
      void use_if_return() {
          int number;
      
          /*
           * Get the number.
           */
          printf("Please input a number between 1 and 3: ");
          scanf("%d", &number);
      
          /*
           * Do selection-specific processing based on the input, or no processing if
           * the input is out of range.
           */
          if (number == 1) {
              printf("Thank you for inputting the value 1.\n");
              printf("I'll now perform the calculation based this value ...\n");
              return;
          }
          if (number == 2) {
              printf("Thank you for inputting the value 2.\n");
              printf("I'll now perform the calculation based this value ...\n");
              return;
          }
          if (number == 3) {
              printf("Thank you for inputting the value 3.\n");
              printf("I'll now perform the calculation based this value ...\n");
              return;
          }
      
          printf("The value %d is not between 1 and 3.\n", number);
          printf("I'd say you have some issues when it comes to following instructions.\n");
      
      }
      
      /**
       * Input a number between 1 and 3 from the terminal.  Do some different
       * calculation based on the value of the number.  If the number is not in the
       * range 1 through 3, output an error message and do no calculation.
       *
       * This function uses a switch statement with breaks in each case.
       */
      void use_switch_break() {
          int number;
      
          /*
           * Get the number.
           */
          printf("Please input a number between 1 and 3: ");
          scanf("%d", &number);
      
          /*
           * Do selection-specific processing based on the input, or no processing if
           * the input is out of range.
           */
          switch (number) {
          case 1:
              printf("Thank you for inputting the value 1.\n");
              printf("I'll now perform the calculation based this value ...\n");
              break;
          case 2:
              printf("Thank you for inputting the value 2.\n");
              printf("I'll now perform the calculation based this value ...\n");
              break;
          case 3:
              printf("Thank you for inputting the value 3.\n");
              printf("I'll now perform the calculation based this value ...\n");
              break;
          default:
              printf("The value %d is not between 1 and 3.\n", number);
              printf("I'd say you have some issues when it comes to following instructions.\n");
          }
      }
      
      /**
       * Input a number between 1 and 3 from the terminal.  Do some different
       * calculation based on the value of the number.  If the number is not in the
       * range 1 through 3, output an error message and do no calculation.
       *
       * This function uses a switch statement with returns instead of breaks.
       */
      void use_switch_return() {
          int number;
      
          /*
           * Get the number.
           */
          printf("Please input a number between 1 and 3: ");
          scanf("%d", &number);
      
          /*
           * Do selection-specific processing based on the input, or no processing if
           * the input is out of range.
           */
          switch (number) {
          case 1:
              printf("Thank you for inputting the value 1.\n");
              printf("I'll now perform the calculation based this value ...\n");
              return;
          case 2:
              printf("Thank you for inputting the value 2.\n");
              printf("I'll now perform the calculation based this value ...\n");
              return;
          case 3:
              printf("Thank you for inputting the value 3.\n");
              printf("I'll now perform the calculation based this value ...\n");
              return;
          default:
              printf("The value %d is not between 1 and 3.\n", number);
              printf("I'd say you have some issues when it comes to following instructions.\n");
          }
      }