Assignment Structure

  • Compute value on right-hand side
  • Store that value into variable on left-hand side
  • Operators

    Defined on values of various types. You can apply an operator to a variable, but that just means to use its value.

    Integer Operators

    + - * / %

    / gives "floor": 9/4 = 2 % gives "remainder": 9%4 = 1

    Float Operators

    + - * /

    / is floating divide: 9.0/4.0 = 2.25

    Precedence

    What is 7 + 4 * 3?

       (7 + 4) * 3 = 33?
    or  7 + (4 * 3) = 19?

    Answer: * has higher precedence, so the correct equation is 7 + (4 * 3). The book gives detailed precedence rules on page 771, but when in doubt put parens in. Do it when there is any question so that you and the reader of the program will be sure.

    Increment and Decrement Operators

    ++, -- before and after. See increment.cpp Demo

    Loops and Decisions

    Not all programs are just a straight shot through lines of code. Sometimes we need new structures to facilitate our needs. We want to be able to loop and to execute one of several alternatives. To do this we need conditions.

    Conditions

    All decisions about executing loops and alternatives are based on conditions. Strictly speaking, a condition is just an integer-valued expression. If the expression is equal to 0, then it is considered false. If the expression is not equal to 0 then it is considered to be true.

    Relational Operators

    The following relational operators evaluate to 0 or 1.

    Logical Connectives

    C++ also contains the following logical connective operators:

    Example

    int a = 9, b = 4, c;
    c = (b != 0 && a/b > 1);
    cout << c;  //prints 1
    But if b == 0, c is 0, and a/b is not evaluated because of the "short-circuiting mechanism".

    Pitfall Example

    int a = 5, b = 4, c = 3, d;
    d = A > b > c;
    cout << d;  /prints 0
    This occurs because a > b > c is really: (a > b) > c --> (5 > 4) > 3 --> 1 > 3 --> 0. To correct this, use (a > b) && (b > c)

    If Statement

      if (expression)	or	if(expresson)
    	stmt;			  stmt;
    				else
    				  stmt;
    
    Examples
    
      if (goals >= 10){             if(year % 4 == 0)
        Yell();			  cout << "Election year";
        BreakStick();               else
        }				  cout << "We're safe";
      GoHome();

    Note

    While Loop

    while (expression) <--- header stmt; <--- body

    What the computer will do is test the expression. If it does not equal to 0 then it will do the body. Eventually the expression will equal 0 and the next statement after the body is executed. There had better be a way to make the expression be zero in the loop. Otherwise you will have created an infinite loop!!

    Notes:

      {
        stmt;
        stmt;
        .
        .
        .
      }

    See electionyear.cpp and infloop.cpp Demos

    To Index Previous Next