CSC 101 Lecture Notes Week 2

CSC 101 Lecture Notes Week 2
Let's Start Programming


  1. A brief introduction to programming language syntax and the book's notation (textbook pp. 45-49).
    1. The term syntax refers to the grammatical structure of some written text, whether it's a story in English, a program in C++, or a piece of text in any other language.
    2. Some of you may recall a grade school exercise called "sentence diagramming", which goes something like this:
      1. Examine a sentence and determine which part of speech each word is.
      2. That is, identify parts of the sentence like the subject, the verb, and the object.
      3. For example, here is a subject/verb/object sentence diagram for the sentence "The dog loves his master."

    3. Sentence diagramming works by analyzing a sentence based on general syntactic rules.
      1. For example, here is the syntactic rule used to diagram the sentence just above, and ones like it that have the same simple structure:

      2. This rule is given in the form used throughout the textbook, which the authors call a syntax template.
        1. The name of the syntactic structure being defined appears at the top of the template.
        2. The definition appears within the box.
        3. Boldface items are literal words or symbols that must appear in a sentence exactly as they appear in the template.
        4. Two or more items from which one can be chosen are indicated with a brace to the left.
        5. Shaded items are optional.
        6. Ellipses ("...") indicate that an item can be repeated.
    4. Just like English sentences, C++ programs can be syntactically analyzed using general syntax rules.
      1. For example, here is the syntactic rule for a C++ main function, from page 49 of the book 1:

      2. This template describes the generic syntax of any C++ main program.
      3. As other C++ features are introduced in the book and the notes, their general syntax is defined in a syntax template.

  2. A sample C++ program
    1. To introduce the C++ programming topics covered in Chapter 2 of the textbook, we'll start with a simple example.
      1. Following the example, we'll review in further detail the C++ features that the example illustrates.
      2. You should note that the example is similar in program structure and complexity to programming assignment 1.
    2. Here is the example (with line numbers for reference purposes):
       1  ////
       2  //
       3  // This program computes simple statistics for five real numbers entered from
       4  // the terminal.  The statistics computed are the sum of the numbers, the
       5  // arithmetic mean, and the standard deviation.
       6  //
       7  // Author: Gene Fisher (gfisher@calpoly.edu)
       8  // Created: 30mar99
       9  // Last Modified: 1apr99
      10  //
      11  ////
      12
      13  #include <iostream.h>
      14  #include <math.h>
      15
      16  const int NUM_DATA_POINTS = 5;          // Fixed number of data points
      17
      18  int main () {
      19
      20      float i1, i2, i3, i4, i5;           // Input variables
      21      float sum;                          // Computed sum
      22      float mean;                         // Computed mean
      23      float std_dev;                      // Computed standard deviation
      24
      25      //
      26      // Prompt the user for the input.
      27      //
      28      cout << "Enter five real numbers, separated by spaces: ";
      29
      30      //
      31      // Input the numbers.
      32      //
      33      cin >> i1 >> i2 >> i3 >> i4 >> i5;
      34
      35      //
      36      // Compute the sum.
      37      //
      38      sum = i1 + i2 + i3 + i4 + i5;
      39
      40      //
      41      // Compute the mean.
      42      //
      43      mean = sum / NUM_DATA_POINTS;
      44
      45      //
      46      // Compute the standard deviation.
      47      //
      48      std_dev = sqrt((pow(i1 - mean, 2) +
      49                      pow(i2 - mean, 2) +
      50                      pow(i3 - mean, 2) +
      51                      pow(i4 - mean, 2) +
      52                      pow(i5 - mean, 2)) / (NUM_DATA_POINTS - 1));
      53
      54      //
      55      // Output the results.
      56      //
      57      cout << endl
      58           << "Sum = " << sum << ", "
      59           << "Mean = " << mean << ", "
      60           << "Standard deviation = " << std_dev << ", "
      61           << endl << endl;
      62  }
    

  3. C++ comments (example program lines 1-11 and more; textbook pp. 70-71)
    1. A comment is a part of a C++ program to aid human understanding.
    2. A comment has no operational meaning within the program, i.e., it does not affect what the program computes.
    3. In C++, a comment has two syntactic forms:
      1. starting with two slashes ("//") and extending to the end of the line
      2. starting with "/*" and ending with "*/"
    4. A comment may appear anywhere within the program text.
    5. Comments are indispensable in documenting what a program does, which is why they are required in all CSC 101 programs, as explained in the handout CSC 101 Programming Conventions, Volume 1.

  4. C++ libraries (example program lines 13-14; textbook pp. 73,77)
    1. As briefly introduced last week, C++ programs frequently use features that must be retrieved from a C++ library.
    2. These libraries define parts of the language that are not used in all programs, and therefore are included in a program only on demand, using the #include directive.
    3. In the statistics program example, the two libraries used are iostream.h and math.h
      1. The iostream library defines the cin and cout operators, and is required in all programs that use either or both of these operators.
      2. The math library defines a variety of mathematical functions, such as sqrt (the square root) and pow (the exponential, or power, function); this library is required in all programs that use one or more of these non-built-in math functions.
      3. Note that the ".h" suffix (a.k.a., extension) is used to name all C++ header files, which is how C++ libraries are physically stored.

  5. C++ identifiers (used throughout the example program; textbook pp. 49-51)
    1. The technical term used for the name of something in a C++ program is an identifier.
    2. In the sample program, identifiers are used to name the constant data value NUM_DATA_POINTS, the main function, and the program variables i1, i2, etc.
    3. The general syntactic form of an identifier is

    4. Note that this general syntax allows identifiers to start or end with an underscore, which our CSC 101 conventions disallow; hence our conventions restrict the syntax of identifiers.
    5. There are two broad categories of C++ identifiers -- reserved words and programmer-defined identifiers
      1. Reserved words are a built-in part of the C++ language, such as "int"
        1. It is a syntactic error to try to use a reserved word as a programmer-defined identifier, e.g., as the name of a variable.
        2. The complete list of reserved words is in Appendix A of the textbook.
        3. Programmer-defined identifiers include all those used in a program for naming variables, functions, and other identifiable C++ constructs we'll discuss later in the quarter.
      2. Note that identifiers from C++ libraries, such as cin and cout are considered programmer-defined, even though the programmer who uses the libraries does not define them directly.
        1. Given this, it is not a syntactic error to use the name of library identifier for some other purpose, as long as the library is not included.
        2. Nevertheless, it is a very bad idea to name variables or functions using common library identifiers, and this practice should be avoided.

  6. C++ data types (example program lines 16-23; textbook pp. 52-56)
    1. A C++ program operates on data that have specific types.
    2. In the statistics program, the constant datum NUM_DATA_POINTS is an integer (i.e., whole number), which is designated as type int in C++.
      1. C++ supports several other types of integral data, in addition to integers.
      2. These types are char (for single-character data), short (for reduced-precision integers), long (for extended-precision integers), and enum (which we will discuss a little later in the quarter).
    3. The variables in the statistics program (lines 20-23) are floating point (i.e., real numbers with a fractional part), which are designated as type float in C++.
      1. C++ has two other floating point types, in addition to float.
      2. These are double (for double-precision real numbers) and long double (for extended double-precision).
    4. In all of CSC 101, we will use only the normal-precision int and float types for integers and real numbers, respectively.
    5. We will also use the char and enum data types, a bit later in the quarter.

  7. C++ declarations (example program lines 16-23; textbook pp. 56-57)
    1. A declaration in C++ associates an identifier with a nameable item in a program.
    2. In the example C++ programs we've seen so far, there are three kinds of declarations:
      1. functions, such as the declaration of function main on line 21 of the stats example
      2. variables, as on lines 20-23
      3. constants, as on line 19
    3. The following are noteworthy properties of declarations:
      1. The names of all declared items must be unique.
      2. All identifiers must be declared before they are used.
    4. As we go through the quarter, we will see additional kinds of nameable items that can be declared.

  8. C++ variables (example program lines 20-23; textbook pp. 53, 57-59)
    1. Declaring a variable associates a name with a location in computer memory.
      1. As illustrated on page 53 of the textbook, computer memory is organized into a collection of addressable locations, each one of which can hold a changeable data value.
      2. In order to use one of the locations in a C++ program, it must be given a name, which is what the variable declaration does.
      3. As illustrated on page 54, memory locations are actually different sizes, depending on the type of data they hold.
        1. E.g., a single-character memory location is typically four times smaller than a location used to hold an integer.
        2. In CSC 101, we will typically not be concerned about this level of detail in computer memory.
    2. The general syntax of a variable declaration is as follows:

      1. The DataType is the name of a data type, such as int or float; this is the only type of data that the variable can hold. 2
      2. Following the DataType are one or more variable identifiers.
      3. The declaration must end in a semicolon.

  9. C++ constants (example program lines 16, 28, 48-52, 58-60; textbook pp. 59-61).
    1. All literal numbers used in a program, such as 5 and 2, are called numeric constants (example program lines 16, 48-52).
    2. Sequences of characters enclosed in double quotes, such as "Enter five real numbers, separated by spaces", are string constants (lines 28, 58-60).
    3. A single charcter enclosed in single quotes is a character constant (not used in the stats program).
    4. Constants can be given names in a constant declaration of the form:

    5. Giving constants declared names is beneficial in programs for two reasons:
      1. It improves program readability.
      2. It makes programs easier to change, as explained on pp. 61-62 of the book.

  10. C++ executable statements (example program lines 28-61; textbook pp. 63-70, 132-136).
    1. The real deal in a C++ program is to make things happen; this is done with executable statements.
    2. There are three kinds of executable statement in the sample stats program:
      1. Assignment statements (lines 38, 43, 48-52).
      2. Input statements (line 33).
      3. Output statements (lines 28, 57-61).

  11. C++ assignment statement (example program lines 38, 43, 48-52; textbook pp. 63-70).
    1. The C++ assignment statement stores a data value in a variable, replacing any value that is already there.
    2. The general syntax of an assignment statement is

      1. The variable to the left of the equals sign is the variable begin assigned to.
      2. The expression on the right of the assignment statement is the value being assigned.
    3. While an assignment statement looks like a mathematical equation for equality, it does not have the same meaning.
      1. The assignment statement involves an action of storing a value in memory.
      2. E.g., the assignment statement
        x = 1
        
        means "store the value 1 in the memory location named x".
      3. In contrast, the mathematical equation
        x = 1
        is simply a statement of fact; it means "the value denoted by the variable x is equal to 1".
    4. The distinction between assignment and mathematical equality is made quite clear by the assignment statement
      x = x + 1
      
      1. In C++, this means "assign to the variable x its current value plus 1"
      2. As a mathematical formula, x = x + 1 is meaningless, since it's impossible for a mathematical variable ever to equal itself plus 1.

  12. The concept of an updating assignment statement (not used in the example program; textbook pp. 66-67).
    1. The x = x + 1 example above is a form of updating or incrementing assignment statement.
    2. Such assignments are very common in C++ programs.
    3. Note in particular that you will need to use this form of assignment in your solution to programming assignment 1.
    4. The stats program example does not illustrate an updating assignment as it stands.
      1. To consider how an updating assignment could be used, suppose we wanted to input the five numbers one at a time, keeping a running total, rather than inputting them and then summing them all at once.
      2. The following program lines show how this would be done, using a running sum.
      3. These lines would replace lines 25-38 of the original stats program above.
        //
        // Prompt for and input the first number.
        //
        cout << "Enter the first of five numbers: ";
        cin >> i1;
    
        //
        // Intialize the sum to the first number.
        //
        sum = i1;
    
        //
        // Output the sum so far (which is just the value of the first number).
        //
        cout << "Running sum so far = " << sum << endl;
    
        //
        // Prompt for and input the second number.
        //
        cout << "Enter the second of five numbers: ";
        cin >> i2;
    
        //
        // Update the sum by adding in the second number.
        //
        sum = sum + i2;
    
        //
        // Output the sum so far, which is now the total of the first two numbers.
        //
        cout << "Running sum so far = " << sum << endl;
    
        //
        // Prompt for, input, and add in the remaining three numbers.  Print the
        // running sum after each number is added in.
        //
        cout << "Enter the third of five numbers: ";
        cin >> i3;
        sum = sum + i3;
        cout << "Running sum so far = " << sum << endl;
    
        cout << "Enter the fourth of five numbers: ";
        cin >> i4;
        sum = sum + i4;
        cout << "Running sum so far = " << sum << endl;
    
        cout << "Enter the fifth of five numbers: ";
        cin >> i5;
        sum = sum + i5;
        cout << "Total of all five numbers = " << sum << endl;
    
    

  13. C++ expressions (example program lines 38, 43, 48-52; textbook pp. 63-68, 99-104).
    1. C++ expressions represent computed values.
    2. The stats program illustrates three forms of numeric expressions:
      1. simple constants, such as the integer value 5 on line 16 and the 2 on lines 48-53
      2. arithmetic formulas, such as the sum on line 38 and the division on line 43
      3. formulas involving mathematical functions, such as the sqrt function on line 48, and the pow function on lines 48-52.
    3. The general form of an arithmetic expression is

      1. The Operands can be constants, variables, or other expressions
      2. The ArithmeticOperators include addition, subtraction, multiplication, division, and modulus, as shown in the table on the top of page 65 of the book.
      3. An expression without a left operand is called unary, as in the expression -2 which denotes the value negative 2.
    4. The general form of a function call used in an expression is

      1. C++ mathematical functions include the sqrt and pow functions used in the stats program, plus many more in a number of C++ libraries.
      2. A sample of the available functions is given in the table on page 103 of the book.
      3. We will use only a limited number of the many functions available in C++ libraries.

  14. C++ input/output statements (example program lines 28, 33, 57-61; textbook pp. 68-70, 132-136).
    1. C++ input and output statements serve as the interface between a human user and an executing program.
      1. In the basic form used in the stats example, input comes by typing on the terminal, and output is printed on the terminal
      2. C++ has much more elaborate forms of input/output, including reading from and writing to data files.
      3. We will study some of these forms as we progress through the quarter.
    2. The general form of C++ input and output statements are

    3. Note that ExprOrString in the OutputStatement can include the expression endl, which denotes a new line in the output stream.

  15. Summary of stylistic difference between CSC 101 conventions and the book:
    1. Variable naming
      1. CSC 101: variables are all lowercase letters, with underscores separating multiple words
      2. Textbook: variables start lowercase, and use one capital letter to start each word after the first
    2. Placement of the opening curly brace in a function definition
      1. CSC 101: the opening curly brace goes on the same line as the function heading
      2. Textbook: the opening curly brace goes at the beginning of the next line following the function heading
    3. Variable declarations always precede executable statements
      1. CSC 101: all variable declarations must precede all executable statements
      2. Textbook: the book generally follows this same convention, but does not state it explicitly


index | lectures | labs | handouts | assignments | solutions | grades | help

Footnotes

1 Note the difference in placement of the left curly brace; this is a matter of style discussed at the end of the notes.

2 Even though variables can hold only one type of data, it may appear in some programs that a different type is being assigned to a variable, as in

  int i;  

i = 2.5;
where it appears that a floating point number is being assigned to an integer variable. What is actually happening here is that the real number 2.5 is being automatically truncated to the integer 2, before it is assigned to i. Such truncation is called data coercion and is covered in Chapter 3 of the book.