[Skip Navigation] [CSUSB] / [CNS] / [Comp Sci Dept] / [R J Botting] / [CSci201] / 05
[Text Version] [Syllabus] [Schedule] [Glossary] [Labs] [Projects] [Resources] [Grading] [Contact] [Search ]
Notes: [01] [02] [03] [04] <05> [06] [07] [08] [09] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20]
Podcasts: [01] [02] [03] [04] [05] [06]
Labs: [01] [02] [03] [04] [05] [06] [07] [09] [10]
Tue Jan 22 18:39:19 PST 2008

Contents


    pages 45-48 Logic

      Podcst on reading

      [ 05.mp3 ]

      Project 1 is due at start of the class.

      Why learn logic

      Logic is not just the basis of computer circuits, it is also a fundamental tool of the computer professional. The ability to read and write logical formulas (Boolean expressions) is both easy and vital. One way to learn more about these expressions, in abstract, is to take one of the more formal GE courses in critical thinking.

      The good news -- logical operations are easy to understand and pretty easy write. The bad news -- they can get complex and some are difficult to get right. These notes points out half-a-dozen common mistakes (traps) made when people are writing conditions in C++.

      Reading -- Pages 45-48

        These three pages introduce some simple ideas that will be used in every program you will write. They (or similar ones) are used in every language.

        Hint -- a few extra parenthesis make logical expressions easier to read

        Comparison Operators -- page 45

        SymbolMeaningtrue examplefalse example
        <less than1<22<2
        <=less than or equal1<=22<=1
        ==equal to1==11==2
        !=not equal to1!=21!=1
        >greater than2>12>2
        >=greater than or equal2>=21>=2

        Trap -- == vs =

        Do not write something like this:
         		if( i = 1 )                   //ERROR
        when you want to test for equality. The above compiles and runs but (1) the condition is always true and (2) it changes the variable i to be 1! Instead write
         		if( i == 1 )

        Trap -- using == with doubles

        You can not rely on "==" working with double length numbers because of rounding errors. The value of (x == y) when x and y are doubles is nearly always false. It is better to check to see if x and y are close togther. A test like
         		if ( fabs(x-y) <= EPSILON )
        is usually what is needed -- where you choose EPSILON to be a constant small number set to an acceptable error.
         		const double EPSILON = 0.0000001;

        Logical Operators -- and, or, not -- page 46

        For historial reasons we have two notations for each logical operator.
        SymbolWord
        &&and
        ||or
        !not
        Proffesional C++ programers tend to use the symbolic form -- C/Java/PHP programmers don't have a choice. I plan to use the words. You can use which ever you like.

        Hint -- Testing for divisibility

        Many times a program will need to find out if one number is divisible by another. As a simple example is a number even or odd. The "%" operator is useD to calculate remainders after dividing. So we can use
      1. number % divisor == 0

        to check if the number is divisible by the divisor. For example, you might write:

         	if( number % 2 == 0)
         		cout << number << "is even."<< endl;
         	else
         		cout << number << "is odd."<< endl;

        Complex Conditions

          Complex conditions turn up in the solutions of many problems. They can be challenging to code. For example, suppose that an int variable year holds the number of the year -- say 2008. We may need to calculate whether this is a leap year or not.

          Every body knows that if the year is divisible by 4 then we have a leap year:

           		year % 4 == 0
          but this is not quite right, because nowadays the rule is more complex. When the year is a century, because then we must check if the century is divisible by 4:
           		year % 100 == 0 and (year /100) % 4 == 0
          When the year is not a century we have.
           		year % 100 != 0 and year % 4 == 0
          Now we need to combine the two rules. In this case their is a leap year if either condition is true:
           		(year % 100 == 0 and (year /100) % 4 == 0)
           		or
           		(year % 100 != 0 and year % 4 == 0)
          In fact the exact rule is worse than this because the century condition was only introduced in different years depending on which country you are in... For more information check out the Wikipedia on the web.

          The above shows that real life can involve complex conditions. The income tax code provides many more complex examples. Many businesses have very complicated formulas for calculating discounts, wages, stocks, etc.. Analysing and coding these is very interesting.

          Hint -- lay out conditions tidily

          Trap -- English syntax != C++ syntax

          This is a classic error. You want to code
        1. x and y are both equal to 0

          so you write

        2. x and y == 0

          Sadly, in C++, this is wrong. In C++ it compiles and computes the wrong condition because of the design of C++ (see [ Strange Conditions ] below). The correct code is

           		(x==0) and (y==0)

          Trap -- range tests

          Suppose you want to test if x lies between 1 and 2 inclusive. The following
           		if( ( 1 <= x ) and (x <= 2) )
          will work but
        3. 1 <= x <= 2 is incorrect -- it compiles and does something quiet wierd. Again see [ Strange Conditions ] below.

          Trap -- Using and when or is needed

          English speakers can get confused and use and when they need or. The result is often an condition that is always false (and so useless).

          You have to be very careful working these out.

          The data type bool and the two logical constants -- true and false

          George Boole investigated "The Laws of Thought" and invented an algebra (Boolean Algebra) that is name after him. This was an algebra with two values -- true, false. In his honor the logical values in C++ are said to be of type bool.

          So far you have met int and double. Now you have met bool. You can have Boolean variables, and store the results of bool expressions for future use:

           		bool tooBig = (x >= 10000);
           ...
           		if( tooBig ) ...
          Introducing bool variables can simplify complex conditions and make your prgram more readable.

          Hint -- Use Boolean Algebra to simplify conditions

          The rules of George Boole's algebra are useful for simplifying C++ conditions. Here is a list of the rules you can use
        4. Boolean_Algebra::=following
          Net
          1. For p, q, and r boolean expressions.
          2. p and p == p.
          3. p and q == q and p.
          4. p and (q and r) == (p and q) and r == p and q and r.
          5. p and false == false.
          6. p and true == true.

          7. p or p == p.
          8. p or q == q or p.
          9. p or (q or r) == (p or q) or r == p or q or r.
          10. p or true == true.
          11. p or false == p.

          12. not (not p) == p.

          13. not ( p and q ) == (not p) or (not q).
          14. not ( p or q ) == (not p) and (not q).

          (End of Net Boolean_Algebra)

          Add to these the rules for negating comparisons

        5. negating_comparison_operators::=following
          Net
          1. For expressions x,y.
          2. not (x==y) == (x!=y).
          3. not (x!=y) == (x==y).
          4. not (x<=y) == (x>y).
          5. not (x<y) == (x>=y).
          6. not (x>=y) == (x<y).
          7. not (x>y) == (x<=y).

          (End of Net)

          Here is an example based on our old text book -- Horstmann.

          Suppose we are working for a catelog company that has complex rules for calculating discounts depending on the country and the state. Our program may include this code

           		if( not (country == USA and state != AK and state!=HI))
           			shipping_charge = 20.00;

          We can use Boolean algebra to simplify the condition:
          Let

          1. not (country == USA and state != AK and state!=HI)
          2. not (country == USA) or not ( state != AK) or not (state!=HI)
          3. country != USA or state == AK or state==HI

          (Close Let )
          So the following will do the same test, simpler:
           		if( country!=USA or state==AK or state==HI)
           			shipping_charge=20.00;

        Strange Conditions

        Any expression can be a condition in C++! In an if like this
         		if( e )
        the expression e is evaluated and if the value is 0 then the if treats it as false. If e is non-zero then it is taken to be true.

        This is why we do not express x and y are greater than 0 like this x and y > 0. C++ treats this as (x) and (y > 0) and this is true if x is not 0 and y is greater than zero.

        Similarly, C++ will convert a bool value into numbers:

        and this is why 1<=x<=2 does not test if x lies betweeen 1 and 2. Instead C++ treats this as (1<=x) <= 2 -- first the program tests if x is greater than 1 and if it is produces a 1, of false then it gets a 0. These are then compared to 2. The result is therefure true!

        The property that in C++ data becomes bool and vice versa is exploited when we test to see if an input has worked or not:

         		if ( cin >> something )
         		{ do something }
         		else
         		{ panic }

      Questions on logic

        Are there times outside the lab when I am availabe

        Look for my office hours -- this defines 4*50 minutes each week when I will be available in my office: Tu+Th 10:30-11:40 and Wedns 3-4:20.

        How do you use SSH to log in to CSci.CSUSB


        1. Download the installer.... see syllabus.
        2. Execute it and you should get a couple of extra Icons.
        3. Double click to get a terminal window
          The host is jbh3-1.csci.csusb.edu

        What does using namespace std mean and why do we use it

        A namespace is a collection of names. The namespace std contains many useful names including cout and cin. The using namespace allows us to write these without saying which namespace they are in.

        The libraries that we #include are they real files

        Yes. They are placed in /use/include in most UNIXes. Many of them are files with the extension '.h' for header. You get them from the same place as the compiler.

        How do you code exponents in C++

        Mathematical expressions x to the power y, for general y are written
         		pow(x,y)
        using the <<cmath>> library. The mathematical exponential function e to the x can be written
         		exp(x)
        using the smae library. The parentheses are essential.

        How many libraries can you include in one program

        As many as you want.

        Can you have pi in a program without cmath

        Only if you type in the value of π yourself

        What is the reason that x and y == 0 is not (x==0) and (y==0)

        Tradition.

        What programs have logical expressions

        Nearly every program needs conditions and the simplest way to write these is nearly always using logical operators.

        What types of programs have truth tables

        Not many..... BUT truth tables are a good way to think about complex conditions.

        Can we use the comparison operators

        Yes. Indeed you will and must use them:-)

        When do use the not operator

        You use it when you have written an expression but realise it is the oposite of what you wanted. The you put "not("...")" around it.

        How many different comparison operators are in C++

        6

        How many different logical operators are in C++

        3

        How many must we know

        All 3 logical operators, and all 6 comparison operators.

        Are there only 3 logical operators in C++

        Yes -- kind of. The 6 comparison operators can also be used to compare bool expressions. For example
        pqP<q
        falsefalsefalse
        falsetruetrue
        truefalsefalse
        truetruefalse

        What does bool mean

        The reserved word bool in C++ is the name of a type of Boolean data.

        Where do bool and get their names from.

        The name bool comes from George Boole [ George_Boole ] who invented it in the 1800s.

        The word int is shorthand for integer -- the mathematician's name for a whole(integral) number.

        Are there other types we will learn about in class.

        Yes: char, short, long, string, ..., arrays, vectors, ... enumerations, ...

        plus the Do-It_Yourself data types: structs and classes.

        When is bool used

        The main use of the reserved word bool in C++ is to introduce variables that have two possible values: true and false. Absolutely typical is setting a flag to note something that has happened:
         		bool end_of_file_flag =false;
         		...
         			end_of_file_flag= (cin >> variable);

        Why does not have a different priority to and and or

        (1) not is a prefix operator. The other two are infix operators.

        (2) The is a long long tradition of having not act on the following simple condition rather than a group:

         		not today and tomorrow
        means:
         		(not (today)) and tomorrow
        not:
         		not (today and tomorrow)

        What does bool actually do

        It reserves a piece of storage that can hold one of two values.

        Is a while statement a kind of loop

        Yes.

        Is a while statement the same concept as a loop

        No -- some loops are not while loops.

        I dont understand while statements.

        The will be covered in the next reading, lecture and lab. These should help.

      Glossary

      1. and::="the bool conjunction operator",
      2. (x and y) is true if and only if both x is true and y is true.
      3. bool::="a type of data with two values true and false and three operators, and, or, not".
      4. not::="the bool negation operator",
      5. (not x) is true if and only if x is false.
      6. or::="the bool disjunction operator",
      7. (x or y) is true if and only if either x is true or y is true.

      Exercises

      1. Complete the following truth tables:
        xyx and yx or y
        truetrue??
        truefalse??
        falsetrue??
        falsefalse??
      2. Trace the following program with several different input values: [ 05ex0.cpp ]

      Quiz 2 -- On project 1 and tracing programs

      Lab 03 -- Using UNIX Commands.

    Abreviations

  1. Gnu::="Gnu's Not Unix", a long running open source project that supplies a very popular C++ compiler.
  2. KDE::="Kommon Desktop Environment".
  3. TBA::="To Be Announced", something I should do.
  4. TBD::="To Be Done", something you have to do.
  5. UML::="Unified Modeling Language", [ uml.html ] (beginner's introduction to the UML).

End