[Skip Navigation] [CSUSB] / [CNS] / [Comp Sci & Eng Dept] / [R J Botting] / [Samples] / c++.FAQ
[Index] [Contents] [Source Text] [About] [Notation] [Copyright] [Comment/Contact] [Search ]
Fri Mar 21 07:41:01 PDT 2008


    FAQs on C++

      Why are you teaching Linux?

      Total cost of ownership, reliable networked systems, + hard core professionals use it.

      Why are you teaching C++?

      Used in many industries. After C++ other languages are easy! It is also leads to programs that execute quickly.

      It is like a tool box full of very sharp power tools. You need to know what you are doing but you get a lot of power and speed in return. C++ is very much the parent of most modern (web-based) languages.

      How is C++ used in Games?

      You need a good graphics and user interface library plus a "games engine" that understands the physics of objects. C++ acts as the glue connecting these components. The components are probably also written in C and/or C++.

      How do you develop a program?

      Very carefully!

      First: understand the problem. Second: work out how the user will use the program. Third: sort out the data needed. Fourth: design objects to store the data and do useful things. Fifth: write code for the objects, user, data, ....

      Why are you teaching UML?

      The only industrial diagramming language for software.

      How has computer programming changed through out the years?

      Here is my quick and personal list.
      1. 1800s Ada Lovelace programs Babbage's Analytical Engine.
        <1940s Programs were written for human computers to execute in English and mathematics.
      2. 1940s Programs written by changing the machine hardware (in secret).
      3. 1950s Instructions written as numbers and stored in memory.
      4. 1960s First programming languages mimic mathematical formula(FORTRAN, ALGOL) or managerial English(COBOL). Programs became complicated so we split them up into independent pieces called modules. Flowcharts used to design programs. Many local low level languages. Mainframes.
      5. 1970s Structured programming. Programs are designed using Pseudocode and diagrams and split into functions. Pascal. C. Unix. Minicomputers.
      6. 1980s Data Abstraction. We started to group functions around data and let other parts of the program only see those functions. Ada. The IBM PC.
      7. 1990s Objects. C++. Java. The Web.
      8. 2000s Modeling: diagrams of objects etc used to analyze problems and design solutions. Perl, Ruby, C#, Python

        How does a computer work

      9. Here is a model of a computer: A person sitting at a desk with a simple calculator. They read instructions in a book called the "program". They write down answers on a work pad(RAM) and also use them in future calculations. They have an in tray (input) were they get data, and an out tray where they put data (output).

        What is the function of the backslash character

        The backslash (\) character is use in C++ and many other languages to change the meaning of the following character in a string. The backslash and the following characters/number form an escape sequence. or to indicate an strange character that is illegal or untypable. Here is a short list of escape sequences.
        • \n Newline
        • \t Tab
        • \" Double quotation marks(")
        • \\ A real backslash
        • \007 Beep

        Can you explain more clearly how translate human-readable code to machine code.

        Not really -- it is rather complex. Take CSCI320 and CS570. Meanwhile
        1. Recognize the basic words and symbols in the code.
        2. Use the syntax to parse the symbols into a structure and reject syntax errors.
        3. Scan the stored structure and generate some machine code.
        4. Optimize the code (a dark art).
        5. Output the result.

        What translates mnemonic instructions into machine code?

        The assembler.

        Why is C++ faster

        It is compiled and so the code doesn't have to be parsed many times. It also lets the programmer get close to the machine.

        What are namespaces

        I C++ the names that programmers create are all placed in a namespace. This lets different programmers use the same name for different purposes, even in the same program. For example, most of the standard libraries place their names in "namespace std". SO the official name for the C++ Output stream is
        but the
         		using namespace std;
      10. statement makes it OK to omit the "std::".

        Are there any standards for C++

        Yes the is one international and American national standard C++. Any variations you meet are non-standard.

        Explain how a bug gets past the compiler

        A compile only checks to see if you've followed the grammar, the syntax of C++. It doesn't check to see if you've written down rubbish.

        Computability theory shows that it is impossible for a computer to diagnose all bugs that can happen.

        To quote a friend: "Nothing is foolproof, fools are too ingenious".

        Is HTML in use and is it like C++

        HTML is still in use. It is totally unlike C++ in its purpose, syntax, and meaning.

        What aren't all compilers the same

        (1) Economics (2) human error.

        Floating point notation

        Floating point is John Von Neumann's invention. It lets computers do arithmetic with "real numbers" easily. The basic circuits do calculations with whole numbers: integers. It takes special hardware or software to handle numbers that are not whole numbers.

        You know if you want to calculate "1.23 * 32.1" that you can calculate "123*321" and then place the decimal point in the answer. This is the idea behind floating point. We express numbers as a mantissa and an exponent. The exponent tells us where to put the point: 1.23 = 123E-2 and 32.1 = 321E-1, for example. The "E" indicates the "Exponent" and is short for using "10 to the power". Now if you do the math you will see that you multiply the mantissas and add the exponents to get the answer:

      11. 123E-2 * 321E-1 = 39483E-3 = 39.483

        In other words the point is allowed to float inside the number...

        Modern computers provide a form of floating point that uses Binary notation rather than decimal. It is easy to use (just forget it!), give approximate but good answers, and is slower than integer arithmetic.

        Most computers provide two different sizes of floating point number: normal and double length. Double length numbers take up twice the space and are slower.... but the give a more accurate answer.

        Choosing data types: int vs double vs string

        Use double for all measurements. Use int only for counting things. Only use 'float' for a measurement if you have a small (20th century) computer.

        Beware of dividing ints!

         		2 / 3
        is 0. If you don't want to do integer division -- you need doubles.

        For any kind of character handling (like -- "insert a comma") you need strings not ints or doubles.

        Why do we include iostream

         		#include <iostream>
        is needed for programs that do IO (Input and Output). It tells the computer how to connect C++ to the user's keyboard (cin) and display(cout).

        What are cin and cout

        Normally cin is the users input to the computer and cout is the place for out to the user.

        Can you create a program to prompt and read variables as it runs

         		#include <iostream>
         		using namespace std;
         		int main()
         			cout << "Prompt";
         			type variable;
         			cin >> variable;

        Explain range restrictions on numbers

        Most computer hardware gives a fixed amount of storage to each type of number (int has 16 bits, float 32 bits perhaps). Going outside the range (overflow) can produce bad results.

        You can get more storage for int by asking for long int in the program. You can also ask for long double rather than double.

        The old float data type is OK for fast calculations with larger errors.

        Can we do a number theoretic modulus in C++

         		n % m
        is the modulus of n mod m.

        Why do uninitialized numeric variables have random numbers

        The initial value is what ever has been left behind in the allocated memory by the previous program. This is unpredictable. The program will often work sometimes and produce incorrect answers else where.

        Initialize doubles and ints will loose points!

        Do I like shortcutting assignment and arithmetic

        Only in private. Avoid it in this class!

        What kind of comment do I like the // or the /*...*/

        I like both. Any comment is worth more than none. I'll equal credit for both. Please use both and discover the good and bad features.

        Is the underscore _ used as a space holder in identifiers


        What does a compiler turn C++ into

        A lot of numbers. By way of "assembler code".

        Are we going to get a list of C++ commands

        There are at least 100 basic types and you don't need them all. It is best to add them one at a time to your notes and "cheat sheet".

        If you really need to get a description of the options try [ ../samples/c++.syntax.html#Statements ]

        What are C Strings

        Before C++ existed with easy to use "strings" there was an older language (C) with primitive and dangerous "char-star" ( char* ) string. Briefly: each was an array of characters terminated by a null character.... and we will talk about arrays later in this class.

        What are strings for

        Strings are a common form of data: a number of characters in a row. You should use them for data that is not numeric: no addition or subtraction.

        Examples: names ("Horstmann"), SIDs("123-45-6789"), pieces of text ("The quick brown fox jumps over the lazy dog."), an so on.

        Why do we need a third string when we concatenate two words

        The expression
         		"Fred" + "Flintstone"
        with no space, unlike
         		"Fred" + " " + "Flintstone"
        that produces
         		"Fred Flintstone"

        What and why substrings

        Substrings are parts of strings.... We need them to slice and dice nonnumerical data. Typically people gives character data and we need to search it and extract the pieces that we want out of it.

        Example: given

         		int main()
        as input to a compiler we will need to extract and recognize the "main" in the line.

        When to use getline and >> with strings

        Use >> to read in words separated by spaces. For example given
         		123 ++ grandma
         		cin >> a >> b >> c;
        would put "123" in a, "++" in b, and "grandma" in c. But
         		getline(cin, s)
        puts the whole line "123 ++ grandma" into s.

        So, use getline when you want to parse the user's input yourself.

        Can C++ do other Math functions than the elementary ones in cmath

        I can't find any ones in the standard C++ library [ lib-numerics.html ] except the ones that Horstmann lists on page 59.

        I did a search on the web and found Matpack [ matpack_frame.html ] (free), and there is also MatLab and the NAG(Numeric Algorithms Group) library.

        For other functions you can use a reliable reference like [AbramowitzStegun6465] (in the CSUSB library and my office).

        My program rejects every string function and operation

        at the start of your program.

        What happens if you don't give enough room in formatted output

        You probably get some asterisks or a wrong answer.... why not try it in a simple program?

        How is input and output used in a program

        Input occurs when the user types some data and it's value is placed in a variable inside a program. Typically done early in a program to get ready to compute other values that are output to the user.

        What is int cents = value % 100;

        The "%" operate calculates remainders (moduli). If value is an integer that holds a large number of cents -- say 12345 cents, then it is 123 dollars and 45 cents. If you divide by 100
        you will get the number of dollars and if you computer the remainder
         		12345 % 100
        you get 45 -- the number of cents.

        Can C++ do equations or algebra or calculus


        There are expensive software tools that can help solve equations, do algebra, and do much of the calculus. Example: Mathematica. These may have been programmed in C++.

        Can computers do infinity

        No -- well not very well and usually only by accident.

        However -- the standard floating notation developed by IEEE and adopted on most computers has a value that prints as "inf" for the result of calculations that should have produced infinite answers.

        When to use '

        Only when there is a single character in the quotes: '(' and you don't need to do any string operations on it.

        We will return to characters later.

        Explain the dot notation

        Some functions are only defined if they are applied to an object. They are called methods. They are used like this:
         		object . function_name ( arguments )
        Examples include "length" and "substr" that operate on strings.
         		myName . length ( )
         		myName . substr (start, length )

        We will meet many more example next week...

        Why isn't Microsoft C++ the same as the standard


        What is the most efficient way to program the tic-tac-toe display

        Horstmann's "comb" technique is rather neat. I would define and use
         		const string comb="+--+---+--+\n|  |  |  |\n";
        for example.

        What is the most efficient way to program a tic-tac-toe program

        The hard parts are (1) teaching the computer what the rules are, and (2) teaching it how to win. A simple idea: list every possible position and tabulate the best move for it.... but this needs a "vector" to hold a large number of positions and moves. We'll do vectors later in this class.

        You have to do a lot of analysis and design to do this project well.

        What is the difference between a class and an object

        A class is a collection of many similar objects. In mathematical terms, a class is a set of objects. Thus "Fido" is an object and "Dog" is "Fido"'class.

        When we say that foo "is a" foobar we imply that foo is the object and foobar is its class.

        Does it matter: YES. Bugs and wasted time is the lot of those who confuse sets with elements.

        In a program an object is a little bit of memory reserved for a special purpose. The class has little memory of its own and defines what the purpose of its objects are: Time, Employee, Point, ...

        Can I construct one object inside another

        Yes.... but the class has to define how it works.

        Explain #define

        This is a compiler directive. Suppose you have
         		#define answer 42
        in a program then the compiler remembers that "answer" means "42" and deleted the line.... but when ever it sees a line with "answer" it replaces it by "42". So,
         		cout << answer+1<<endl;
        is replaced by
         		cout <<42+1<<endl;
        before the the rest of the compilation takes over.

        What are boundary test cases

        A boundary test case is some input data that produces output that will change a lot if we made a small change in the input data. It is a test to see if a program can handle such changes.

        What is a WAN

        WAN is an acronym for any largish network. A small network is a LAN. The largest network is a network of connected networks called the Internet.

        Can you ++ a double

        You can ++ a int or a double variable, but not a constant: [ ../cs201/doubleplusplus.cpp ]

        What is return 0;

        A return statement computes a value and terminates a function leaving the value behind.

        C++ programs execute the main function until they hit their return statement. That is when they stop. And they leave the zero as a signal to the operating system that zero errors occurred.

        Can C++ calculate derivatives and antiderivative.

        Not easily. You would have to teach C++ how to store and manipulate formulas and then all the rules of the calculus. It is easy in Maple and Mathematica to differentiate functions. In languages like Prolog and LISP it is not to difficult to code the rules of differentiation.

        Oddly antiderivatives are difficult for human (intelligent) mathematicians. I don't think there is an algorithm and with no algorithm you can't write a program.

        How does a member function differ from a nonmember function

        1. member functions are a part of a class, other functions are not.
        2. member functions must be applied to an object like this
           		lengthOfStr = str.length();
        3. other functions mustn't be applied to object.

        Is animation possible in C++

        Yes... but you need (1) a better graphic library like "Open GL" and knowledge of the calculus (up to multidimensional) and physics.

        What is the difference between = and ==

        This statement
         		variable = expression ;
        changes the value of the variable so that it is the current value of the expression.

        This expression

         		expression1 == expression2
        is a test to see if the two expressions have the same value at this time. It is often used in ifs and whiles.

        Explain the selection operator

        This is the only operator in C++ that has three arguments. It is also the only use of a question mark ('?') in C++.

        The expression

         		test ? expression1 : expression2
        is a neat way to for a program to select on of two expressions to evaluate. However you probably won't need it in CSci201.

        A common purpose is to express mathematical function that are do different things in different ranges. For example a function that was 0 when x is less than or equal to 0 and 1 otherwise (the Heaviside function) is written

         		(x<=0 ? 0 : 1)
        These functions tend turn up in applied mathematics and physics rather than pure math. For example when I was working on the stresses in a large steel reaction vessel for a chemical company I modeled it as a cylinder with a spherical cap. The (?:) operator let me describe this simply.

        Explain input validation

        The data that comes into a computer (input) is often in the wrong format, missing, or illogical. Input validation makes sure that such bad data is rejected rather than being mis-processed.

        It is possible to write programs that ask the user to correct invalid data. They tend to be complicated. It takes time to plan them correctly and some advanced programming to handle them well. An example is: what happens if you forget your password.

        Explain if vs if/else

        The if allows a program to choose between doing nothing or doing something:
         		if(sender == "dick@csci.csusb.edu")
         		   return 1;

        The if/else lets the program choose between two different sets of operations -- an either-this-or-that choice:

         		if(sender.is_local() )

        To choose the right one for a program, you have to work out, in detail, how you plan to solve the problem. Use pseudo-code or a diagram to do this. Then you can see where you have an optional behavior(if) and where you need a choice of two actions (if/else).

        Why line up braces and indent statements

        (1) You will not forget any.

        (2) You won't get lost in your code.

        (3) You will look good to other programmers (and bosses).

        When can I leave out the braces in an if or if/else

        Precisely when the program has a choice of executing exactly ONE(1) statement in one of the branches.

        The braces turn a sequence of statements into a single statement. if and else control ONE (1) statement only.

        The following do precisely the same thing:

         		   cout <<"x is negative\n";
         		   cout <<"x is negative\n";
        The first is shorter and easier to type. The second is easier to change if we need to add a statement inside the if.

        What is the difference between return 0; and return 1; in a main function

        The first sends a 0 to the operating system. UNIX treats this as a signal of success: Zero errors.

        The other sends a 1 and UNIX treats this as a signal of something having failed.

        When should I #include the string library.

        First it does no harm (the program gets a bit bigger when compiled).

        Second, it is not needed if you don't do any of the operations defined in it: substr, length, concatenation.

        Third, if you include it now, you won't have to in the future when the program gets more complex.

        Fourth: Many people start coding by copying a file that has3 or 4 #includes and that "using namespace..." and "int main()"... and their name in a comment just so they can get to the meat of the problem quicker.

        Can I put an if/else inside an if/else? Should I use braces

        Yes you can (and will). I use braces when ever it gets complicated.

        What are loops for

        Loops tell the computer to repeat the same computation many times. They are used to process repetitive data in files, produce interesting patterns in graphics, carry out iterative algorithms, and wait until something happens.... and much more.

        How do you avoid infinite loops

        First, never write a loop that looks like this
         		while ( ____ == ______ )
        since the values of the two expressions can jump all over the place and never become equal.

        Second, by being careful. In other words you choose a terminating condition that you can guarantee will become true some time. For example if the loop starts while(x<10) then x should increase each time the body of the loop is executed. If it is while(x>=17) then x should get smaller in each cycle.

        A sound discipline (but not easy) is to calculate how often each loop will repeat its body as a function of the arguments. This leads to the discipline of the analysis of algorithms that is in the core of computer science.

        Now some loops do not follow these two guidelines and yet they still always stop after a finite number of steps. These are subtle loops and need careful design, testing, and checking. You need to use loop invariants.

        What are loop invariants

        A loop invariant is any boolean expression or fact that remains true as the loop runs. It should start true, and it won't change, so it ends up still being true, however many times we repeat the loop.

        For example in the following loop

      12. s = Σ [ i=1..n ] ( i*i ) is always true:
         	s=0; n=0;
          while (n<100){
         		s=s+n*n;  n=n+1;
        So at the end when n==100:
      13. s = Σ [ i=1..100 ] ( i*i )

        This is a complex topic that needs some high powered logic to really understand. I cover them in CSci556 (senior level formal methods).

        If I have an infinite loop how can I terminate the program

        In Windows call up the task manager, find the process and click "End Task" with your fingers crossed.

        In Unix, hold down the Control key and tap the letter C key. In rare cases an expert can use the Unix kill command to terminate a program.

        If a program is running on a workstation with nobody there, for a long time.... push the on/off button on the CPU. Reboots are emergency operations but sometimes it is the only way to stop a maliciously breeding program.

        What is a sentinel value

        A sentinel value is a special input value that is found after the real data has been read or processed. It signals that the data is complete.

        How do you test for input failure or end of file

        is a good test. You can also test
         		cin >> blah
        as it is executed and inputs data:
         			cout << sqrt(number) << endl;

        What is a Boolean variable

        A Boolean variable is declared to have type bool:
         		bool variable;
         		bool variable=true;
         		bool variable=false;
        To some extent, bool behaves as if it was declared like this:
         		typedef enum {false, true} bool;
        with three special operations: and, or, not.

        So a Boolean variable is a named piece of memory that is used to remember the truth or falsity of something. A Boolean variable only needs a single bit of data (one Binary digIT). Floats, ints, and doubles need a lot more space. Doubles are always approximations.

        Use one any time your program needs to remember if something is true later in the computation.

        Boolean Joke -- Do you have tea or coffee for breakfast?


        Booleans and loop-and-a-half

        In a loop-and-a-half problem we have to repeat a sequence until some event happens inside the loop. The test is outside the loop -- we need to know if the event happened somewhere else. Booleans are about remembering events for the future.

        Here is the loop-and-a-half pattern.

         		bool event_happened = false;
         		while( not event_happened )
         				event_happened = (test for event here);

        Can you give an example of a function with multiple parameters

        Here is a function that calculates the length of the hypotenuse of a right triangle given the base and height: [ ../cs201/09multi.cpp ]

        What is the relationship between a function and a parameter?

        There are several relationships.

        First, a function is declared with formal parameters. These are (normally) local variables. They get their initial value when the function is called.

        Second, when a function is called it is given some expressions as actual parameters. These are (normally) evaluated and the values are given to the function.

        Note: the exception is parameters "passed by reference" which we will discuss later.

        Notice that each actual parameter must match the corresponding formal parameter. If it doesn't one of two things happen:

        • The compiler gives you an error message.
        • The compiler inserts casts to force the actual values to fit the formal parameters.

        What is a predicate and how do we use it.

        A predicate is any function that returns a Boolean value.

        You use it to test the truth and falsity of properties you are interested in as the program runs.

        You use predicates in conditions mainly: if(....) and while(....). For example

         		if( near(x,y) ) ...
         		while ( odd(n) ) ...
        Notice the nested parentheses. One pair for if/while and one for the call.

        In some groups of programmers there is a tradition of adding a 'p' to predicates... and indeed this conventions tends to include conversation like:

        to ask questions.

        What is a side effect?

        A side effect occurs when a function changes something out side the function. For example:
         		int glob=0; //evil global variable
         		int f()
         		   glob=glob+1;  //sneaky change to global variable
        Here calling
        changes glob.

        Note: invisible side-effects on global variable are not a good idea.

        Why are side-effects a bad idea


        Plus: there are better ways of getting what you usually need -- classes.

        How do functions help you write big programs?

        First: when you plan what functions to use, you develop an organization for the code. You divide it into a number of separate sub-problems. And as in ancient times, "divide and conquer" is a good strategy.

        Secondly, you write the functions once and call them several times. This makes the program smaller, any way.

        When should you put a function before the main function?

        Nearly always.

        One exception is when you declare the function header before the main program

         		void fun(int argument);
        (notice the semicolon!) and define it later
         		void fun(int argument){ .....}
        (NO semicolon, but has braces...)

        The other exception is when the function is in a separate file and you "#include" it in the program, but here again you must do this before calling the function.

        Why should you put a function before calling it?

        The compiler doesn't know what to make of the call unless it has been told the name of the function and how many arguments it has.

        Why do we put comments before functions?

        To help people understand what the function does. They read the comments and skip the complications.

        It doesn't take long before we forget what a function is supposed to do, so the person we help, is often ourself.

        When we have a return in a function do we still need one in main?

        Yes. Each function should have its own return value and so needs at least one "return" statement.... including "main".

        Exception: procedures with nothing returned (void).... don't need a return.

        How do we modify the values of parameters inside functions?

        You can do this but it has no effect on the actual argument unless you use "pass by reference".

        What is the easiest way to say "A or B" in a condition?

         		(A) or (B)

        Will we use any other #includes


        Can we put an #include later in a program

        Included files are designed to work if they come first in a program because they define functions.

        Bad things can sometimes happen if you do it later in the code.

        Can I use C++ to create programs that I can sell?

        Ask Bill Gates and Paul thingie..... Microsoft makes lots of money selling C++ programs.

        But get a lawyer before getting into serious business. You can get badly hurt.

        Explain more about the condition in a while statement.

        The condition is tested and the loop body is entered if the result is true. The condition can be as complicated as you like.

        Which is the compile command "g++... " or "./...."

        The compile command starts "g++" because it calls the compiler called "g++". The "g" is for "Gnu" and "++" from "C++".

        Is a class a holder for a bunch of functions?

        Yes. It is not a function but a collection of functions.

        A class also lists the data to be found in all its objects. So it is also a holder for a bunch of variables.

        A class also has a number of objects (initially none) because it defines how to construct new objects.

        How do you modify or change the value of a private data field?

        A private data field can not be changed from outside the class. You have to call a member function of the class that changes it. These functions are called mutator functions.

        What is the purpose for declaring an accessor function with const?

        This tells the compiler to make sure that you don't accidentally create a mutator that changes the data in the class. The const is short for constant, and the data fields are forced to be constant when the function is called.

        When an accessor is called the data fields in the object are retained. And the const enforces this!

        Do you have to define functions before classes?

        NO. You can declare non member functions like main anywhere. You can only define a member function after they are declared in the class.

        So typically classes come first and then functions.

        How does encapsulation work?

        The compiler won't let you do anything to an object that is not declared to be public in its class. This puts a "capsule" around the contents of the object.

        What is an interface?

        An interface is a list of functions that you can use -- public member functions.

        An example: Watch interface
        get_time()Timeno change
        start()nonestarts the stop watch
        stop()nonestops the watch
        get_timer()intreturns number of seconds since starting the stop watch...
        set_time(t:Time)nonethe watches time is set to t

        What is the difference between implicit parameters?

        When you call a member function you apply it to an object and can also pass some data to it:
         		object . function ( data );
         		summer . add ( data );
        The data is called the explicit parameter(s). The object is called the implicit parameter.

        When we define a function, we don't mention the implicit parameter. The word implicit means we don't mention it.

        For example the function below adds numbers to the total of a particular object but doesn't say which:

         	Summer::add(int data)
         		total = total + date;
        The total is always the total that is in the object mentioned in the call:

        How does a class differ from a function?

        A class contains functions.... But is not a function.

        You can call a function. You can not call a class.

        A class constructs objects. Most functions do things to existing objects.

        A function can return a value. Classes have no value to return. They define a new type of value that you can use.

        When are global variables used in C++?

        When you don't know any better!

        When a group of functions share some data then you need a class to hold both the data and the functions.

        Explain getline and >>

        Use getline to get a complete line of data from the user... ending when the tap the "Enter" key.

        Use ">>" only when you know what type of data comes next. Use getline when you can't predict the type of the input data. the getline function returns a string and you can then explore the string and figure out what is in it.

        What do two colons do?

        The two colons are used in C++ to relate a name to the class or namespace in which it is a member. A function like
                 void C::F(...)...
        is member of a class named C. It's own name is F. It is rather like they way we (mostly) have a family name and a personal name -- call me

        What are the differences between && || and or?

        In C++ "&&" is the same as "and". They are both operators used in writing conditions: A and B (A && B) is true precisely when both A and B have the value true. It is false otherwise. Similarly, "||" means the same thing as "or" and these are also used in writing conditions. However A or B (A || B) is true if either A or B has the value true. It is false only when both A and B are false.

        What do default constructors do for you?

        When a class has a default constructor it means you can create new objects with out worrying about any parameters -- the default constructor will define a suitable object for you. You don't have to have a default constructor and it can be anywhere in a class description. How ever they are useful whenever you know what a typical object looks like.

        How do special constructors differ from the default constructor?

        They have parameters. C++ matches each declaration and construction by using the type of the parameters. It searches all of them looking for the right number and right types.

        Can you have a class with no constructors?

        You can write a class without any constructors, but the C++ compiler will then add a default constructor that does nothing:
        To stop strangers from constructing objects you make all the constructors private. This is an advanced technique and needs more experience and knowledge than we have time for in CSci201.

        What are mutators for?

        The are used to change the data values in an object. They are chosen to reflect real life changes in the real world. Mutators change the internal state of the object.

        Why can't I use a constructor to mutate an object?

        Making a new object is different to changing an existing one. So I guess that the C++ designers decided that someone this confused should be stopped...

        How do you indicate whether the implicit parameter is passed by reference or value?

        It is always passed by reference! There is no choice here.

        Why do some of the book's classes have two constructors and others only one?

        Why not?

        You should have the right number of constructors for the job the class has to do. No more and no less.

        How do I get the right number of constructors.

        With some experience you will be able to get this right by thinking about the different ways that an object might need to be created.

        If in doubt do the absolute minimum for the program in hand and add new ones when needed.

        Are overloaded functions important?

        Overloaded functions (member and non-member) are important. You can not avoid using them. And you will need to create new ones as well. The C++ compiler matches function calls with function definitions. It does this by looking at the name (easy) and also by looking for a function that needs the data you have given it.

        Do you have to use I in a loop?

        No. You can use any variable name you like as a counting variable. The traditional names are: i,j,k,l,m,n.

        Can there be more than one constructor in a class?

        Yes. They must have different types and numbers of parameters. They are overloaded.

        Is programming an art or a science?

        Yes. We can teach the science part.... but the art is something you will have to develop for yourself.

        Must an accessor be a member function?

        Yes. The purpose of an accessor is to access private data. Only functions that are members of a class can do this.

        What is a CASE tool?

      14. CASE::="Computer Added Software Engineering", by analogy with "CAD" Computer Aided Design, a tool that helps you develop higher quality software typically by putting a graphic front end on the way to code.

        What is the difference between implicit and explicit parameter?

        Explicit parameters are written in parentheses after the function name. The implicit parameter appears before the "dot" in a function call but is not mentioned inside the function definition -- it is implicit. Operations on the data members are done to the parts of the object that appears before the dot in the calls:
         		implicit . function_name( explicit );
        and hidden in the body of the function:
         		Type data;
         		Type function_name( formal_explicit_parameter)
         		{ // a ref to `data` turns into `implicit.data` from the call

        Can you define an object variable that is not initialized by a constructor?

        This is simple (and dumb) (1) forget to define a default constructor in the class.

        (2) declare the object variable with no parameters:

         	class_name object_variable;

        Hey presto! You've got an object full of garbage data. And:

      15. GIGO::="Garbage in, Garbage Out".

        Why are member function important to classes?

        Object are used via their class's member functions. No functions, no use. So you get a useless class.

        Functions provide limited and controlled access to data. UML class box relate to the code?">

        How does the layout of the UML class box relate to the code?

        It doesn't. The UML puts the data first, in C++ you can put it last. Similarly the UML has the functions at the bottom, in C++ they can be anywhere.

        The UML uses position to signal the difference between operations and attributes. C++ uses special syntax. UML diagram when should you do them?">

        There is a lot of info needed for an UML diagram when should you do them?

        Start simple and add information as needed.

        Don't put all the details at first. Grow the diagrams and compartments: name, then add some data, then add some functions, ....

        First use UML as a rough sketch, then work out the detail and code them. Then do a nice tidy UML diagram to summarize what you've done when you present your work to others.

        What is the purpose of the ampersand in a function header?

        It means that the parameter in the call MUST be a variable. It also means that what ever is done to the formal parameter inside the function, actually is done to the variable that was the actual parameter.

        Why does revealing less information give more flexibility to improve a class?

        When information about the inside of a class is not revealed, then people can't rely on what you did when they use your class. So you can safely change what you wrote without breaking their code.

        Why do we have both member and non-member functions?

        C++ inherits "naked" functions from C, and it is too late to change that.

        Also sometimes you have need for a simple function and do not need the hassle of putting a class around it and declaring objects to get access to ONE LITTLE FUNCTION....(sorry to shout... I feel better now).

        What is overloading a function?

        A function is overloaded when the same name has different types of arguments. The compiler will pick the definition that fits the data types in the call of the function.

        Do most programming jobs require understanding the UML?

        It will help..... and a lot of job adverts mention it.

        Can you have a function called 1 or 2?


        Are there any programming languages that can be used to process themselves?

        Yes. C++ is one of them. Our 'g++'/'c++' compiler is written in C++.

        Will there be any use for computer programmers now that programs can write programs?

        Yes.... there is a definite future because computer programs are essentially rather stupid compared to a human being. It takes a human to figure out what the problems are and then to choose what needs to be programmed. A computer also has some definite limits (covered in the Upper Division Theory courses), and a smart human is needed to avoid the need to program these.

        Several times in the last 40 years somebody has produced a new language claimed that:
        LISPWe can now program an artificial intelligence.
        COBOLManagers can now write programs in English.
        TLOThis is The Last One you'll need.
        PrologYou can describe the problem in logic and Prolog finds the solutions.
        In every case, the claim turned out to be false.

        When do we use p and q in C++?

        These variables can be used for Boolean variables. The p stands for proposition and the q is the next letter in the alphabet.

        However it is better to use a name that means something, like


        Mostly they are used in teaching and learning Booleans, logic, and programming.

        Is a dangling else attached to the wrong if?


        How do you get complex logic right

        A couple of rules: (1) THINK, and (2) THINK.

        It helps to walk through complex cascades of if-else-if-else. It helps if you draw diagrams of complex logic. Flowcharts and "digraphs" can be a great help... especially combined with some logic.

        And it helps even more to show your thinking to other people you work with.

        Finally thorough testing is GOOD.

        Can you explain the difference between && and ||?

        It helps to practice with lots of Boolean expressions.

        But the fact is that most natural languages are not very good at distinguishing these to ideas. They did take more than 1800 years for them to appear in logic, mathematics, and philosophy.

        In real projects it is almost always a good idea to tabulate all the conditions and what needs to be done with them. Computer Scientists have developed many techniques, notations, and tools for this purpose and we cover them in several parts of the curriculum.

        What are the Boolean Operations used for?

        Expressing complex conditions.

        A complex Boolean expression can simplify a complex set of if-else statements. For example, for all conditions, P and Q, and statements A

        (with no elses) is simpler as
         	if( (P) and (Q) )
        (and often the ()s can be left out).

        Explain symmetric and asymmetric bounds in a loop

        A loop typically starts by allocating a value to a variable. In other words, the variables starts out equal to a value.

        The end of a loop can be specified in two common ways:

         		while( variable < bad_values )
         		while( variable <= last value)

        In the second case we end up with the variable equal to the bound. This is like it starting out equal to a lower bound. Horstmann therefore calls it: symmetric.

        For each loop ask: does it go on until a bad value must be stopped, or until the last good value.

        Again: THINK!

        Explain switch statements

        The switch statement can be used to simplify some complex pieces of logic. It is only helpful when you need to make a choice between more than two different cases, AND the choice is made by looking at an int, bool, of char (character).

        It doesn't work when the choice depends on doubles or strings.

        Other than that they are very simple:

         	   case Value:
        The Expression is evaluated and its Value found in the set of cases. The case selects a sequence of statements that ends with a break; statement. At the break; the computer jumps to the end of the switch and exits it.

        What is the difference between nested ifs and a sequence of if else if else?

        An if-statement divides the code into two pieces:
        Either part can have another if-statement inside it. When an if appears in the TruePart we say that it is a nested if.

        Nested ifs tend to be for complex and type conditions.

        We can also have an if inside the FalsePart. Often, the FalsePart is a single if-else

        Then we simplify the syntax to
         		else if(anotherCondition)

        This a common structure that appears when we have a series of either-or operations.

        How Can you define a variable that is not initialized in a constructor?

        By forgetting to put the code in the constructor.

        Can you initialize a data field when you declare it in a class and outside a constructor?


        How does if-else and switch differ?

        if-else is a 2-way choice but a switch can have any number of alternatives.

        The if-else tends to be less buggy.

        Why is lazy evaluation lazy and what does it mean?

        Lazy evaluation means that the program does not evaluate every part of an expression unless it has to. In particular we know that false and p is false for any value of p and so there is no point in testing p. Similarly with true or p.

        Lazy evaluation lets the program run quicker.

        It also allows an unsafe part of a condition to be ignored unless we know it is OK:

         		D>=0 and sqrt(D) < 3.0

        Explain pass by reference with classes

        A member function is defined and called with pass by value or pass by reference just like any other function.

        However, the implicit parameter is actually passed by reference.

        Why does Dr. Botting Hate the Do Loop?

        Because he has had lots of bugs when he has used it.

        How does the for loop differ from the while loop?

        A while statement has one part: the condition tested at the start of the loop plus the body:
         		while ( condition ) body

        A for statement has three parts: the initialization, the condition, and the increment, plus a body that is repeated.

         		for(initialization; condition; increment ) body.

        The for loop does the work of a more complex while:

         		{ initialization;
         		  while( condition )
        Since many loops do have the three parts of a for statement, it is worth using it rather than the more complex while.

        What is the difference between a "for" loop and a "do" loop?

        First a do loop always executes its body before testing its condition. A for loop tests the condition before it executes the body.

        A do loop has a condition and a body. A for loop has initialization, condition, increment, and body.

        Inside the body of any of the looping constructs while, do-while or for what does a break and continue command do?

        The break command jumps you out of the loop entirely.

        The continue command jumps you to the bottom of the loop and then lets it repeat (via testing the condition).

        Is there a limit to nested loops?


        Could you explain more about the nested loops?

        Sometimes we have a problem that contains the same problem many times inside it. This demands a loop. If the inner problem also contains another loop, you'll need a nested loop to handle it.

        One of the commonest forms is reading and writing tables.

         	A table has many rows.
         	A row has many items.

        So the code looks like

         	Process Table
         		Process Row in the Table
         			Process Item in Row
         		end loop
         	end loop

        An example: write a program to output a simple multiplication table. It has 12 rows numbered 1 to 12 and 12 columns numbered 1 to 12. The item in row r and column c has value r * c. Like this

           1   2   3   4   5   6   7   8   9  10  11  12
           2   4   6   8  10  12  14  16  18  20  22  24
           3   6   9  12  15  18  21  24  27  30  33  36
           4   8  12  16  20  24  28  32  36  40  44  48
           5  10  15  20  25  30  35  40  45  50  55  60
           6  12  18  24  30  36  42  48  54  60  66  72
           7  14  21  28  35  42  49  56  63  70  77  84
           8  16  24  32  40  48  56  64  72  80  88  96
           9  18  27  36  45  54  63  72  81  90  99 108
          10  20  30  40  50  60  70  80  90 100 110 120
          11  22  33  44  55  66  77  88  99 110 121 132
          12  24  36  48  60  72  84  96 108 120 132 144
        Here is the code [ ../cs201/mtable.cpp ]

        Now figure out what this [ ../cs201/mtable2.cpp ] program does.

        Can you explain the char ch; more clearly?

         		char ch;
        This creates a one byte piece of storage called "ch". You can store a single character in it. Single characters are not strings. They are found inside strings. A single character constant or literal is written

        In C and C++ chars are also numbers in the range 0..255. As a result you can do arithmetic on them. For example:

         			'a' + 2

        In consequence, we can go through the whole alphabet like this

         		for(char ch='a'; ch <='z'; ch++) ...

        What is De Morgan's Law?

        This is a law of logic published in the 1800's by Augustus De Morgan. It states that for all logical values p and q:
      16. not( p and q) == ( (not p) or (not q) )
      17. not( p or q) == ( (not p) and (not q) )

        You can prove this using truth tables. Try it!

        Is there any reason to seed the number generator more than once? If not, why make a function for it? Why not just add it to the beginning of main()?

        I completely agree.

        What are the commonest errors that happen in classes with member functions

        First there are all the errors with normal functions -- forgetting to specify the returned type, forgetting an '&' on a reference parameter, ... and so on.

        You have to be sure that functions have the right names and that the prototype/header matches its definition.

        With member functions you can access member data... and so these give rise to extra errors using up the wrong variable.

        What is an oracle

        An oracle is a program that is given test data (possibly random) and predicts the correct result. You can then run the real program and find out if it produces the same results. Notice that an oracle is often good enough for deployment as the real solution to the problem...

        In UNIX your test shell script might look like this

         		generate >test.data
         		oracle <test.data >correct.out
         		program <test.data >test.out
         		diff correct.out test.out
        Which lists the lines where the oracle has done something different to the program.

        How does a test harness work

        A test harness is just a normal main program the exercises the class/functions by calling them. It may out put results or use the assert function to test them.

        You have lots of code like this:

         		TestClass object;
         		assert(object.value() == correctvalue);
         		assert(object.value() == correctvalue2);

        When should I use arrays and when vectors?

        Use arrays only when you know the maximum number of items that can be in the array before you compile the program. Arrays have a fixed number of items. Vectors can grow and contract as items are pushed and popped.

        Use arrays when their size is pre-specified and you need the program to run very quickly or do a lot of calculation. Vectors are slower than arrays because they are dynamic.

        In the future you will meet an advanced technique that lets you delay fixing the size of an array until after the program has started. However, once the storage is allocated to this "dynamic array" it can not expand or contract. If more data is needed then you must get more storage, copy the data to it and change the address of the array. But now you have merely duplicated the effort of the people who programmed the "<vector>" library.

        In what kind of application would you use arrays

        When speed is important and the maximum amount of data known in advance. classic areas include

        Device drivers -- Low level functions driving hardware in an operating system.

        Numerical methods solving large mathematical problems.

        Embedded systems -- running inside military weapons and domestic appliances.

        What is an array index

        It is a number or int expression placed between "[" and "]" after the name of an array:
         		array_name [ index ]

        What are the bounds of an array

        These are the two fixed values that define the largest and smallest index that can be safely used. The low bound is always 0 in C/C++/Java. The upper bound, in C/C++, is determined when you declare the array. The upper bound is the index of the last element is one less than the size of the array.

        Declare array

         		type name [ size ];
        then the bounds are
      18. 0 .. size - 1

        What is a bound error

        This is a programmer's mistake of going outside the bounds. This is not detected by the compiler. Typically they suddenly make a program behave very badly -- segmentation faults, frozen computers, stupid output.... quite unexpectedly. They are the commonest way that hackers can break into systems.

      C++ Background

        What makes a computer translate its 0s and 1s into a language we can understand

        Programs. Luckily most of the input and output is translated by code that is in a special <iostream> library so we don't have to worry to much about how this happens in this course... it is all "High Energy Magic".

        How does a Control unit talk to other devices

        It use the computers "bus" -- a set of "wires" that connects all the parts of the CPU. Each "wire" can transmit a single bit {0,1} of information. The power of the CPU depends on how wide this "highway" is. We have had chips with 4 bit, 8 bit, 16bit, 32 bit, and 64 bit buses.

        What were the first computers used for

        Pretty much what computers are used for now: mathematical calculations and data processing. This was all in "batch mode". You provided the input and got the answers days or even weeks later.

        Then came real time and interactive applications running on minicomputers. With minicomputers the first computer-based communications systems started leading to the Internet and the Web.

        The invention of the chip we made it possible for computers to control things from toasters to battleships by way of automobiles.

        Why do we use g++ rather than gxx to compile things

        The people who wrote our compiler (the Gnu Project) chose the name 'g++'.

        Does MS Windows come with a C/C++ compiler

        No. But CSE CSUSB students can get a free copy of the MS integrated Development environment (IDE) -- Visual studio.

        Can you recommend a good free compiler for home use

        Try the Gnu compiler. But under MS operating systems expect your own C++/C programs to crash fairly often.

        In order to program something does it have to be in a language that the computer understands

        Pretty much. What matters is if you have software that translates your program into the language that the computer "understands". Further, the computer/compiler/software relies on you using the language correctly. It will not correct your errors and will carry out the most stupid instructions just the way you wrote them.

        Is C++ only code or do you need something else to make interactive programs that are more user friendly

        C++ does not define ways of doing complex graphical applications. However there are several libraries that let a C++ programmer do this kind of thing. In CS201 we will stick with the fundamental skills of programming rather than doing lots of specialized user interface libraries.

        Why is C++/C more efficient than Java

        Because Java is not executed by the real hardware, it is executed by an interpreter called the Java Virtual Machine. This slows the program down.

        Why is Java so easily converted between platforms

        Because Java is not executed by the real hardware, it is executed by an interpreter called the Java Virtual Machine. It is easy to move the JVM to a new platform.

        What is value of interpreting vs compiling

        Interpreted languages (smalltalk) are easier to program, but compiled languages produce faster running programs.

        Why was FORTRAN popular when COBOL had better data

        FORTRAN was (and is) popular with scientific programmers because it does precisely what they want: Formula Translation. Scientists don't need the complex data that COBOL is good at.

        What is the different between static and dynamic linking

        Static linking is done before the program is run. Typically the library functions etc. are inserted in the executable by a link loader. Dynamic loaded modules are added to the program after it starts running as and when they are needed.

        Static linking is simpler and safer but not as flexible or efficient.

        What is an object oriented program

        This is a program built bottom up from "object" -- little pieces of data and encapsulated knowledge that work together to produce the effect that the user prefers.

      . . . . . . . . . ( end of section FAQs on Chapter 1) <<Contents | End>>

      Questions on Variables and simple programs

        How can I remember all the special words and rules

        Have the book open when you write code. Repeatedly using the rules and words will make them stick.

        Write them down. Many teachers will allow a single "Cheat sheet" in Quizzes and Exams.

        Who figured out how to write expressions

        Jim Backus in FORTRAN I...... which lead to the Algols,....B,...C,...C++.

        Who figures out what to write in expressions


        What is the precedence for operators in C++

        It is close to "Please Excuse My Dear Aunt Sally" or the British "BODMAS" mnemonic.
        1. Parentheses (and Brackets)
        2. Multiply and Divide (left to right)
        3. Add and subtract (left to right)

        Do the precedences of C++ operators change in a program


        Are there any confusing expressions

        Warning: look out for "^" it is not exponentiation.

        Warning: Look out for expressions like

        because the computer sees two integers (2) and (3) and so does integer division giving the answer
        To get "two-thirds" you need to force the compile to use double length calculations like this


         		17 % 5
        is valid and gives the remainder when 17 is divided by 5 == 2.

        What are real numbers

        Numbers that can have any number of digits before and after the decimal point.

        Talk to the math department!

        Can you have a double constant and how do you do it

         		const double NAME = value;
        Example -- mathematical pi π
         		const double PI = 4*atan(1);

        Note -- you can have constants of any type you want. When ever you learn about a new type you'll find you can construct constants for that type of object.

        Does C++ have single length variables like BASIC

        Yes. They are called 'float' variables and declared like this
         		float x;
         		float CONST = value;

        What do double and const double do

        These reserve space for a double-length number -- ready to do calculations. Good for holding measurements. Vital when you want to do work with fractions. They also give the space a name.

        How do you use double in a program

        It's used to declare variables that hold measurements and fractions:
         		double name;
         		double name=initial value;

        You should always declare a variable before you use it.

        Is writing the declaration first like backwards

        Possibly -- but it is needed for the compiler to know what each symbol means the first time it sees it.

        Is there a limit to the number of variable you can have


        What is the int main()

        In some books (and my old examples) the main function is always written like this:
         		int main()
        rather than
        Both are OK. The first is very precise. The second use a rule that, by default, functions return 'int's.

        Why is the final return not required by the standard

        Because if you had to have it then thousands of C and old C++ programs would by non-standard and not compile. The standards people (and most compilers) left a loop hole.

        Why aren't complicated math functions included automatically

        They take up time to compile and make the compiled program bigger.

        When C++ was C it was used mainly for "system programming" and there was no need for most program to do complex math.

        This is even more true about non-elementary functions that can be found on the Internet... but are not part of the standard. Most programs don't need them.

        How is input entered

        The program starts to run and stops. The user types in the input data and taps the "Enter" or "Return" key. The program takes what the user typed and makes it fit (if possible) what is in the cin statement.

        Can you solve math problems in C++

        C++ is very good at things that can be expressed as arithmetic. You have to do any algebra or thinking however...

        You can solve any solvable problem in C++.

        One of the big discoveries made in the beginning of computer science was the discovery that some problems can not be solved by a computer. These are called unsolvable problems and Turing was able to show that no computer would be able to solve them. This is a fascinating and tricky topic that is covered in the CSci500 level theory classes.

        What we can say is that if any machine can do it then C++ can program it.

        Can we make the the input and output look nice like Visual Basic

        Yes -- if you get a copy and #include the right library.

        On the other hand it is very easy to do once you've got the library. For example both our KDE Linux and MS Windows have nice user interfaces that let you draw forms and generate code for them.

        I didnt fully understand ++ and --

        (1) It is a subtle bit of C++.

        C++ lets you put ++ and -- operations inside expressions. They always add (subtract) one from a variable, but they also return a value. Suppose we have
        Then after

         		k = ++ i;
        we have

        If we again start with
        Then after

         		k = i ++;
        we have

        Summary of the rules
        ExpressionEffect on iReturned value
        i+1Noneold i + 1
        i++add 1 to iold i
        ++iadd 1 to iold i + 1

        Why is tracing a program helpful

        No other method gives you an understanding of what the computer is going to do.

        Once you have traced a program you can usually figure out what was going on.

        What does cout mean

        This variable is pronounced "C out" and it means: the place where C output is sent.

        What is a literal

        This is a value like 123, 1.23, or "Hello, World". It is a symbolic constant that represents itself. Numerical literals are normally typed using decimal notation (but C++ also does octal and hex if you need it). Strings like "Hello, World" as (currently) stored as a sequence of ASCII characters.

        Is C++ used in Graphics, Games, Special Effects, Movies


        However in Movies the C++ will be hidden inside an interface for movie makers to use.

        What does -= mean

        This is the "subtract from" operator. It one of a series of operators:
        Short formLong form
        x -= e;x = x - e;
        x += e;x = x + e;
        x *= e;x = x * e;
        x /= e;x = x / e;

      Questions on ifs

        When do I use if statements

        Any time that you need to make a program choose between two (or more) alternative sequences of actions.

        You should expect to be using if in every program you write.

        Can you use if statements for things other than sales

        YES. We discussed calculations of date, pressures in vessels, tax rules, .... etc etc .

        The example discounts in the book are wrong

        Quite possibly.

        Is there a limit on the number of if statements in a program

        No. You can use as many as you need to make it work the way it should work.

        Do you terminate an if with something like an ENDIF

        No. An if-else ends at the end of the statement after the else ... which may be a sequence inside {braces}.

        This is historical and saves typing.

        What syntax is used to construct if-statements

        See above. What separates two independent if statements Nothing. For example

        If you have a } do you need a semicolon

        Semicolons (;) in C++ are used to terminate expressions:
         		x = e;
         		cin >> x...;
         		cout << e ....;
        So sometimes that will be appear before a brace, but not always. Statements can also end with braces and so you can see things like this
        Sometimes I've even done this
         	}  }  }

        What does nesting mean

        Here is the example from class
         	if( day == THU )
         	   if( time == 12 )
         	      class = 201;
         	   else if( time == 12 )
         	      class = 375;
         	      class = 0;

        Isn't it not simpler to always use braces

        YES. But when i a hurray, in class, or short of space I often just forget them. Just like this: Here is the example from class
         	if( day == THU )
         	   if( time == 12 )
         	      class = 201;
         	   else if( time == 12 )
         	      class = 375;
         	      class = 0;

        Can you avoid complex nesting

        Sometimes by writing complex conditions. See below.

        Can I chain conditions together like I do in VBasic

        1. Can make this shorter by starting off with an example.

        2. Example: If you spend more then $100, bought exactly 5 items, and it was
        3. on the weekend. Only then would you win the super prize.

        4. Would a nested If inside a nested If be the only way to chain these 3 If's
        5. together? Or is it possible to somehow link them together in the first If
        6. statement like you can with AND in Visual Basic?

        YES you can chain these together, probably like this
      1. amount > 100 and number == 5 and (day == SATURDAY or day==SUNDAY).

      Questions on logic

        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.

        Professional tend to be more careful with "using namespace" and only use shorthand for parts of libraries that they need.

        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
        using the <<cmath>> library. The mathematical exponential function e to the x can be written
        using the same 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 or set up a constant
         		const double PI = 4*atan(1);

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


        It comes from the precedence rules that make 'and' have a higher precedence than '==' so that "x and y == 0" means

         		(x and y) == 0

        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 realize it is the opposite of what you wanted. The you put "not("...")" around it.

        How many different comparison operators are in C++


        How many different logical operators are in C++

        3: not, and, or. See below.
        pnot p
        pqp and qp or q

        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

        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
         		(not (today)) and tomorrow
         		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


        Is a while statement the same concept as a loop

        No -- some loops are not while loops.


        Why are break statements so bad

        They have been implicated in causing disasters. The break has two distinct meanings and some people for get this and produce code that does not work properly.

        Secondly, break skips over statements to get to the end of the loop and this is easily forgotten.

        The fact is you can program anything with if and while. So rather than code like this

         		if( B )
        You can, instead use a bool flag.
         	bool ok = true;
         		if( B )
         		if( ok )
        I'll be happy if you don't use break in projects. I'll only penalize you if it goes wrong! It won't appear in quizzes, finals, or labs.

        Can you explain for loops

        For loops are compact way of writing counting and scanning loops.
         	for(A; B; C) {D;}
        is shorter than
         	{ A; while(B){ D; C; } }
        and does the same thing.

        Should you use while or for

        Use for for counting and scanning. Use while for all other iterations.

        Most for-loops look like one of these

         		for ( i=0; i < ...; i++)
         		for ( i=1; i <= ...; i++)
         		for ( i=...; i >=0; i--)

        How many Layers deep have you gone in nesting while statements

        I'm not sure.... I've written for-loops at least 3 and possible 4 deep. I've never worried about it.

        How does an if differ from a while

        An if selects one of two alternatives. A while repeats a sequence until a condition become false.

        What does fabs mean

        It means "Floating-point Absolute Value". It does something like this
         		if( x < 0 )

        What is your opinion on using the Microsoft Visual C++ expression editor

        I've found the "Visual" environments (except the original VB) to need a lot of setting up -- I've usual given up.

        Are loops the same as while statements

        No. There are two kinds of loop (for and do-while) that are not 'while' statements.

        Is Linux/Unix an OS just for programmers or can average users use it

        I think that Linux KDE is better than Vista!

        But it is striking that Apple Macintoshes come with a version of Unix and the users a smugly happy with it: "It just works".

        On a lighter note.... here is a fun video on the topic [ videoplay?docid=-5847227571896228342&q=linux+windows+macintosh&total=802&start=0&num=10&so=0&type=search&plindex=2 ]

        Is there a limit to repetitions in a for loop


        Is there a limit to repetitions in a while loop


        Which is safest for or while

        They are equally safe to use. And both need care.

        Can you just use an if and something instead of a while

        Yes. You can use the "g*t*" statement -- now considered to be a rude word! Or you use recursion (later in the course).

        Luckily -- we have a simple while!


        What is tracing and how is it used

        Tracing is a process of seeing what the computer does when a program runs. It shows every value if every variable at each step of a program. The best way to do this by hand is in a table with variables as the heading.

        Tracing is used as the first step to understanding a program.

        It is also a useful training technique and diagnostic test of how well you understand something.

        We traced a piece of code like this in class:

         	int t = 0;
         	for (int i=0; i < 5; i++)
         		t = t + i;
         		cout << t << endl;

        What is a for statement for

        To count and to scan across containers.

        What is another way to work with loops

        I only know of the ways I have taught you.

        Is there a way to do both for and while statements without getting confused


        What does ! mean


        if statements and iomanip

        You don't need any libraries to use if.

        Difference between float and double

        Both store real numbers. Float uses less space and may run faster. Doubles have more significant figures.

        How are arrays and vectors helpful

        Doing without them is painful in the extreme -- believe me!

        Why can't we use vectors instead of arrays

        Their are only two reasons for using arrays: (1) they are efficient (faster, less wasted space) and (2) you have to fit with software that uses an array.

        Can vectors be used in place of arrays


        In this class -- use vectors whenever you have the option.

        When do I use vectors

        Nearly Always!

        Exception... I know that I need precisely <...> items. Example: 9 squares on a Tic-tac-toe board.

        What are vectors actually used for

        Storing a collection of data items in memory and to allow us to reorganize the data.

        What kind of program uses arrays vs vectors

        Old programs used arrays -- no choice. Modern programs tend to use vectors. Exception to speed up code.

        How does the size of an array relate to the last subscript

        If the last subscript is 5 then the size will be 6 elements.

        Can you give a clear definition of an array

        A fixed number of items of the same type numbered from 0 upward and stored in adjacent pieces of remarry memory.

        What happens if we put a string into an array of ints

        C++ will convert the string into an address and store that!

        What functions are part of the vector library

        Check out the documentation in [ ../samples/stl.html#Vectors ] [ ../c++std/cd2/lib-containers.html ] (from the draft standard...)


        When we write a loop must we separate the different conditions on different lines

        You don't have to. The compiler will compile the same condition independent of the layout you choose.

        But one way to make conditions clear and easier to understand is to separate them. When you format code tidily you will make fewer logic errors.

        How do loops work

        It depends on the loop. If it is a while loop like this:
         		while ( C ) { B }
        then the computer does the following

          Evaluated the condition C;
          If the result is true then Execute all of B and go back to step 1.
        1. If the result is false then continue

        You get a pattern like this:
      1. C; B; C; B; C; B; .... B; not C;

        A for loop like

         		for (A; B; C) { D }
        is more complex
        1. Execute A
        2. Execute B and test it.
        3. If the result is true then
          1. Execute D
          2. Execute C
          3. Go back to step 2 above.

        4. If the result of B is false continue

        (Note: memorize this!)

        In short the pattern is

      2. A; B; D; C; B; D; C; ...; C; not B.

        When can we use loops in programming

        Whenever you have a set of statements that need to be repeated several times you should use a loop.

        Whenever your algorithm talks about "repeating steps.... until ..." or "Do .... until ..." then you must use a loop.

        Note: Writing an algorithm before you start to write code is the only way to get complex loops that work!

        Do we have a list of compiler errors and there meanings

        Not as far as I know. It is worth making your own personal list of the errors that happen in your own programs. Practice can help a lot in finding errors.

        There is one trick is to notice the line number of the error and look backwards from that line.

         m_n_ms.cpp:22: error: `string' has not been declared

        The book lists three kinds of errors -- are there more

        There are a lot of programs that do precisely what is planned and expected of them. They fit the requirements that the programmers were given... However they don't do what is actually needed.

        We have a joke: that is not a bug, it is a feature.

        These requirements mistakes are the kind of error that I am very interested in. They are quite insidious. But they are a type of logic error.

        Do execution and Logic errors show us errors like compiling errors

        No. The compiler accepts the program as OK and then bad things happen.

        What is the most common error made by programmers

        Compiler -- depends on the how much experience the programmer has. But a common one is not declaring a variable or including a library.

        Execution -- Running of the end of an array.

        Logic -- off by one errors with indexes and counters.

        What is the most common Execution Error that you see

        Uninitialized variables. Especially when the variable is what we call a pointer -- and is supposed to store the address of some data.

        Can you identify execution errors before you run a program

        I can do this fairly well -- and I write my own code with enough care that I don't get very many -- except when I'm short of sleep.

        However a complex program can defeat the best of us with an unexpected error when it runs.

        How do you copy a file using ssh

        If you are logged into a Unix computer and want to copy a file called original to a file named new then you write the command
         		cp original new

        If you are running the Secure File Transfer Client then you can probably use the mouse to Right-Click the file and pick the 'Copy' item in the menu that pops up.

        (thank for a question that taught me a new technique).

        How exactly can one exploit code that has gone over the bounds of an

        array Perhaps you should go to the "Ethical Hacking" seminar the CSci club is running.

        The details depend very much on the machine and the mistake. I have an example in my cs202 labs. A badly designed login system that anybody can log into as long as they supply a long enough user name. What happens is that the user name overwrites the password field with something like 'xxxxxxxxxxx' and then you can use something like 'xxxx' to login.

        Is there a program that checks for errors automatically

        The complier tries to catch as many as possible. There was a program (lint) that looked for suspicious code that was probably an error... an example would be the following pattern
         		if ( ... = .... )

        But Computability theory proves that there is know computer program that will find all the errors in a computer program. We cover the details of the proof in the CSci546.

        Does C++ allow you to run the program line by line to find the errors like Visual Basic does


        What debugging aids are there in the Lab

        There is a Gnu Debugger (gdb) that does this.

        By the way -- it is a command line debugger and so can be used remotely via SSH. The KDE provides a GUI front end called "kdbg" that is under the "Start"->Development->KDbg menu.

        You can find out more [ Gdb ] on the Wikipedia.

        On the other hand find most debuggers harder to use than thinking and planting extra outputs. I don't use it enough to be any good at it or to give you instructions and advice. I have a CS202 lab that Dr. Zemoudeh wrote that showed how to use gdb.... but I've discarded it in recent years. To be honest -- I feel debuggers are for wimps:-)

        A number of people have asked about these debuggers. I will see what documentation I can find... TBA.

        What is the difference between a compile error and a logic error

        Suppose that we programmed in English then
         Cat the mat on sat.
        is a compile (syntax) error. But
         Poor oil on burning water.
        is a logic error.

        In other words a logic error follows all the rules of the language but instructs the computer to something bad or at least unexpected.

        Will a program with logic errors compile


        How can a program with logic errors compile

        Because commands can make perfect grammatical sense and still be bad. Computers don't understand this and do it anyway. The key point of computer science is that computers are stupid but follow instruction precisely as written. Badly chosen instructions lead to erroneous behavior. The logic of the program is broken.

        It can be quiet subtle. For example: my wife is a substitute teacher for SBUSD but the new computer program can not be told that she is not in the house with out inputting her PIN... and a lot of other stuff. This compiled, runs, and makes us both want to smash the telephone. I class this as a logic error. Bit notice the program must have compiled an run without an execution error.

        Is there any reason for not using double

        Don't use double when you want to exact answers.

        As a rule you only use int's for counting. If you notice that you are doing lots of multiplications, and you don't mind an approximate answer then you can use double.

        There is another solution to the problem when you want to do precise (integer) calculations with very large integers. It is not a simple solution: you must use an vector of int's to represent numbers and work out operations for multiplying, adding and subtracting using multi-length arithmetic your self -- or hunt for the functions and classes on the Web.

        I'd love to spend time on this but it is not a very useful technique for everyday programmers. Perhaps I'll be able to put it in a future lab!


        What are the limits of error messages

        The can spot syntax errors and warn you of one or two logic or execution errors.

        How to combine if and while statements

        It depends on the algorithm you are trying to code.... when you have more than two or three ifs and whiles you need to first sort out your algorithm.... your plan of how to solve the problem.

        If part of the algorithm reads

         	If A is true then do B while C is true else do D.
        Then you'll probably have
        Notice the careful indenting to make the structure obvious.

        Another classic part of an algorithm puts the if inside the while:

         Repeat the following until A is false
         If B is true then do C else do D

        To summarize: first get an algorithm, second code it with indenting.

        How do I incorporate whiles and ifs with messing up

        First: get an algorithm. Second: code it with indenting.

        How do you know when to use a string

        Use a string any time you have data that has characters in it: names, addresses, StudentIds, SSNs, Dates, Times, .....

        Basically they can be used in just about any program.

        Describe in further detail about getting fast and easy access to elements in the sequence of a vector

        If you have a vector with 1,100 elements:
         	vector <double>example(1100);
        Then you can access the first element as
        The 115th item
        The last item

        More you can access a whole subset

         	for(int i=114; i<120; i++)
         	{	do_something with example[i]

        How to character literals work

        The compiler spits the blip (') on the input and enters the code for translating character literals. This code puts the right character or pattern of bits into a one byte storage area:
        1. If the next character is a blip(') then report a compile error.
          If the next character is not a backslash (\) then that is the character to store. If the character after that is not a blip(') report compile error and exit. But if it is... store the character and exit.
        2. If the next two characters are a backslash followed by a 0 then translate the string from octal to binary.
        3. If the next three characters are a backslash followed by an x and a 0 then translate the string from hexadecimal to binary.
        4. Else compile error.

        (Note 1 -- I let you work out the details). (Note 2 -- I'm guessing about the algorithm).

        Can you teach us to write in binary

        Yeah -- easy. Just pick a few binary digits -- each one either a '1' or a '0'...
        You interpret these as a number by using powers of 2:
         			64+32+   8+4+  1

        There are some standard algorithm for converting decimal to binary and back. Each computer Scientists has their own gimmicks --- A friend taught me how you can do the conversions on a Japaneses Soroban abacus!

        I can show you a program that uses characters and strings to write out the binary form of a number if you like: [ ../cs201/binary.cpp ]

        Can you create a while statement that will read the a program backwards

        Well, programs are in files and we can write code that reads a file in the order in which it is stored.... but we don't have the tools (in CS201) to go backwards through a file.

        What I can demonstrate is how you can read a file forward and put it in a string backwards and then print it out: [ ../cs201/backwards.cpp ] , you can download this and compile it into an executable called backwards and then try this command

         		./backwards < backwards.cpp

        How will we use strings

        I'm not sure what I'm going to ask you to do.... except it will involve: substr, find, +, [...], and a few other simple operations.

        There is no knowing what you might choose to do in your project with strings.

        What is the function of a string

        To hold character data like names, addresses, telephone numbers, ....

        What is a character array

        It is a piece of computer storage divided into character sized pieces and numbered from 0, 1, 2, .... up to the size - 1.

        In other words it is an array of chars.

        Think of a character array as a box in a form where you can write or type things. Fixed size. Type in what you want, where you want, and read it out again, and change the content.

        Why is the old str library dangerous

        It does no error or bounds checking. Even the simplest operation of copying can crash the program or operating system if not written very carefully.

        Explain more about strings

        See below!

        What is a simple explanation of the standard class string

        "Standard" means that you should get the same behavior from the <string> library where ever you use C++. The word class means that strings are objects and we can do things them like this
         		object.operation( data ).

        A string, in theory, has these operations:
      1. Concatenation s1+s2
      2. Substring s.substr(start, size)
      3. Find matching substring s.find(match)
      4. Find number of characters in string s.size()
      5. Get the i'th character s[i]
      6. How do strings differ from character arrays

        Strings have a lot of useful operators that arrays don't have.

        Arrays have a fixed size and this makes them hard to use. Strings automatically get the storage they need when they grow. Automation makes strings easier to use.

        Please use strings when ever you can!

        Is there a limit to the number of characters in a string

        Not really. I think you can fill up the whole of the virtual memory given to you program in a string -- 1 byte to a character.

        What is MS-DOS

        DOS stands for "Disk Operating System" and MS-DOS was Microsoft's first big contract -- to supply a Floppy Disk-based Operating System for the new IBM Personal Computer.

        When you open the Command Line/ Run Command box in Windows you can input a MS-DOS command.

      . . . . . . . . . ( end of section Questions) <<Contents | End>>

      Questions on Functions

        Can you explain Binary Search

        Binary search search a collection of items by dividing them in half and then picking one half to search. It is a common example of a divide and conquer algorithm. You can use the algorithm to search anything that is in the right order. The white pages of a telephone directory is one example. To find a name in the directory, you put your finger in the middle of the directory. The name is either before or after your finger. Pick the correct half. Again, divide the pages you are search into two halves, and pick the right half. Continue until the page you want is in front of you.

        Try it on any order list, array, or vector...

        What is the purpose of functions that return a value

        They defines a short hand way of doing a long calculation. You can get the calculation by just calling the function. You can share it with other people as well.

        Are there an infinite number of functions in C++

        There is a potential for an infinite number, but any given program can only have a finite number.

        Is there any limit on the number of functions


        Can you put if and while inside a function


        Can you define a function inside a function


        Can we use functions in place of anything

        I guess so.

        In simple words what is a function

        A named piece of code that you can use many times in many ways.

        How are functions declared

        Functions a declared by writing the header:
      1. type_of_data_returned name_of_functions ( parameters )

        From then on (but not before) you can use that function in the program. More in the next class on this topic.

        Can you explain the fmod function

        Here is a working program [ ../cs201/fmod.cpp ] that demonstrates what it does.

        Why are there only functions and no procedures in C++

        The inventors of C thought it was a good idea to only have functions. If you didn't say what was returned, it would be an int.

        When they standardized C they let people use the word "void" to indicate functions that didn't return a useful result. So procedures are called void functions in C++.

        What is return

        Return is a statement that gives control back to the calling code. The computer leaves the function and continues from the statement or expression after the call. The return can also calculate and return a value.

        How do I use return

        First plan an algorithm for the function.... where it has a result and finishes.... you have a place in the code to write
         		return result;

        Do you declare functions before main


        You have to because you can only use a function after the compiler has seen a declaration (the header) of the function. Before then the call will not compile.

        Can functions produce non-numerical results

        Yes. Functions that return bool are good for testing and are called predicates. Functions returning strings and characters are also useful. Beware, however, of returning arrays from a function. The results are not good.

        How do functions use parameters

        First they evaluate them. Then they move the values to the initialize the formal parameters -- just as if they are local variables.

        More on this in the next lecture/discussion.

        What is a block

        A function with no name! More officially it starts "{" and ends "}" and has at least one declaration.

        How can variables be declared in blocks

        Just like they are declared in the main program.

        Can things be declared outside a block


        Functions must be outside a block (with a couple of exceptions mentioned later this quarter).

        Variables can be declared outside a block. They are called global variables and are a very dangerous feature seeing that any function can change their values without any sign of the change occurring.

        Constants can be defined out side a block and are called global constants and are a very good way to define natural constants and numbers. The classic example being

         const double PI = 4*atan(1);
        Here is another:
         const int DAYSINWEEK = 7;
        These are computed before the program starts and can be used safely anywhere in the program. Notice that constants should be in capital letters.


        How does a search know what number to search for

        You have to have a parameter or variable that contains the target number. I usually call it target. If you need to get both the target and the numbers into the computer from the user in this course you will either need to read in the number of numbers first and then the target (or targets). An alternative is o read in a single target first and then read in all the numbers until CTRL/D.

        How do you compare to strings

        If you have two strings, like this:
         		string s1....
         		string s2....
        Then you can use the same operations as you do with ints:
      1. s1 == s2
      2. s1 != s2
      3. s1 <= s2 (lexical order)
      4. s1 >= s2 (lexical order)
      5. s1 > s2 (lexical order)
      6. s1 < s2 (lexical order)

        If the data are null-terminated character arrays (texts) then you need to use:

         		strcmp( "abc", "abd")
        which returns the difference of the first two characters that a not equal. It give 0 if the two arrays are equal.

        How are functions used

        Functions are used when they are included in a program and then called.

        You should use them to contain common calculations and tasks.

        They let a single statement of simple expression stand for a complex computation.

        What functions help you round numbers in different ways

        You get standard rounding when ever you assign a double to an int variable. This converts the double to the nearest int.

        The cmath library has two functions that convert doubles to integers. They are named ceil and floor. The function ceil returns the smallest integer that is not less than the value of the parameter -- the ceiling above the number. The function floor returns the largest integer that is not greater than the value of the parameter.

        Should we put a return statement at the end of a void function

        Not really. The compiler will do it for you anyway.

        What makes a function and advanced function

        It has one or more of the following features:
        1. reference parameters
        2. default values for parameters
        3. recursion
        4. etc.

        How do we avoid overcomplicated functions

        Divide them into simpler and smaller functions.

        How ever you can prove that some problems can only have complex solutions.

        How to avoid overloaded functions


        Can we make our own library of functions

        Yes. Put them in a file called mylib.cpp for example and
         	#include "mylib.cpp"
        (Notice the double quotes -- they tell the compiler to start looking for the include library in the same directory as the include statement. )

        If you have a lot of useful function you might consider precompiling them and having a header file "mylib.h". But this is up to you.

        What if two overloaded functions have the same number of parameters?

        The compiler looks at the types of the parameters and picks the function that fits each call. The compiler will complain at great length if there is no such parameter set, or if there is more than one.

        Explain the declaration scope of an Entity

        It is the places in the program text where using the entity refers to a particular declaration.

        What is a recursive function

        Any function whose definition include (directly or indirectly) calling it self.

        What is a reference parameter

        A reference parameter as a "&" (ampersand) character in the its description. It means that each function call will provide a variable. The variable provide in each call will replace the parameter in all computations. This is the best way to communicate several values back to a calling program.

        Why divide programs up into independently compiled files

        This is for large projects. You split the problem into files and put them in different files. You use "#include" to share function declaration. You use a Makefile to make sure that each file is compiled before it used.... there is no such parameter set, or if there is more than one.

      . . . . . . . . . ( end of section Questions) <<Contents | End>>


        How is numeric data important

        Counting and measuring are key human activities. Starting with money, lengths, land, volumes, weight, ... we have always needed to compute with numbers -- or get cheated. So understanding how numeric data works (and sometimes fails) is a useful piece of knowledge.

        What predefined data types are most useful when starting C++

        Which predefined data types will we actually be using

        Use int to count and scan, use double for measurements, and strings+chars for non-numeric data.

        How does a computer work

        A computer has a control unit(think: dumb brain), an arithmetic-Logical Unit (ALU) (think: calculator), primary memory(think: working space), secondary memory(think: file cabinet), and input/output(think: in and out trays).

        The primary memory is divided into numbered memory cells each holding one byte of information.

        A control unit has a program counter (PC) that counts instructions and follows the Van Neuman cycle:

        1. Get the next instruction from location PC.
        2. Decode the instruction into operations and the address of data.
        3. Get the data form primary memory and move it to the arithmetic logic unit.
        4. Tell the ALU to do the operation
        5. Send the result back to somewhere in memory.
        6. Compute a new value for PC and return to the first step.

        Note: some instructions skip steps. For example, Branch instructions often just move the address into the PC.

        What determines the size of data types on a machine

        Nearly all machines have a fixed size for int's and one for doubles. I've only know one where you can change the "word size" as it ran. It didn't survive in the market place.

        What is a float

        In C++ it is a number that has a floating decimal point but is not as large, slow, or precise as double length. The details do not matter much!

        Is there a limit on the size of floating point numbers.

        Yes ... also on the precision. But it all depends on the CPU you have and the compiler you are using. However there is a library <float.h> or <cfloat> that defines constants like FLT_MAX, DBL_MAX, and LDBL_MAX the maximum representable number in each of float, double, and long double.

        The <limits.h> or <climits> library does something similar for chars and its.

        By the way, these days all CPUs are using the IEEE Standard floating point notation (ANSI/IEEE Std 754-1985) which defines the limits and precisions.

        Notice: all computation is limited by the amount of memory available.

        What is the purpose of the sizeof operator

        It tells you how many bytes the compiler has given to a variable or to a data type. The lab will give you many examples... .

        How do bits store information

        A bit can be made to stand for a single true/false or 1/0 decision.

        Two bits can handle four different cases. All we need to do is to decide what each combination means. Similar 8 bits can handle 8 different meanings. Here is how we would make them encode unsigned and signed numbers and as Days of the week:
        BitsUnsigned #Signed #Day of Week

        The information has to be encoded as data. In effect we give each bit a particular meaning. We usually do it character by character. But good examples include the UPC code or the International codes for Airports.

        Exercise: work out a one letter code for the days of the week.

        Exercise: work out a two letter code for the months.

        Who put binary code together

        I think it was Liebnitz in the 1600's. The Chinese used something like it thousands of years ago.

        How are letters changed to binary

        When you tap a letter on the key board a particular set of contacts is made.

        The ASCII code specified that 'A' was 01000001 and that B would be next... and so on up to 'Z', 'a' starts with 01100001, and so on up to 'z'.

        It was a committee decision by the American Standards people.

        Does every key on the keyboard have a special number

        The main keyboard A-Z0-9....{}[];:....!@#$... are all one byte ASCII numbers. The arrow and function keys use a sequence of 2,3, or 4 one byte codes developed by ANSI...

        Does the operating system determine the word size -- Vista comes in 32-bit and 64-bit versions

        I think that this indicates the size of an address in programs running under the operating system. I don't think it changes the amount of data the CPU handles in one cycle. I think that the sizeof operator may well give the same sizes, for example, whatever the operating system is.

        Why are there 8 different predefined data types

        This is how C evolved.

        The book doesn't mention some of them like wchar (wide character).

        What is the method used to store positive and negative numbers

        It is called twos-complement... The Wikipedia article [ Two's_Complement ] is a good description of how it all works and why.

        Is there a negative unsigned data type

        No. Not really needed. You just write the code with a normal unsigned number and imagine it is negative as you write the code.

        When is void used

        We put void in a function definition to indicate it doe not return any reliable data.

        The is another use, the infamous 'void*' which may mention but leave for CS202 to explain in detail.

        Can you write a program to search a MS Excel spreadsheet for data and take you to it

        Probably. I've done searches like this in other spreadsheets.

        What does bool mean

        The keyword bool is short for Boolean, which refers to the name of George Boole. This link [ Boolean ] into the Wikipedia will lead you to more than you need to know about things Boolean.

      . . . . . . . . . ( end of section Questions) <<Contents | End>>


        What should I use instead of a break statement

        I tend to use Boolean variables plus if-else statements. As a simple example:
         		for (i=0; i<N, i++)
         			if(C) break;
        We can vanish the break like this:
         		bool unbroken=true;
         		for (i=0; i<N and unbroken, i++)
         			if(C) unbroken = true;
        But -- if you have a working program with one or two breaks you might as well leave it alone.

        How many different functions are there

        There are an infinity of functions.... for more take CSCI546

        Could you show us a function example like the one in the quiz


        What is the Hexadecimal and octal forms in terms of bits

        Hexadecimal notation groups the bits in fours. The octal notation groups them in threes. So the bit pattern
        is split like this
         		0010 1010 0111
        and each 4-bit nibble is turned into a hex digit, giving the equivalent hex code: 2A7.

        In octal the same bit pattern is split like this

         		001 010 100 111
        giving the octal form: 1247.

        Octal and Hex are popular because these translations are simple to do (compared to decimal vs binary).

        What is the difference between absolute and relative addresses

        The relative addresses start counting at some base. Absolute start counting with address 0.
      1. absolute = base + relative.

        Please explain the sizeof operator

        First notice the spelling is not English -- there is no space between 'size' and 'of'.

        Next, you can put 'sizeof' in front of any variable and the compiler will calculate the storage that it will give to it and replace the expression 'sizeof v' by the number of bytes allocated to 'v' -- by the compiler. This does not include any storage allocated while the program runs with 'new'.

        You can also use it with the name of a data type

         		sizeof int
        will tell you the number of bytes used in one int.

        Why are there different forms

        Arabic notation with 10 digits is based on humans having 10 figures. Binary is because electronic circuits that have 2 values are fast, cheap, and accurate. Octal and Hex come from the need to write down and remember complex binary numbers simply.

        I don't know why have both Octal and Hex. But it is the older computer scientists who think in Octal...

        Is there a reason to use double instead of float

        Double is more accurate.

        Review Pass by reference and pass by constant reference

        Both share access to data without copying it. Pass be reference lets a function access and change the data given to it (as an address). But with a constant reference the function can not change it.

        With pass by value ... changes are made to the function's copy of the given value and do not propagate back to the calling program.

        What does a segmentation fault mean

        It means a pointer has gone wrong. Here are some common causes
        1. Going beyond the last index of an array or vector.
        2. No terminating '\0' at the end of a char text.
        3. Not leaving room for a '\0' at the end of a char[].
        4. Following the NULL pointer.
        5. Not initializing a pointer before it is used.
          A loop that moves a pointer into terra incognita.
        6. Assigning an integer value to a pointer : int *p = (int*) 17;

        How do pointers and text strings work together

        A text string is an array of characters that ends with a special null character '\0'. Each element in this array can be referred to by a pointer. Mostly there are some standard for loops that are used.The old "string.h" library has some classic pieces of code like 'strlen', 'strcat', 'strcmp',...

        There are more complex algorithms. I think of pointers as little fingers pointing to places in the array of chars. The ++ operation and the -- operation move the fingers in opposite directions.

        For example you can have two pointers starting at opposite ends and use them to test to see if a text string is a palindrome

         bool palindrome(char* a)
            bool palindrome=true;
            char *p = a;
            char *q = a+strlen(a)-1;
            for( ; p < q and palindrome; p++, q--)
                 if( *p != *q )
            return palindrome;
        You can download [ ../cs201/13palindrome.cpp ] (function + tests) and see if it works.

        How are pointers used in todays popular programs

        I'd love to.... but most software is closed and a trade secret, so I can only guess.

        I have some open source software that I maintain [ http://www.csci.csusb.edu/dick/cs320/lisp/src/ ] is an example.... Meanwhile

        How are pointers used in practical situations

        (1) Parameters passed by reference uses a kind of pointer. (2) Getting more storage as the program runs. Vectors have an internal pointer that is points at the heap. (3) Advanced data structures (CS202 and 330) are all built by using links. The links are pointers. (4) All work at the hardware level (drivers) use pointers. (5) ...

        What is different between p1=p2 and *p1=*p2

        Assuming that both p1 and p2 are pointers to locations then
        will change p1 to point to the same place that p2 points. Here is a picture of memory before and after:

        The command *p1=*p2 changes the place that p1 points to by the place that p2 points to:

        To see why this is review what a pointer is and how it works.

        Notice that if p1 or p2 is undefined or NULL then *p1 and *p2 lead to a run time error. However 'p1=p2' makes sense.

        Can you have an array of pointers

        Yes. They are even useful for some programs. For example we can declare the main function as having an array of pointers to texts:
         int main ( int argc, char* argv[] )
        which are the arguments of the program when executed as a command!

        Can you have a vector of pointers

        Yes. For example for any type T
         		vector < T * > vpt;
        declares a variable vpt which is a vector of pointers to data of type T.

        These are often used in advance object-oriented code.

        What is a lingering Pointer

        This happens when you use a pointer to allocate memory that has been deleted. The data is no longer there and the program (with luck) crashes.

        How do you use a lingering pointer

        You avoid it like the plague.

        Some years ago I was working on a complex interpreter for the language Prolog for use in CSCI320 (Programming Language). It had a very strange bug that would some times pop up and crash the system -- in one laboratory but not the other lab! I thought it was the print routine, but I couldn't see anything wrong in it. Then I noticed that the crash only occurred when a variable appeared twice in an expression -- in one lab only -- the lab that used some IBM UNIX workstations. And I remembered that IBM computers tend to remove primary from a program when you deallocate it, but other manufacturers let you keep the storage in case you wanted to reuse it. Suddenly it dawned: When one variable appeared in two places the garbage collection routine was deleting the storage twice. The first time was ok but left a lingering pointer. The second time the IBM computers crashed the program. It took about 20 minutes of programming to fix the deletion routine to work properly.....

        Can there be any use in garbage -- allocated memory with no pointer

        We call it garbage because it can't be used any more. It is wasted space. We can't even delete and so recycle it. It is in the computer's land fill: the heap. However when the program finishes all the memory is given back to the operating system.

      . . . . . . . . . ( end of section Questions) <<Contents | End>>


        What are declarations

        A declaration reserves some storage and gives it a name. It may also put data in the storage.

        Please explain the void parameter and its use in more detail

        If you declare a function like this
         .... fred (void )...
        then the compiler will object if you ever write any call of fred with data in it:
         	...fred (42);
        is now illegal.

        Similarly, if a function is declared to return "void" then you may not use it in an expression to get a value.

        How are pointers and arrays useful in computer programming

        First: arrays are a very common type of data. See below for examples, and the book.

        Second pointers provide a simple and fast way to access items in the array. Here is an example with an array of ints being added up by using a pointer

         int sum(int a[], const int N)
         	int sum =0;
         	for( int* p = a; p < a+N; p++)
         		sum = sum + *p;
         	return sum;

        What does the command char do

        The keyword char is the name of a predefined type -- the computers standard character type -- these days coded as 8 bit ASCII. Because "char" is the name of a data type you use it primarily to declare variables and constants:
         	char input;
         	const char QUOTES = '\"';
        These statements reserve a piece of primary memory and give it a temporary name. It is just big enough to contain one byte (8 bits) of information.

        You can also use "char" to declare arrays of characters and to specify parameters and returned types from functions:

         	char example ( char para ) { return para + 1; }

        What is typedef

        The typedef key word (notice the spelling) is used to give a new name to a complex data type. Giving things well chosen names makes them easier to understand.

        You use "typedef" by writing it in front of any normal looking variable declaration:

         	typedef vector <int> intvect;
        and it totally changes the meaning. In stead of creating a new variable (storage, address, ...) it defines a new data type. You can then use it to declare variables
         	intvect example_int_vector;

        Typedefs can make some declarations a lot easier to understand However I don't intend to require them in any project, use them in example, or test your knowledge of them in any quiz or final. .What is the function of enumeration types They make programs more readable. See next Question.

        How does an enum reduce bugs

        Enumerated data makes you code more readable. It makes it harder to do stupid things like forgetting how you coded a particular value. It makes it easier to see a mistake. For example if you saw:
        you can only guess at what is in my mind. But if first create an enumerated type with good names you know precisely what I'm writing about:
         	enum StopLight {red,yellow,green};
         	   StopLight light;

        And if you find me doing something like

         			light = light * green;
        you can be pretty sure I've made a mistake!

        Here more examples:

         enum TicTacToeSymbol {empty, oh, cross};
         enum LifeState {dead, alive};
         enum Month{jan, feb,mar,apr,may,jun,jul,aug,sep,nov,dec};
         enum DayInWeek { mon, tue, wed,thu, fri, sat, sun };

        When using enumeration types does the compiler assign a values to the different words


        The compiler removes the names and replaces them by numbers so you don't have to learn anything new about how enumerated data works -- it is an int in disguise.

        The normal numbers are: 0,1,2,3,....

        You can specify any int you like for an enumerated value.

        Can you explain why you need an array of strings with an enumerated type

        This shows you a common technique that is used when you have an enumerated type and want to input and output its values. The technique is to declare an array of strings that show the outside view of the data -- inside the computer enumerated values are just numbers. Then you use the array to output them.

        Example.... I declare TicTacToe to have three values: empty, oh, and cross. (see above). This does not help me output the values. So I also declare

         	const string tttout[3]={" ", "O", "X"};
        So no I can output a particular place on the board like this:
         		cout << tttout[empty];

        More below...

        What is a multidimensional array

        A one dimensional array is a row of items numbered [0], [1], [2], ..., [SIZE-1]. Examples include an array of characters "abc" and this array of ints:
         	const int DAYS_IN_MONTH[12]={31,28,31,30,31,30,31,31,30,31,30,31}; // not leap year
        You access an element like this DAYS_IN_MONTH[jan].

        Note: I used an enumerated value in the above example...

        Multidimensional arrays have two or more subscripts. They have two or more dimensions. They are arrays of arrays.

        Examples of two-dimensional arrays.

         		TicTacToe board[3][3]; // 9 cells in a square array
         		LifeState plane[100][100]; // for Conway's game of life
        You access elements in these arrays like this: board[0],[1], plane[24][42], etc.

        Once you have got a TicTacToe board and a array tttout defining how to output the symbols you display a board like this

         for(int row=0; row < 3 ; row++)
         	for(int col=0; col < 3; col++)
         		cout << " " << tttout[ board[row][col] ] ;
         		if(col < 2)
         			cout << " | ";
         	cout << endl;
         	if( row < 2 )
         		cout << "-----" << endl;
        (This code needs combining with previous snippets and testing...)

        Another example is a single work sheet for a spreadsheet! In fact, most of the tables that users want see are two dimensional tables:

         		double sales[WEEKS][DAYS_IN_WEEK];
        You access the cells like this sales[8][fri]

        Three dimensional arrays are also common. A modern spreadsheet has many worksheets and each of those is a two dimensional array of formulas. Similarly, many scientific models of objects -- a body, a bridge, a block of uranium, etc. are modeled by a large three-dimensional array. The cells in the array can store the amount of bone, the stress, the radiation, etc. in the cell... and the computer can calculate what happens. This kind of volume Modeling and computation is expensive and common!

         	double bone[10][10][10];
        declares an array of 1,000 cells organized like a cube. You access a particular cell like this bone[row][col][slice].

          Be happy you have multidimensional arrays. When I started out I didn't have them in my programming languages. I will not forget in hurry a friend who need a 5><5 square and declared 5 different arrays:
           		double a[5],b[5],c[5],d[5],e[5];
          And the pages and pages of special code for each row of the array... I went in a different direction. I declared
           		double a[25];
          and had to mentally transcribe a[r,c] into
           			a[ 5 * r + c ]
          every where...

        If we want to combine 2 different arrays do the rules of matrix addition and multiplication apply

        NO. Sadly, no. .... You can not add and multiply arrays in C++ unless you have included definitions of the operations. You'd have to hunt for these on the Internet.

        Don't get me on the topic of programming matrix operations. I have had to do it in two different jobs and did four years of college work on them....


        Why is information added before the main program doesn't the compiler ignore it

        The only things that the compiler ignores are comments. They are used to help human beings understand the program... including your future self. There are two kinds of comment. The big comments take up many lines and start with
        and end with
        You can also add comments at the end of a line by first putting
        Comments record your thinking and work getting the program to do what it should do. The compiler ignores them but humans (like the teacher) uses them.

        The constant definitions, function declarations, and classes that appear before the main are stored by the compiler ready for the main program to use them.

        What is the function of a typedef in simple terms

        The typedef statement is subtle and so it is hard to describe it accurately and simply at one time.

        Briefly: a typedef stores a complicated definition of a type and gives it a name. Then you can use the name to stand for the data type.

        Please check last weeks notes for more...

        How do I use the signum function

        This is a function that is given a number and returns a number so
         		cout << signum(-17) <<endl;
        should use it and out put -1.

        If I have a long in a function parameter can I call it with an int value

        Yes. The compiler adds code to make the int fit the new format. It is called a widening coercion.

        If I define an enumerated "suit" type do I have to write input and output functions

        Yes. See example in previous notes.

        Why do we need object orientation

        1. Employers expect it.
        2. Your programs will be easier to modify.
        3. Your colleagues will not think that you are Rip van Winkle.
        4. You'll get more points in CS classes.
        5. There are some real cool tricks available to OO programmers
        6. ...

        What is the purpose of object-oriented programming

        First: it lets you reflect the real world problem in your code. Thus the program is easier to construct and easier to understand.

        Second: it makes your program into a large number of simple pieces. You can work on each piece without worrying to much about the rest of the program. The program is split into classes, and the classes into functions.

        Third: You can extract a class into a file and use it in many different programs. Some people have made a career out of selling useful "class libraries".

        Fourth: Fewer complex algorithms.

        What is the difference between OO programs and structured programs

        The division of the code into classes rather than steps in an algorithm.

        The typical OO program starts with classes and ends with a tiny main function.

        Why do we have all these different names for the same ideas

        Because we are human. It takes time for a language to stabilize and OO has only just got to a standard language -- the UML.

        What is a class

        A class is a set of similar objects. It has a name and declares a set of variables. Each object has these variables in side it. The class also defines a set of functions that work on the variables. All objects in a class can handle these functions.

        What is a class diagram

        A class diagram is a picture of a set of classes and how they are related. It can show name, data, and operations of each class. It can show that objects of once class have, know, or use objects of another class.

        A class diagram is a blueprint for an OO program.

        Does the UML shows some pictures

        Yes. The UML -- Unified Modeling Language -- is a graphic language. It use pictures to express OO ideas.

        What does the UML stand for

        Unified Modeling Language

        What is the UML

        It is a way to draw pictures that combines just about every technique used to design programs -- since the time of Babbage onward. It is now a standard language and supported by all the big players in the software field -- including Microsoft, IBM, etc.

        Can I demo the UML diagramming tool in class

        Yes... see below

        Can you save the example Dia in class

        [ ../cs201/15UML.png ] (to look at) and [ ../cs201/15UML.dia ] (for you to edit)

        Note: Your Linux doesn't know how to open 'dia' files, but you can teach it (just like MSWindows) by right clicking the icon and selecting the "Open with..." item in the pop-up menu.

        Can you show character arrays in the UML

        Yes. Here is a C++ declaration
         		char array[256];
        Here is what you put in a UML class
         		array : char[256]
        Basically -- reorder, put in a colon, and remove the semicolon.

        As a rule you can use any data type in C++ in the UML like this.

        How do we implement knows, has, is relations in C++

        hasdeclare a data member
        knowsdeclare a reference or pointer data member
        is aderive the class from the other class [ ../cs202/ ]

        What is the inheritance concept

        It allows you to reuse an existing class and add more data and operations to its features.

        Very useful in complex programs. But shouldn't be needed in CS201. Covered in CS202...

      Questions on classes

        What are the predefined floating points

        Float and double are two predefined floating point data types. They have number expressed with a mantissa and exponent format. They are good for measurements but not for counting.

        Will we be translating UML diagrams in to code

        Yes. Demo in class of the Counter class.

        Will we be translating code into UML diagrams


        Would constructors be considered a type of function

        Yes. They are strange because they don't a returned type or a void and always have the same name as the class.

        What are constructors

        They are functions that create new objects. They are called when you declare the object, or when you use the 'new' operation. First the computer reserves the space it needs (by looking at the attributes) and then it executes the commands in the constructor.

        Why do we need classes

        To control the complexity of a big program. It is the old divide and conquer technique. Divide up a complex programs into many simple classes. Connect them by passing messages. As a result the program will be be more maintainable -- and have fewer bugs.

        What is a class

        A class is a template of a set of similar objects. They all have similar data and will accept the same operations.

        Should my class names all start with capital letters


        Does every body start class names with a capital letter

        Every body except the people who wrote the standard does it right. The standard has class names like: string, vector, etc..

        How does a class work

        A class is a template describing an object. It includes a description of the data/attributes of the objects and the operations/functions that can be applied to these objects.

        A class's name is used to construct new objects that belong to the class. Then it is up to the objects.

        Why set classes to private at the start

        Just to remind ourselves of the rule that things a private at the start of a class unless until we write "public:".

        Be happy -- in Java we have to write private or public before every declaration!

        How does an object work

        Objects store there attributes/data in primary memory. You use an object in a program be sending it a message:
         		object_name . message (data)
        This works just like a function call.... but while the function executes the function has access to the attributes inside the object.

        Normally attributes a private and can not be accessed outside the object/class.

        Where would you find a library of available classes

        Start with the standard library. I have a summary [ ../samples/stl.html ] of the most useful -- mainly containers like vectors and deques. The Wikipedia entry [ C++_standard_library ] looks a useful place to learn. I also have a copy of the draft standard [ ../c++std/cd2/index.html ] (not easy to read but comprehensive). You can find other libraries on the web such as [ http://www.boost.org/ ] as an example.

        Can we make our own libraries

        Yes. Put them in a file with the right incantation and then #include it -- put the file name in double quotation marks. The incantations:
         #ifndef FILENAME
         #define FILENAME
        (at the top of the file)
        (at the end of the file).

        What are inline functions

        If you include a member function's body inside its class declaration then it is said to be inline. Normal functions work because the computer jumps from the call to the start of the function and jumps back again when the function returns. An inline function is quite different. The compiler takes the call and replaces it with a copy of the function's body (with parameters substituted as needed).

        So inline functions are fast but take more space. Use them for small function bodies.

        Why would destructors be used in real-life program situations

        They are used for tidying up and recycling storage allocated by 'new' on the heap. Only used on large programs. Not needed in CSci201.

        What does the double colon operator do in a program

        It is used to refer to functions and data inside a function.
         		ClassName::functionName (....)
        refers to the function called functionName inside the class called className.

        Is there a reason why programmers use word_word and wordWord identifiers

        Just history. The Smalltalk people started the wordWordWord convention. The Pascal people the word_word_word idea. C++ doesn't care. Most people use the wordWordWord format. This takes less typing. But it makes it harder to spell-check your C++ code.

        Can we program in Dia like we can in C++

        We don't have a compiler for UML. Dia doesn't even have a tool to output C++ code. Perhaps you should write it?

        What does cerr do

        cerr does every thing that cout does. But you can take output sent to cout and redirect it into a file:
         		command > file
        But 'cerr' output doesn't go in the file, it is shown to the user.

        Use 'cerr' to output error messages and debugging print out.

        Where do I declare a variable so that it belongs to a function

        Put the declaration after the opening '{' of the function and before the closing '}'.

        What are constructors

        They are member functions of a class that have the same name and initialize the data members of the class.

        Are there any other ways to initialize data members other than using constructors

        Not reliably.

        What you often find is a setter member function that changes the value of a data member. For example if you have

         	int knobs;
        in a class, then you may also have
         	void setKnobs(int newvalue){ knobs = newvalue; }

        A good rule is to only add a setter function when it is going to be used by another class.

        What are some other type of programs in which object oriented programming can be used

        OO has been used for all applications, and all sizes of program from the smallest "Hello World" to whole operating systems, like Linux.

        The only case for not using objects is when the program is trivial in a non-OO language. Fir example I do a lot of programming using the Linux shell and tools. They are not OO but are very powerful for sorting, editing, searching, summarizing tables.

        Similarly your grades a kept in a spreadsheet these days. It is more flexible and easy to use than the Object Based Hypercard system Used in the late 1980s and early 90s.

        Dont you need a main program to use a class

        Yes. With out a main function the program never starts running. Because 'main' is where it starts.

        However -- a class may be used by another class, and that class can be use by main.

        Why is the simplest solution usually the right one

        Simple solution don't have as many problems and are easier to fix when things change.

        This philosophy is also a guide for us to avoid unneeded complexity.

        When drawing is there an easy way to combine several classes into one

        What a cool idea!

        Not as far as I know. None of the tools I've used in the last 20 years had this feature. You just have copy in the attributes and operations and connections...

        It is best to only have one class in your diagram from each name. We ended up with several "Person" classes in lab08 because the book illustrated each concept in a different diagram.

        If you wanted a user to input a function with variable what type could you use

        C++ is a compiler it handles and stores functions before the program runs. After then there is no compiler running to accept and insert new code.

        More -- this is a very dangerous feature. Whenever a language has allowed users to supply code somebody has exploited to take control of the computer on which the program runs.

        A quick example -- the first Internet worm caused utter havoc by using email to send and compile code across the Internet. It sent a copy of the attacking program.... and they spread, grew, took over more and more machines ....

        What is the difference between quotes and diamond brackets in include statements

         	#include <iostream>
        starts search the compilers standard library for a file called "iostream".


         	#include "myFile.cpp"
        starts the search in the same directory as the file in which you types the #include line. Only after filing to find it, does it search the standard libraries.

        What exactly does the computer do with int counter = sqrt(n) when n is not a perfect square

        Lets try

         		int counter = sqrt(17);

        1. First the computer makes space for one int in RAM with the name "counter". Then it proceeds to find the initial value to store in it.
        2. Since 'sqrt' is a function that needs a double to work on, the computer converts 17 into a double -- 17.000000.
        3. The sqrt function works on 17.00000 and produce a good approximation to the square root of 17. Something like 4.1231056...
        4. Next the double 4.1231056... coerced to fit into an int slot. To do this it is rounded off to 14. This will be to the closest integer to the double number.
        5. The rounded value 4 is placed in the memory area called counter.

        Notice this hard-to-remember fact: the expression on the right of '=' is evaluated the same way whatever the variable is on the left of the assignment. After the value is found it is made to fit the variable.

        With nested for loops do you do the whole of the second loop inside the first one

        Yes. If you see code like this
         		for(A; B; C)
         			for(D; E; F)
        then the sequence of events is like this
         A; B;  D; (E; G; F; E; G; F; ) !E; C
            B;  D; (E; G; F; E; G; F; ) !E; C
            B;  D; (E; G; F; E; G; F; ) !E; C

        How do you get a program to pick a card at random

        The function 'rand' is used in C++. All other languages have a similar function. They work as random as it gets. The book has a very good example of rand.

        In what situations does having constant object benefit a programmer

        When you have an object that must not, even by accident, change or mutate.

        What is the inheritance concept

        [ ../cs202/inheritance.html ]

        How do objects oriented programming relate to data mapping

        Interesting question.

        First both data bases and OO are inspired by making the software reflect the real world. You can even use UML diagrams (with no operations) to describe a data base.

        Second they have totally different theories. Most databases these days are "Relational" -- organized in tables connected by keys (values of attributes). In OOP we use the addresses (pointers) of data to connect and relate the objects.

        There are some data bases that over some object-oriented features and so we may end up with a consistency between the two approaches.

        Rich now, however, most OO programs has a special set of classes -- the persistence layer -- that know all about the data base the program uses but stops the other objects needing to know about the data base. This is deep stuff and we have several classes that touch on it.

        Which arrow in Dia is used in a class diagram

        It should be the open arrow head: ---->

        Why are the type names in Dia backwards to C++

        UML comes from the Pascal->Ada tradition and Dia follows that tradition. C++ comes form the FORTRAN->Algol->CPL->C->C++ tradition.

        How many bits in a binary number

        It depends on the compiler and the CPU. Write a program that has
         		cout << 8*sizeof(int) <<endl;
        to find out the answer.

        What is the difference between public and private

        These are two key words used in C++ class declarations. Variables and functions declared after a private can not be accessed or used by another class, function, or the main program. Those that are public can be accessed and used.

        In the UML a private member is marked with a minus and a public one with a plus sign.

        The tradition is to make all data private and most functions public. You only allow other classes, functions, and the main program to use the private data in public ways. This makes it harder for programs to do something unexpected.

        The only way to change or get the value of a private int is to use a prewritten public operator/function to do it.

        What are the friends of a class

        A class may declare another class to be a friend. It can also declare a function to be a friend.

        What do friends do

        The have access to the private data and functions of a class.

        Avoid them.

        What does this do

        The keyword this in a member function in a class is a pointer variable with a predefined value. It points at the current object.

        It's main purpose in C++ is to let you send it to another object:

        It is like sending your phone number so people know where to contact you.

        What does the double colon do

        It separates a class name from the name of a data field or function in that class. It makes a complex name out of simple ones. You can use it to make one part of a program refer to a part of a different class -- as long as that is public.

        Give an example of a constant object

        Constant numbers like π are obviously useful. It is rare to need a constant object for a class.

        However it is very wise to pass parameters that refer to objects as constant references. That way the function can see the value of the object but not change it.

        Why do we have to define our own comparison operators for an Array

        C++ doesn't define one as standard -- so when we have a class of objects that we want to compare then we have to tell C++ how we want it done.

        What is an assignment operator

        The main assignment operator is '='. It is used like this
        		variable = expression;
        However there are half-a-dozen others: +=, -=, *=, /=, <<=, >>=, ...

        For example

         		variable += expression;
         		variable = variable + expression;

        What are unary operators

        The following symbols can be used on numbers as unary operators: - ++ -- ! not * ~.

        You can make them work, with the same syntax, on any class of object, if you need to, by defining operations like: operator !.

        Details are in the text book and are not part of this class.

      Questions -- on any simple C++ topic

        How do you distinguish and attribute from an operation

        An attribute is some data. It does nothing.

        An operation does something and is not data. It is a tiny little program.

        Attributes are never shown with parentheses, operation are always shown in with parentheses.

        In the UML: attributes are in the second compartment of a class and the operations are in the third and bottom compartment.

        How do I print a diagram in Dia on 1 or two pages

        The File>> Page Setup menu gets you to a dialog. In the bottom left hand part you can select "Fit to" 1 by 1. Then click the "OK" button. Typically this makes the page fit the diagram a little too tightly, so I add a line across the top of the diagram and select the white color ("FFFFFF").

        Another, simpler technique is to export the diagram as "png" and print the result.

        What is a query

        A query is a UML function that gives you data about an object without changing the object in any way. It is written as a stereotype like this
         		<<query>> getColor():Color
        Queries are also called accessors and are coded in C++ with the "const" keyword
         		Color getColor() const { return color ;}

        Is a friend function only used when there is a left-hand operand that doesn't belong to the class

        No. Any function can be declared to be a friend of a class. It is useful when the function needs access to something that is private in the class. It doesn't have to be an operator, and it doesn't have to explicitly refer to the class in the header, or the body.

        Why do we use classes -- they make a simple program complicated

        We use classes because they make complex programs simpler. They separate the concerns into different classes so we only have to think about a small part of the problem at one time. We can also think about the solution of the problem in terms that are used by our clients. We can model the problem and make a visible connection between the problem and our code.

        We also use them because they are the only way to do drive modern graphical user interfaces.

        Finally there are some useful and powerful class libraries for certain kinds of problem.

        Can we create our own types with type conversions

        Yes. There is one subtle problem that sometimes happens.... that is in CSCI202.

        What is the purpose of a function call operator

        We use it when we need an object that works just like a normal function.

        You can skip the rest of this answer....

        I had a recent case of a student who had written a program to integrate functions of one variable. Here is how we used it:

         		cout << integrate( sin , 0, PI/4 ) << endl;
         		cout << integrate( exp , 0, 1 ) << endl;
         		cout << integrate( recip , 1, 20 ) << endl;
        (where we declared
         	double recip (double x) { return 1.0/x; }

        Our problem was that we wanted to integrate this function with respect to x:

         	double chisq(double x, double f ) {return /*horrible*/; }
        which has an extra parameter f the degrees of freedom.

        So we defined a function object:

         	class ChiSq
         	{ double f;
         	    ChiSq(double f0=1):f(f0) {}
         	    double operator()(double x) { return chisq(x, f); }
        And then wrote
         		cout << integrate( ChiSq(2) , 1, 2 ) << endl;
         		cout << integrate( ChiSq(3) , 1, 2 ) << endl;
        And it worked...