[Skip Navigation] [CSUSB] / [CNS] / [CSE] / [R J Botting] / [CSE201] / FAQ
[Text Version] [Syllabus] [Schedule] [Glossary] [Labs] [Projects] [Resources] [Grading] [Contact] [Search ]
Notes: [01] [02] [03] [04] [05] [06] [07] [08] [09] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20]
Labs: [01] [02] [03] [04] [05] [06] [07] [08] [09] [10]
Tue Mar 12 12:58:55 PDT 2013
Opening the PDF files on this page may require you to download Adobe Reader or an equivalent viewer (GhostScript).

Contents


    FAQs on C++ and CS201

      2012-03-15 Thu Mar 15 12:50 Some questions answered

        Can you explain the debugger

        No! It is not on the final.

        Do we learn bad things thaqt microsoft hides

        No. It is more a matter of freedom of choice and, you can then choose to good or bad with it. This is not on the final.

        How does CE differ from CSE

        CSE201,202,330 is in the core of both. But CE has a lot more hardware, computer logic, and physics, and chemistry...

        Can we use a cheat sheet in the final

        Yes

        Both sides

        Yes

        Small printing

        Yes.

        Is the final only based o the quizzes

        No. It refers to project work.... and to lab and class work.

        What must we know forwards and backwards

        Operators, ints, doubles, strings, claasses, UML, vectors, and arrays.

        How does overloading make a prgram easier to read

        By coosing wise overloads. For example using + to add ints and doubles.

        What is the difference between of adding an else

         	s=0;
         	if(x>0)s++;
         	if(y>0)s++;
         	s=0;
        --------vs-----------
         	if(x>0)s++;
         	else
         	if(y>0)s++;
        In class we tried all four combinations of x and y values for both pieces of code and found a case where the first code makes s=2 and in the second case s=1.

        Can you use boole for none truth values

        No.

        What are the boolean operators


        Table
        OperatorSymbololic Key property
        and&&True only when both are true
        or ||False only when both are false
        not!Turns true to false and vice versa

        (Close Table)

        Why do we use boolean operators

        To express complicated condition -- typically found in the real world like -- taxes, prices, rules, ...

        What is boole more

        This is a variable that is true if a loop should continue. It is set to false when the loop must not repeat any more. It is used to handle loop and a half problems.

        What is a sentinel

        A value supplied as some data after the real data has been input. Or a special value stored in a vector or array to show that the rest of the array of vector has no useful data,

        Nested Loops

        Program fragment that prints out
         	11 12 13
         	21 22 23
         	31 32 33
        ---
         for( char r = '1'; r<='3'; r++)
         {
         	for( char c = '1'; c<='3'; c++)
         		cout << r<<c << ' ';
        
        
         	cout<<'\n';
         }
        Please check the above code.

        When to use a function

        (1) You are told to.

        (2) You are tired of writing the same code, many times (like twice). THis is the DRY -- Do Not Repeat Yourself rule.

        Is it worth using classes when programming alone

        Thoughtful pause.... and then ... Yes, when the problem is complex.

        Can you define a variabl in an object that is not initialized in a constructor

        Yes. But the result will compile and probably have subtle bugs.

        How to avoid parallel vectors

        Use a class.

        Why to avoid parallel vectors

      1. It make the code shorter and easier to understand. For example when simulating asteroids and planets you can replace six vectors by a single vector and a class.
         	vector<double> x;
         	vector<double> y;
         	vector<double> z;
         	vector<double> vx;
         	vector<double> vy;
         	vector<double> vz;
      2. It helps you make programs that reflect reality.
         	class Object { double x,y,z,vx,vy,vz; ....};
         	vector <Object>objects.

        How to use strings inside arrays and vectors

        Carefully!
         		string suits[4]={"clubs", "diamonds", "spades", "Hearts"};
         		vector <string> suits(4);//...

        When to use arrays

        FIXED SIZES.

        How to recover from bounds errors

        you don't. You fix the program and recompile.

        Is there a way to cout a vector without a for loop

        Yes. It is part of CSE202.

        How do you append two vectors of ints

        Algorithm to append vector a at the end of vector b. (
        1. For each element in a (
          1. Push the element onto the back of b
          )
        )

        Is there any data type to store letters and numbers other than strings

        Yes. Single characters can be stored in a "char". A fixed number of chars in a char array. A varying number in a vector<char> -- but this i a string!

        How do reference parameters work with vectors and arrays

        With ref parameters the address of the start of the data is passed to the function and the function adds the index to the address its got to get the item.

      . . . . . . . . . ( end of section 2012-03-15 Thu Mar 15 12:50 Some questions answered) <<Contents | End>>

      2012-02-23 Thu Feb 23 11:30 Questions asked in Class 14

        Why use classes instead of functions

        Functions are OK in small programs: one person, one purpose, one run, and throw away. Classes make it possible to split up a project so that many people can work on it as once. In class we looked at dividing up a tic-tac-toe program into 3 or more teams. We realized that you had to list the function calls between the different parts -- and these should be put in classes so that the compiler can check the connections. This in turn lets the different parts be worked on in parallel...

        Why do we have private hidden information

        So we can separate the problem and work on the different parts safely.

        How do you call a member function from main or another function

        First make sure you have an object of the right class
         			Class object(....);
        then write
         				... object. memberFunction(....) ...

        How do you call a non-member function in a member function function

         				... function(....) ...
        Example
         		diagonal = sqrt( x*x + y*y );

        How do you call a member function from another member function of the same class

        Do not write any object -- this is implicit!
         				... memberFunction(....) ...

        How to correctly define a mutator

        As a member function that returns void.

        How to correctly define a accessor

        As a member function that returns some data and is const.

        How to correctly define a constructor

        As a member function with the same name as the class name ... and returns nothing.

        How to correctly define a data field

        As a member that is not a function and has a type.

        What is the difference between explicit and implicit parameters

        You have to declare explicit parameters. When a member function is called they are put in different places
         		implicitOboject . function ( explicitParameters)

        How do you distinguish member functions from nonmember functions

        Look at where they are declared -- if it is in a class then it is a member function.

        What is the distinction between public and private

        This is a distinctions about the members of a class. If a member function or data field can be accessed from outside the class (and its members) then it is public. Otherwise it is private.

        How do you know which is public vs private

        Look for the key words before the members declaration.
         		public:
         		private:
        In a class, before the first of these the members are private.

        What is the interface of a class

        It is a list of the public member functions found in the class declaration.

        What is the implementation of a class

        This is the list of function definitions after the class plus the private data fields and member functions.

        Why do use a getter function when you can just write function to get the data

        When you write it -- it is a "getter". But many teams adopt the rule that its name starts "get" -- that's all.

        Why is there a semicolon at the end of the class

        Because the syntax rules allow you to declare a class and some instances at the same time:
          class Example
         	{
         		...
         	} instance1, instance2, instance3, ... ;
        the semicolon terminates the list of declared instances of the class.

      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.
      2. <1940s Programs were written for human computers to execute in English and mathematics.
      3. 1940s Programs written by changing the machine hardware (in secret).
      4. 1950s Instructions written as numbers and stored in memory.
      5. 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.
      6. 1970s Structured programming. Programs are designed using Pseudocode and diagrams and split into functions. Pascal. C. Unix. Minicomputers.
      7. 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.
      8. 1990s Objects. C++. Java. The Web.
      9. 2000s Modeling: diagrams of objects etc used to analyze problems and design solutions. Perl, Ruby, C#, Python

        How does a computer work

      10. 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
         		std::cout
        but the
         		using namespace std;
      11. 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:

      12. 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!), gives approximate but good answers, and is slower than integer arithmetic. Floating point numbers have a bigger range than int's.

        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 they give a more accurate answer.

        What are the differences between float and double

        Both have addition, subtraction, multiplication, division, etc.... But this is because float numbers are converted to doubles before the arithmetic is done! Double take twice the space when the number is stored. Float is less accurate and doesn't have as large a range of numbers. So you are more likely to have errors with float than with double. We used float when RAM was expensive and measured in Kb not Gb.

        These days..... use double for all measurements and int for counting.

        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.

        Use 'int' when a mathematician uses 'integer' and 'double' when she/he uses 'real'.

        Beware of dividing ints!

         		2 / 3
        is 0. If you don't want to do integer division -- you need doubles. On the other hand beware of using "%" (modulus) with doubles. It means nothing and doesn't compile.

        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

        Yes:
         		#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++

        Yes.
         		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

        Yes!

        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"
        produces
         		"FredFlintstone"
        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
        then
         		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

        Insert
         		#include<string>
        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
         		12345/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

        No.

        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

        MONEY.

        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 do you compile Pseudocode

        You can't because it is a fake code. It is read and written by humans, for humans, only.

        As a result Pseudocode omits a lot of things that compilers need -- declarations, correct syntax, horrible details, predefined commands, etc.

        How do you type Pseudocode

        You can use any word processor or editor.

        I often put my Pseudocode in a comment at the start of a function with the heading: Algorithm.

         /*Algorithm
         	1. Open data file
         	...
         */

        When is it worth writing Pseudocode

        Any time you are not sure how to code something.... write it in strict English first and then translate it by hand into C++ or a real code.

        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
           		object.function(data)
           		lengthOfStr = str.length();
        3. other functions mustn't be applied to object.
           		diagonal=sqrt(x*x+y*y);

        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.

        The double equals is a test to see if the two sides are equal. It mostly appears inside ifs, whiles, fors, etc. It returns a bool value of either true or false

         		if(answer=='y')

        The single equals sign is used to assign a new value to a variable. Here is the format for an assignment statement:

         		variable = expression ;
        It evaluates the expression and puts the result into the variable.

        It is quite legal to put an assignment inside any other statement because it returns a value -- the value that was assigned to the variable. So you can find things like this

         		sum=sumsquares=0;
        and it will compile and assign the 0 to two variables (useful!). But also this
         		if ( a = 24 )
        which will compile, assign 24 to a and return a non-zero value of 24 which the if will interpret as true. This is often a bug..... but some master C++ programmers use an "=" in a condition to great effect.

        How long a chain of else-if can you have

        As long as you like.

        Why use setprecision

        We use this to make the output has a certain number of decimal places. For example money usually has two deimal places, only.

        Example setw

      13. setw(n)::iomanip="Set width of next output to n".

        What is ASCII

      14. ASCII::= See http://cse.csusb.edu/dick/samples/comp.text.ASCII.html

        What is type char

        This is a "golden oldy" of computing. C++ inherits a special data type that is like an integer but only big enough to store a character -- in most cases an ASCII character. A character (roughly) is what is sent to the computer when you tap a key once. The constant characters are shown in a program with single quotes, by the way. You can do arithmetic on chars. You can assign and test chars. They often appear in a switch like the next one.

        Give an example of a switch

         		switch( answer )
         		{
         		  case 'Y':
         		  case 'y': //handle Yes....
         		  break;
         		  case 'N':
         		  case 'n': //handle No...
         		  break;
         		  default: //handle unexpected answer
        		}

        When should we use the default case

        All good switches have a default case.

        What is cin.get()

        This is an expression that sends the "get" message to the cin object. When cin has get() called it takes the next character from the input and returns it as a value of cin.get(). BUT if there is no next character then it returns EOF.

        Explain EOF and character input

      15. EOF::acronym="End Of File", term used thru out computing.

        C++ has roots in the time before standard character codes -- when each company had their own way of signaling end of file. This was when C was young and didn't know that it would give birth to C++. The C people had a clever idea. Not intuitive -- clever. They decide that when you tried to read a character from an input stream you would be given an int value. If this value represented a character (typically in range 0 to 255 of ASCII) all was well. If the stream was ended then the value '-1' (negative one) would be returned instead.

         		int input=cin.get();
         		if(input!= -1)...

        In the input/output libraries they defined a constant called EOF equal to minus 1. This made code a little easier to read.

         		int input=cin.get();
         		if(input!=EOF)...

        When the standard was written it was decreeed that EOF could be any int that was not in the character range. So, we dare not write "-1" when we should have written "EOF". Some new library may use -42!

        Why is grade or cin.get() an int

        There was and is no common end of file char.

        If character input is put in a "char" you can not determine if the end of file has arrived. It always looks like a char. By using an int we have at least one extra value we can use to signal end of file.

        Explain line 60 on page 209

         		while ( ( grade = cin.get() ) != EOF )
        This is a common cliche -- it does these things:
        1. Get the next character from cin (if any).
        2. If there was a character put its code in grade. If not, put EOF in grade.
        3. Test if grade has been set to EOF or is it a character
        4. If not EOF enter the loop.
        5. Elsejump to the end of the loop.

        This is what Lewis Carrol would call a "portmanteu" it combines several functions into one statement. This is not normally a good idea, but this one has been used in thousands of programs and so you can trust it.

        Meanwhile: keep a copy of a loop like this so you can copy it into your own programs. For example: [ kitten.cpp ] , the little 'copycat' command.

        Is there another way to input characters

        Yes. There is a different way to get a character from an input stream:
         		char c;
         		while( cin.get(c) ) ...
        Notice: we input the character (if any) into a char, and the command itself returns True if OK and false if not. To see how this works go to [ copy.cpp ] , a version of kitten.

        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() )
         		   message.goesTo("silicon.cse.csusb.edu");
         		else
         		   message.goesTo("mailer.csusb.edu");

        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).

        We have if and else clauses, is there a then clause

        No.

        Have there been calls for other control structures

        Yes. But they haven't survived the consensus. When an idea has lots of support it gets put into a language like C++.

        Indeed the tendency has been to reduce the number of control structures.

        One thing -- we have three or four statements (break, raise, goto, return,...) which modify the standard behaviors of the three structures. More later in this class and/or CS202.

        The number of structures is pretty much standard these days.

        Can you prove that only Sequence + Selection + Iteration are needed

        The proof takes several pages and the use of Boolean variables (later). You can find it by following this link [BohmJaccopini66] and (on campus) to the Assoc Computer Machinery's digital library at [ 355592.365646 ] (off campus -- sign into library with your Coyote ID first).

        Other than if and else is there another way to check a condition

        We use switch to choose between a set values. The rest of the control structures give you loops rather than choices.

        There is a function in the <cassert> library that can checks is a condition is true, and if not, aborts the program. For example if I'm about the calculate the square root of an unknown number x then I should put this command first:

         		assert(x>=0);

        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:

         		if(x<0)
         		   cout <<"x is negative\n";
        VS
         		if(x<0)
         		{
         		   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 an if select several lines without using braces

        NO!

        Can you use while for anything except repeating statement

        I don't think so.

        Can you put while inside a while

        Yes.

        You can any control structure inside another one... and so on. Example in lab05.

        Do if-else and switch work the same way

        No. If-else is always 2 way and switch is n-way. The machine code is quite different. If-else has a two way condition branch command (BNZ for example). A switch is translated by computing the address of the next statement from the value in the switch.

        However, you can fake an if_else with a case:

         	switch(condition)
         	{
         		case true: true_part; break;
         		default: false_part;
         	}

        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.

        Can you make C++ start executing the last statement in the program

        No.

        The best you can do is to start with a command that jumps, somehow, to the last one. But C++ programs always start executing at "main".

        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.

        Answered Questions on algorithms and control structures

          When to use the different kinds of loop -- while for do-while

          Everybody agrees that you must use the for loop for counting and scanning through data. The while is more general purpose and best at iterative algorithms.

          I personally think you should never use the "do-while". Just an opinion based on 30 years experience.... I used them from 1964 through to 1978 and then abandoned them and started to have fewer bugs.

          Pitfalls of the do-while

          Basically having to write code in the do-while that works whether or not the condition is true.

          Also changing a problem with zero-repetitions to one where there must be at least one repetition.

          What is the purpose of Pseudocode

          To be able to think about a solution of a problem without worrying about the C++ syntax.

          What is the reason for nested control statements

          Because we have nested problems, of course:-)

          Seriously: In the lab I showed you a program that output a grid of symbols. The structure is (

          1. row (
            1. item item item item ...
            )
          2. row (
            1. item item item item ...
            )
          3. ...
          ) so the only wise way to produce the output is a nested loop.

          In general most probems demand a complicated algorithm to solve them... one where a selection has to be repeated, or where we have to choose between two loops. We can have solutions where a repeated pattern has to (itself) be repeated.

          Is there an if-if structure

          Example
           		if(if(.....) )....
          No.

          However this is OK

           	if(....)
           	{
           		if(....)
           		...
           	}

          If you repeat a loop does it restart

          Yes.

          If you use return in a loop does it terminate the loop

          Yes.

          When combining small programs into a large one do you modify the variables

          Yes. You also can put the parts between {braces} and then refactor out the shared variables:
           	{ declare shared
           		{ declare local only
           		}
           		{ declare local only
           		}
           		{ declare local only
           		}
           	}

          The best way to combine small programs is to make them into functions and call them as needed.... coming up next.

          Is the member function determineClassAverage a C++ keyword

          No. In fact, only keywords that are operators can be redefined as member functions. Don't do this in CS201!

          Is the member function determineClassAverage assigned a value

          No. Functions are not assigned values... you must define them. So we need to include a definition like this somewhere in our compilation:
           	void GradeBook::determineClassAverage()
           	{
           		//whatever
           	}

          Should I use ++ and -- rather than writing the assignment out

          Yes! Don't forget it is simpler to type
           		myLongNamedCounter++;
          than
           		myLongNamedCounter=myLongNamedCounter+1;

          Pre and post increment operators


          Table
          BeforeOperationAfter OperationValue returned
          v is v0v++v is v0+1v0
          v is v0++vv is v0+1v0+1
          v is v0v+1v is v0 v0+1
          v is v0v--v is v0-1v0
          v is v0--vv is v0-1v0-1
          v is v0v-1v is v0 v0-1

          (Close Table)

          The wise programmer uses "++" and "--" very simply to add and subtract 1 like his

           		v++;
          and avoids complicated trickery like this:
           		v= (++v) * (v--);
          which takes a lot of thought to get right and even more thought to figure out. Indeed sometimes the result is not specified in the C++ standard so the results are unpredictable.

          Do assignment operators help or just be confusing

          Both. It depends on experience and the precise use. Many people use them and as a result you have to be able to read them.

          Usually it does not make much difference. But when you have a long variable and want to add 2 to it:

          	myObject.forExampleAttribute0+=2
          it is too easy to mistype the expanded version:
          	myObject.forExampleAttribute0= myObject.forExampleAttributeO+2

          If output shows an object to have value zero does it mean it wasn't allocated a value

          Not really, it is easy for a variable to become zero as the result of a complex calculation.

          Also -- there is no guarantee that ints and doubles are set to zero initially.

          Can you set a repetition to terminate at any value

          Yes.

          Is it better to use a merge symbol in UML for multiple activities

          When the UML activity diagram or flowchart shows a choice of two or more alternatives... it should show the end of the selection with merge "---<>--" symbols.

          What is the purpose of a sentinel symbol if it is not acceptable value

          It's value is that it can not be used as input to the algorithm and so it can be used to signal the need to move on to something else.

          How does float differ from double

          Floats don't use as many binary digits, are more approximate, and cover a smaller range of real numbers.

          Examples of conversions

          [ convert.cpp ]

          Explain implicit and explicit conversion

          In C++ you can often convert data of one type to another type -- for example converting an integer into a double. If you use a "cast" then it is explicit.

          In an implicit conversion, you allow the compiler to choose a conversion from one number type to another when necessary.

          Notice that if you write

           		double answer = 1/2;
          the division is int division and so answer is set to zero. However, if one of the divisors was a double
           		double answer = 1/2.0;
          then we get answer set to 0.5. Neither does "double(1/2)" work. The division is done first (using int division) and then is converted to double. :! As a rule it is wise to use explicit conversions.

          How are cast operators used

          These force numbers from one form to another: double to float to int to char. The old fashioned notation was to use the target type. So to find the character whose code is 32 we write:
           		char(32)
          (in ASCII a space character). Similarly to get an accurate average from the sum of a number of int's we used to write:
           		average = double(sum)/number;
          This still works but is deprecated (jargon for: "will not work forever").

          The more modern and complex form is shown below:

           		average = static_cast<double>(sum)/number;
          this should continue to compile and run correctly even if the standard changes. And so this is the form you should use:-(

          How can I convert numbers to strings and strings to numbers

          I've dug up a couple of advanced types of objects "stringstreams" that do the job if you need it in a project, for example. Here [ stringnumbers.cpp ] is a program that demonstrates how to use a couple of functions "convertDouble" and "convertToDouble" that are defined in [ stringnumbers.h ] that you can download and #include in any of your programs.

          Similar code can handle other numeric data and let you choose the formatting.

          How do you output numbers to only 2 decimals

          Use an IO Manipulator like this
           		cout << .... << setprecision(2) << ....;

          [ ../examples/giomanip.cpp ] [ ../examples/iomanip.cpp ]

          This changes the format of doubles for the whole prgram.... until you change it to some other precision.

          Avoiding infinite loops

          The only way to avoid infinite loops is to think. You must be sure, or better, must have proved that each time through the body, you are closer to the terminating condition. For example, if you are counting up, you condition should be counter < some_limit. If you are going down then the condition will be counter > some_value. Avoid using equality tests, by the way, in case the variable jumps over the limit. This also stops you type variable=limit when you want variable==limit.

          The example in the book showed the need for braces {...} to include the commands that change the controlled variable in the body of the loop.

          It is important that you understand the syntax of loops and use braces when needed. Indeed I tend to put them in in every loop, just in case.

          But, there is no replacement for thought when coding loops and selections!

          Why can uninitialized variables lead to errors

          Because 'int's and 'double's are not set up to be any particular value. So if you are adding up data in an uninitialized variable the results are unpredictable, and probably wrong.

          How do I make sure the user has given me one the small number of numbers I expect

          This is a Data Validation problem. Let us assume that the user must input either 1, 2, or 3. Also assume that the user know enough to not input anything but an integer (not Roman "III", or a real number "1.234". Then we need to (
          1. Input a number
          2. if the number is 1 it is valid
          3. else if the number is 2 it is valid
          4. else if the number is 3 it is valid
          5. else it is invalid and the user should try again.
          )

          This looks like a loop -- but how can we check the loop condition?

          Here is a standard way to tackle it using the tools covered in the course so far.

           	int valid = 0; // 0 means invalid, 1 means valid
           	while(valid==0)
           	{	cout << "Input either 1, 2, or 3: ";
           		cin >> number;
           		if (number==1)
           			valid=1;
           		else if (number==2)
           			valid=1;
           		else if (number==3)
           			valid=1;
          
          
           		if(valid==0)
           			cout << number << " is invalid\n";
           	}
          Using Boolean Expressions and variables from Chapter 5 makes this much easier!

          Why do you not place a space between a unary operator and its operand

          It looks better:
           		-3.2 * y + -x
           		- 3.2 * y + -  x

          Can you set a string equal to a variable like string=variable+variable

          Only if the variable are string variables. C++ does not convert numbers to strings.

          What about this nested if...

           	if(x<10)
           	if(y<10)
           	cout<< "The answer is less than 10";
           	else
            cout<< "The number is greater than 10";
          First match the else with the previous unmatched "if". And insert braces and indents in the resulting if-else:
           	if(y<10)
           	{
           		cout<< "The answer is less than 10";
           	}
           	else
           	{
            	cout<< "The number is greater than 10";
           	}
          Next put {} around the above and reassemble the whole thing
           	if(x<10)
           	{
           		if(y<10)
           		{
           			cout<< "The answer is less than 10";
           		}
           		else
           		{
            		cout<< "The number is greater than 10";
           		}
           	}
          Now we can figure out what it "means" or does, may be an activity chart may help

          [activity chart of code above]

          I also find that putting the possibilities in a table helps me understand complex logic:
          Table
          Condition
          x<0TTF
          y<0TF-
          Action
          Output <0X--
          Output >0-X-

          (Close Table)

          Is there a way to put a function in loop and have it coming out not satisfying the condition

          While-loops repeat until a condition is false. If you want the reverse use the "not" Boolean operator like this
           		while( not ( condition ) ) ...

          If you want the condition to repeat the loop to depend on something that happens in the loop.... then use a variable to remember what happens like this:

           	int condition=1;
           	while (condition)
           	{
           		...
           		if(....)
           			condition=0;
           		...
           	}
          Using a Boolean variable (next chapter) helps clarify this.... so do Boolean expressions (using not, and, or).

          What is the difference between a controlled repetition and a counter controlled repetition

          The presence of a counter -- a variable that is initialized before the loop, tested at the start of each repetition, and either incremented or decremented at the end of each repetition.

          When defining a function for a class when are two colons used

          Inside the class you don't need the colons -- the compiler can see which class the function belongs to. Outside the class you need the colons to tell the compiler which class the function belongs to.

          Is it better to keep all class definitio0n in one header file or in multiple header files

          As the problem gets more complex and solution demands more and more classes the better it is to have multiple files -- one per class. A rough guide, when you find yourself repeatedly scrolling up and down the file from class to class... it would be wise to spit up the file.

          What is the importance of attributes

          Attributes reflect the properties of real objects. Most problems involve object with many properties... and so solution that have many attributes.

          How do indicate the initial value of an attribute in UML

           		name : type = initialValue

          How do indicate the initial value of an attribute in UML

          You have to put the initialization into a constructor.

          How many classes should you have

          On for each type of object in the problem. You need to think about what differences are important and so need to appear in code.

          How many classes can you have

          There is no limit.

          How many attributes can you

          As many as you want. No limit.

          Do attributes in the model reflect the variables in the program

          They represent the named data field in the classes.

          Why does the book always use the ATM example

          (1) To show you a realistic project from soup to nuts. (2) Thinking up a new example is difficult. (3) So you don't have to learn about a new situation in each chapter.

          How do develop an error message when the wrong data is input

          Very carefully! You end up with a lot of if-then-else logic and some loops that ask the user to try again.

          How is UML Boolean is equivalent to the bool C++ type

          By design. The difference in name comes from C and a liking for short names in typed code.

          To types of data are equivalent if the same operations give similar results.

          Explain boolalpha

          This is only used in quizzes, exams, and examples.

          It is part of <iomanip> and uses namespace std. So you may need

           	using std::boolalpha;

          Normally, when you output a bool it displays as either 1 or 0. 1 is true and 0 is false.

          After boolalpha you get a truncated form of "false" and/or "true".

          Use it when you want to display bool values/conditions as "t" or "f". This is rare -- mainly: debugging, classroom exercises, lab work, examples in books, ... Mostly it is better to show spell out what the condition means with something like this

           		cout << .... << (single? " Single " : " Married ") << ...;

          Are break and continue only used on loops

          The "break" is used with switch. The continue only with loops.

          When to use negation rather than the negated relation

          When you want the opposite of a complex condition
           		if ( ! (x>3 or y <2) )
          Note -- the "!"/"not" operator doesn't cost anything much in time or space3 and saves brain power.... which is more expensive.

          When the condition is not based on relations you can not just change == to != etc.. For example

           		if(!(n%p)){ /*n is not divisible by p*/}

          As an example in the lab you met:

           	while(cin >> value){....}
          which reads each value until the end of file (or when some one types a vlaue that doesn't fit). The cin>>value is a combined command and condition. You can test for the presence of data and also get the first one:
           	if(!(cin>>value))
           	{
           		cout << "No data! \n";
           		return 1;
           	}
           	double max=value; double min=value; double sum=value;
           	double sumsquares=value*value;
           	while(cin>>value)  // proces the other values
           	{
           		...
           	}

          Why can we only combine the structures using nesting and stacking

          Because it is not clear what it means.... and because C++ syntax won't let you do it.

          Why are nonzero values treated as true

          The designers of C thought that zero ( in binary: all the bits a zero) was clearly the way to encode "false". They threfore decided that all other values (which would have a non-zero bit somewhere in them) should be "true" in a condition. It turns out that this was a smart choice making code simpler and faster in a lot of programs.

          The alternative was to choose a value (say one(1)) to mean "true" and add a run time error if ever a condition was neither 1 or 0. This would make a lot of programs more complex and a bit slower.

          bool forms of negative numbers

          These are treat as "true" because they are nonzero.

          When can you use logical operators && || !

          In any condition -- in if, if-else, while, for, ..., and do-while.

          You can also use then to give values assigned to bool variables (flags):

           	bool flag = false;
           	...
           		flag = (n>2)&& !(n%p);

          Can you write the exclusive or function in C++

          Yes. The exclusive or is true when two Boolean variables have different values. And C++ is happy to apply '==' and '!=' to bools:
           		bool a, b, c;
           		....
          		c = (a != b);

          "Believe it or not."

          Is using && || ! vs and or not just a personal preference

          These days yes. In some older compilers we don't have and/or/not.

          Is bool like truth tables

          Yes.

          Indeed one way to design a logical (bool) expression is to write out a truth table first and then code it using the rows that are true...

          Why logical negation

          It saves thinking!

          Why can't the compiler reject assignments in conditions

          Because many programmers, in the last 30 years, have put assignments in conditions with care and great success. A classic maneuver is
           		while ( (data = cin.get()) != EOF )....

          Explain UML State Machine Diagrams

          State Machine diagrams are elaborated from the "finite state machines" invented by the very first computer scientists to model brains, circuits, and computers. They are used in software engineering, in networking, and in computer science theory.

          They show how the state of something changes under the influence of events. For example, a door is either open or closed. These are the two states for a door (we ignore "half open") for this example. Suppose we are talking about an elevator door, then the events happen when buttons are pushed. There are buttons labelled "open" and "closed". As a result we get the first diagram below that describes how the door behaves.

          Here is another example. I have a ball point pen. If the refill is "out" I can write with it. If the refill nib is "in" it is safe to put in my pocket. In this case there is a single type event "click" when I click the button on top. Sometimes the nib comes out and sometimes it goes in.... See the second state machine below.

          State machines can have more than 2 states. They can have any finite number. In my inlaws house there was a lamp in the bathroom. It had a pull chain. It had for states:

          1. Light off, heat off
          2. Light on, heat off
          3. Light off, heat on
          4. Light on, Heat on

          By pulling the chain you could get to any one of these for states -- see the third state machine below.

          [Three state machines]

          For a couple of more practical examples try [ ../samples/uml0.html#State ]

          State machines are a marvelous way to analyse dynamic problesm, complex protocols, and design intricate solutions that work.

          Explain lvalues and rvalues

          Ever since the ancient language of BCPL (1970s) we have distinguished the kind of value that can appear on the left of an assignment from the kind of value that is normally needed on the right hand side of an assignment.
           		lvalue = rvalue;

          We say that a variable has an lvalue and an rvalue. The lvalue is the address in the computer that is given to the variable by the compilation process. It indicates where data is found, and where it is put. This is the value that is needed on the left of an assignment. This is also what is needed in cin statements -- we need a place to put things.

          A variable has an address of a piece of storage or memory. This piece of memory holds the rvalue of the variable. When we put a lvalue on the right of an assignment we get the data that is in the memory -- not the address. This also happens in cout statements where we need a value to be printed.

          So far the only rvalues you have met have been ints, doubles, floats, strings, and so on. None of these is the address of some data. So it is not a valid lvalue. You can not compile

           		3.14159 = 17;
          for example. It is trying to change a constant! So this is forbidden.

          In C++ we have an operator that explicitly gives the lvalue of a variable where we would normally get its rvalue.

           		cout << & variable;
          In CS202 you meet a kind of varaible that stores addresses -- and these can get confusing.... they are called pointers.

          How is Boolean used in source code

          (1) Conditions return the two Boolean value: true and false.

          (2) You declare Boolean variables like this

           		bool ok;
          (3) We can combine Booleans like this
          Table
          ExampleMeaning
          not(A)negation, opposite value, true<->false
          (A)and(B)conjunction, true only if both are true.
          (A)or(B)disjunction, true if one is true or if both

          (Close Table)

          What is a Boolean attribute

          A Boolean attribute is a true/false property of an object. An example for a Pet or a Person might be:
           		alive : Boolean
          and we would code this as
           		bool alive;
          inside class Pet or class Person... or even both

        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

      16. 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:
      17. 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

         		cin.fail()
        is a good test. You can also test
         		cin >> blah
        as it is executed and inputs data:
         		while(cin>>number)
         			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?

        Yes.

        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 which is often used in this case:

         		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.

        Can you change the value returned by a function

        If you store the returned value in a variable,
         		value = function (data);
        then you can do anything you want with it.

        What is an actual parameter and a formal parameter

        A function call contains the actual parameters:
         		function ( actual1, actual2, ...)
        The actual parameters can be expressions (normally...). They must give values of the right type to fit the formal parameters.

        The function definition has the formal parameters

         		type function (type formal1, type formal2, ...){...}
        Formal parameters are variables. They are never constants or expressions. They are place holders for the actual parameters.

        Why must I type double twice in function parameters

        In normal decalarations you may write
         		double x,y;
        and get two doubles. But in a function header
         		type foo(double x, y)
        is an error. I don't know why. But it is an error.

        By the way.... it is better style to have one variable per declaration as well!

        How do formal and actual prameters get matched up

        The formal and actual parameters are connected up one-to-one by the compiler. Each actual will be evaluated and passed to be the initial value of the formal parameter. The formal parameter (normally) then acts as a local varaible.

        Do the parameter types have to match precisely

        The compiler can convert numeric data as part of the matching process. This is called coercion because it is a forced conversion or cast.

        Thus the call

         		foo(1)
        will match all of the following
         		type foo(char c)...
         		type foo(int i)...
         		type foo(long l)...
         		type foo(double x)...
        I'm not sure about the rules when there are many matching parameters!

        If the actual is a string and the formal paramer is a string is it converted properly

        No.

        Suppose we have

         		void foo(int n){ cout << n+1 <<"\n"; }
        then
        		foo (string("124"));
        will not compile.

        More confusing is

         		foo ( "124" );
        which prints one more than the address where "124" has been stored, believe it or not. This is a historical accident.

        Why match one-to-one between actual and formal

        It works and is simple.... suppose we have
         		foo( 123, 456, 789);
        and
         		void foo( int x);
        how would you match the 3 actuals to one formal? And do you have the same idea as everybody else?

        Can a function change its formal parameter

        Yes.

        Can a function change the value of an actual parameter

        Only under special circumstance do the actions inside a function have any effect on the actual parameters given to it in a call. The rules are
        1. The formal parameter must be declared as a reference parameter [ 15.html ]
        2. The declaration/definition must therefore have an ampersand in it: type & variable.
        3. The actual parameter must be a variable of the same type.
        4. The call is just the same as any other call.
        5. The two variables (in the call and in the definition) are treated as a single variable.
        6. Changes to the formal parameter instantly update the actual parameter.

        More next time.

        Why doesn't cmath have any objects

        It predates OO programming (1970's).

        As a result you write

         		y = sin(x);
        not (Java):
         		y = Math.sin(x);
        I think this is convenient!

        As a rule, classes of objects are created in libraries when there is a clear consensus on an abstract type of data and how it behaves. Strings are an example, streams are an example. Later: vectors.

        As a rule, you should create classes for your project when they mirror real world object. In the ATM example: ATM, Account, Withdrawal, ... and so on. In the problem of grading: GradeBook...

        Does any C++ library have secant cosecant cotangent

        No. You have to do the division your self. You can always define your own function if you want:
         	inline double sec(double x) { return 1.0/cos(x); }

        Does the STL vary

        They are the same for each ditor you use. They may change from machine to machine, and will change operating system to operating system. They als change form time to time -- irritating but true.

        However they all tend to stay close to the standard... and that only changes ever 11 years or so.

        Is there a library that has a function that will find the minimum or maximum of an unknown number of numbers

        Not like this:
         		min( a1, a2, a3, a4, a5)

        However if the values are placed, or exist in a container then there is are functions in the STL which will search the container for the minimum and maximum elements:

         		min_element( vector.first(), vector.last() )
         		max_element( vector.first(), vector.last() )
        These are not in CS201.

        How can I find out what a function like ldexp is used and what it does

        I've found the following source [ ldexp.html ] for that function with links for many others.

        Explain function overloading

        You can give the same name to different functions as long as their parameters are of different types. When the compiler matches a function call with a function declaration it looks at the name of the function and the types of the actual parameters. It looks for a function with the same name and formal parameters of the same type.

        It is rather like the way that words in natural languages have different meanings depending on the context... TBA

        Only do this if the functions have similar purposes.

        Are the things in libraries global and what does this mean

        They are either global or private (hidden and unusable). Global things can be used any where in the program. Here are two example global variables from <iostream>
      18. std::cin
      19. std::cout

        <cmath> defines global functions, <string> defines global operations and the class string, etc.

        Why do I have to write a constructor

        Because it initializes variables. Uninitialized variables are bugs waiting to happen.

        It pays to think about how a new object is set up. A constructor describes this. The good news.... there are abbreviations for writing constructors that the book has not mentioned yet.

        How are global functions reused in other files

        The simplest technique is to put the whole definition in a file and "#include" it in the files that need to reuse the function.

        You are not required to do the following as part of CS201.


          A more complex but efficient technique (it reduces the compilation time...) is to split the functions file into a header file and a code file:
           		function.h
           		function.cpp

          The header file has just the function prototype

           		type function(formal parameters);

          The code file

           		#include "function.h"
           		type function(formal parameters) { body }

          You then pre-compile the code file:

           	g++ -c function.cpp
          which creates a "function.o" file.

          Somebody who want to use your function needs a copy of "function.o" and "function.h" and puts

           		#include "function.h"
          in their program. The must also put "function.o" in their compilations.

        You are not required to do this as part of CS201.

        Do you have to put a function in a header file

        No you can put it in the file that needs it -- but this only makes sense if it is only needed in that one file. Otherwise it pays to put it in a special file and use the above technique to include it where it is needed.

        Can you omit the int in unsigned long int etc

        Yes.

        When to use enum

        See ./15.html

        Did programmers invent viruses

        Only the electronic ones. This is one reason why computer science degrees include an ethics course. We have a responsibility to practice out skills and talents for the good not the bad.

        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:

         		Lunchp.
        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
         		f();
        changes glob.

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

        Why are side-effects a bad idea

        Experience!

        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

        Perhaps....

        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
        Table
        FunctionReturnsEffect
        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

        (Close Table)

        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:
         		object.add(20);

        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
                 Botting::Richard.

        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:
                 MyClass::MyClass(){}
        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?

      20. 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:
         		private:
         		Type data;
         		...
         		public:
         		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:

      21. 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.

        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.

        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?

        No.

        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:
        Table
        LanguageClaim
        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.

        (Close Table)
        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

         		end_of_file
         		bad
         		too_big

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

        Is a dangling else attached to the wrong if?

        Yes.

        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

         	if(P)
         	    if(Q)
         	      A
        (with no elses) is simpler as
         	if( (P) and (Q) )
         	      A
        (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 )
        or
         		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:

         	switch(Expression)
         	{
         	   case Value:
         	      DoSomething;
         	   break;
         ...
         	}
        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:
         		if(Condition)
         		{
         		   TruePart
         		}
         		else
         		{
         		   FalsePart
         		}
        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

         		if(Condition)
         		{
         		   TruePart
         		}
         		else
         		{
         		   if(anotherCondition)
         		   {
         		      FalseTruePart
         		   }
         		   else
         		   {
         		      FalseFalsePart
         		   }
         		}
        Then we simplify the syntax to
         		if(Condition)
         		{
         		   TruePart
         		}
         		else if(anotherCondition)
         		{
         		   FalseTruePart
         		}
         		else
         		{
         		   FalseFalsePart
         		}

        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?

        No.

        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 )
         		  {
         		     body
         		     increment
         		  }
         		}
        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?

        No.

        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
         	loop
         		Process Row in the Table
         		loop
         			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
         			'?'
         			'a'
         			'\n'

        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
        is
         			'c'

        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:
      22. not( p and q) == ( (not p) or (not q) )
      23. 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);
         		object.doSomething(data);
         		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
      24. 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

        Programmers.

        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

        No.

        Are there any confusing expressions

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

        Warning: Look out for expressions like

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

        Also

         		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

        Yes.
         		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

        No.

        What is the int main()

        In some books (and my old examples) the main function is always written like this:
         		int main()
        rather than
         		main()
        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
        Table
        ijk
        2417

        (Close Table)
        Then after

         		k = ++ i;
        we have
        Table
        ijk
        343

        (Close Table)

        If we again start with
        Table
        ijk
        2417

        (Close Table)
        Then after

         		k = i ++;
        we have
        Table
        ijk
        342

        (Close Table)

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

        (Close Table)

        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

        Yes.

        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:
        Table
        Short formLong form
        x -= e;x = x - e;
        x += e;x = x + e;
        x *= e;x = x * e;
        x /= e;x = x / e;
        etc.

        (Close Table)

      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(A)
         	   B
         	else
         	   C
        
        
         	if(D)
         	   E
         	else
         	   F

        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;
         	   }
         	   else
         	   {
         	      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;
         	   else
         	      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
         		pow(x,y)
        using the <<cmath>> library. The mathematical exponential function e to the x can be written
         		exp(x)
        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)

        Tradition.

        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++

        6

        How many different logical operators are in C++

        3: not, and, or. See below.
        Table
        pnot p
        truefalse
        falsetrue

        (Close Table)

        Table
        pqp and qp or q
        truetruetruetrue
        truefalsefalsetrue
        truetruefalsetrue
        falsefalsefalsefalse

        (Close Table)

        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
        Table
        pqp<q
        falsefalsefalse
        falsetruetrue
        truefalsefalse
        truetruefalse

        (Close Table)

        What does bool mean

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

        Where do bool and get their names from.

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

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

        Are there other types we will learn about in class.

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

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

        When is bool used

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

        Why does not have a different priority to and and or

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

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

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

        What does bool actually do

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

        Is a while statement a kind of loop

        Yes.

        Is a while statement the same concept as a loop

        No -- some loops are not while loops.

      Questions

        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

         	while(true)
         	{
         		A
         		if( B )
         		{
         			C
        		}
         		else
         			break;
         		D
         	}
        You can, instead use a bool flag.
         	bool ok = true;
         	while(ok)
         	{
         		A
         		if( B )
         		{
         			C
        		}
         		else
         			ok=false;
         		if( ok )
         		{
         			D
        		}
         	}
        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 )
         			fabs=-x;
         		else
         			fabs=x;

        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

        No.

        Is there a limit to repetitions in a while loop

        No.

        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!

      Questions

        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;
         	}

        Table
        Statement\Variablesticout
        t=00??
        i=000?
        i<5
        t=t+i00?
        cout000
        i++01
        i<5
        t=...11
        cout...111
        i++12
        i<5
        t...32
        cout323
        ...
        cout10410
        i++105
        i>=5

        (Close Table)

        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

        Practice.

        What does ! mean

        not

        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

        Yes!

        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!

        How do you copy a vector

        Use the STL "copy" algorithm or use a for loop [ copy.vector.cpp ] for example.

        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...)

      Questions

        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
        1. Evaluated the condition C;
        2. If the result is true then Execute all of B and go back to step 1.
        3. 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.

         file...............: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

        Yes.

        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

        Yes.

        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!

      Questions

        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
         	if(A)
         	{
         	   while(B)
         	   {
         	      C
         	   }
         	}
         	else
         	{
         	   D
         	}
        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
        becomes
         	while(A)
         	{
         	   if(B)
         	   {
         	      C
         	   }
         	   else
         	   {
         	      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
         		example[0]
        The 115th item
         		example[114]
        The last item
         		example.last()

        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.
        2. 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.
        3. If the next two characters are a backslash followed by a 0 then translate the string from octal to binary.
        4. If the next three characters are a backslash followed by an x and a 0 then translate the string from hexadecimal to binary.
        5. 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'...
         			1101101
        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:
        Table
        TheoryC++
      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. (Close Table)

        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

        No.

        Can you put if and while inside a function

        Yes.

        Can you define a function inside a function

        No.

        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

        Yes.

        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

        Yes.

        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.

      Questions

        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 in below. If you first add 0.5 it rounds to the nearest integer.

        You can use multiplication and division by 10,100,1000, ... to shift the decimal point 1,2,3,... places and then round the result. For an example, of rounding to two places see [ rounding.cpp ] for an example.

        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

        Don't!

        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>>

      Questions

        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:
        Table
        BitsUnsigned #Signed #Day of Week
        00000Sun
        00111Mon
        01022Tue
        01133Wed
        10044Thu
        1015-3Fri
        1106-2Sat
        1117-1ERROR

        (Close Table)

        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>>

      Questions

        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++)
         		{
         			A;
         			if(C) break;
         			B;
         		}
        We can vanish the break like this:
         		bool unbroken=true;
         		for (i=0; i<N and unbroken, i++)
         		{
         			A;
         			if(C) unbroken = true;
         			else
         			{
         				B;
         			}
         		}
        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

        Nope!

        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
         		001010100111
        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.
        6. A loop that moves a pointer into terra incognita.
        7. 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 )
                         palindrome=false;
            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.cse.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
         		p1=p2;
        will change p1 to point to the same place that p2 points. Here is a picture of memory before and after:
        Table
        Commandp1p2
        -αβ
        p1=p2
        -ββ

        (Close Table)

        The command *p1=*p2 changes the place that p1 points to by the place that p2 points to:
        Table
        Commandp1p2αβ
        -αβab
        p1=p2
        -αβbb

        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.

        (Close Table)

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

      Questions

        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:
         		light=0;
         ...
         		light=1;
         ...
         		light=2;
        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;
         ...
         		light=red;
         ...
         		light=yellow;
         ...
         		light=green;

        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

        YES!

        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....

      Questions

        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++


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

        (Close Table)

        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

        Yes.

        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

        Yes.

        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)
         #endif
        (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

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

        The

         	#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)
         				G
        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
           !B;

        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:

         		somebody.pleaseCallMeBack(this);
        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;
        means
         		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.

        Is there a way to limit decimal places without using substrings

        The double length computations are always done to maximum accuracy.

        You can remove the decimal part of a double by assigning it to an integer.

         		int rounded_down = unrounded;

        Thestandard technique for propper rounding to the nearest is to add 0.5 first

         		int rounded = unrounded + 0.5;

        To round to, say two paces, you shift the decimal point before you round and then shift it back again:

         		int rounded = (unrounded * 100.0)+0.5;
         		double result = rounded / 100.0;
        For a running example, see [ rounding.cpp ] in this web site.

        Their are several more advanced techniques in C++. The cmath library has two or three helpfule function for rounding. I hope to cover these later.

        There are also some advanced nput/output manipulator functions for accurately formatting output to a specific number of places. This part of CS202 but here is a sample for formatting doolars and cents:

         		#include <iomanip>
         		. . .
         		//Suitable for a check protected monetary field
         		double dollars = 1234.45;
         		cout << '$';
         		cout << setfill('*'); cout <<setw(10); cout << setprecision(2);
         		cout << setiosflags(ios::fixed | ios:: showpoint);
         		cout << dollars <<endl;
        [ ../examples/giomanip.cc ] (old C++ code).

        What does separating interfaces do to the program

        It splits the program into pieces of code that can be worked on independently. If you are doing a team project (the norm in practice) you can give the separated parts to different people. The interface lays down the rules for their parts of the program to work together. They can then implement their parts in any way that works.

        Library classes are 90% hidden behind an interface. For example here is a simplified list of the "string interface" taken from our library: [ string ] (Plain text file). You can use these functions without worrying about what goes on inside the library.

        How does separating interface from implementation make my life easier

        If you work alone then it means that you don't have to edit and recompile massive files all the time. You work on one file and if needed recompile it, and then switch to another part of the problem and work on that.

        It is Ceasar's method: "Divide, and conquer".

        In a .h file why are function definitions replaced by prototypes

        So that you don't know the details of the function implementation.

        A prototype tells you how to call a function but hides (and delays) the details of what happens.

        A header file (like GradeBook.h) is shared, published information. By only putting prototypes in a header file you expose the right info for a client to use it without swamping the client with details.

        Do I always need a void displayMessage()

        No. Only when you need an object to display a message. Indeed many would argue that instead of display.... you should write string getMessage and use cout to do the output. They like to separate the user interface from the logic of the class. Then the class will not change if you get new input/output devices.

        Why do we always need an object to be in a consistent state

        Other methods in the object rely on the state being consistent.

        Any object which has member functions that leave the state in a strange state can not be trusted.

        Which functions are void functions

        The void functions may change the data in the object, but the do not return any inormation about the object's state/data.

        They are the "setters" or "set functions".

        Non-void member fucntions return data and so are report on the state of the object. They are also called "getters" or "get functions".

        Get functions should not change the state since this can lead to surprises. Good design always follows the Principle of Least Surprise.

        Why is there null character placed at the end of string literals

        The compiler doesn't store the quotation marks. It stores the characters with an extr null at the end and remembers where the string starts. Programs use the null to spot the end of the string.

        Strings in the string library are more complex internally, but they hide their techniques behind an interface.

        Should you use a set function to check some data

        A setter changes the data inside an object so this sounds like overkill. If you expect to need data validation without storing the result then you should code member functions that test the data:
         		bool validData(....){....}
        for instance. A bool is a value that is either true or false and can be used in conditions.

        Why do class names always start with a capital

        Mathematicians always represent sets using capitals.... and a class defines a set of objects.

        It is not part of the C++ language but it is part of the OO culture.

        Are if statements the only way to validate data

        No. There is a function assert in the <cassert> library that makes it very simple to reject bad data. Here is a sample of rejecting an index that is negative or too big:
         	#include <cassert>
         	. . .
         	   assert (index >= 0 ); assert (index <= SIZE-1);
        In general assert(condition) does nothing if the condition is true, and aborts the whole program if it is false.... generating diagnostics.

        Another, modern tool, for rejecting bad data is to use 'if' plus raising an exception. This is advance stuff....

        If you know string data will be longer than 25 characters why not make it bigger

        The question is: where do you stop? 255 characters? 1023 characters? As the limit grows the program needs more and more space for its data.

        The logic is the same with just the number changing:

         		if( p.size() > 25 )....
         		if( p.size() > 255 )....

        This example in the book goes back to the bad old days when you couldn't store a string without defining its maximum size. Running over this size leads te program into very bad behaviors including crashing the operating system and taking control of the computer! If you use the sandard string you don't have to worry about a maximum size: it adjusts.

        However, the point that you must always vaildate the data you have been given is still true.

        Why validate data

        Fewer bugs. In fact -- an easier life for the programmer.

        Are there more UML diagrams

        Yes - thirteen! In CS201 I'm only going to require you to draw class diagrams.

        Are there other kinds of class than the elided and normal variety

        Yes. "Templates" and "Stereotyped classes". We won't do much with these...

        How to compile and link programs on UNIX

        This command
         		g++ -c name.cpp
        will compile a C++ program called name.cpp into an object code.

        You do this for each ".cpp" file you have...

        You can link them into an executable program like this [ g++ -o executable *.o ] The "*" is a wild card. "*.o" is replaced by a list of all your object files.

        Why are role names important in UML diagrams

        A well chosen role name can make an association much clearer. It also hints at data members in the class.... more later.

        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;
         	  public:
         	    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...

        How do you mark the beginning and end of classes

         		class Name
         		{
         			...inside the class
         		}; // match brace to start of class.

        Is there a way of keeping classes together in compilation

        You can put them all in the same file... or you can write special commands for the compiler to assemble the files. You can automate this process using a "Makefile" and the "make" command in UNIX. Something similar is possible for IDEs and MS Visual Studio...

        When to use a function or a class

        Use a class to model real world objects. Use a function when you have a simple task with all its data provided at that time and no memory. Use a function is class if there is any data that must be stored between calls.

        When to use function overloading

        When you have two similar calculations with different types of data. For example adding to ints, adding to doubles, and adding two string.... are all shown with "+".

        The compiler will match the right (usually) function definition with each call for you.

        Why function overloading

        Few different names to worry about.

        How does a program use an identifiers scope

        Inside the scope the variable has a meaning. The compiler keeps a list of variable declarations as it reads the program and looks up each variable when it used in the list.

        What is the difference between global and static local

        The global has a scope equal to the whole file and any other file that decalres an "extern" variable of the same name. The static variable is private to the function/block in which it is declared. Both have a life time equal to the program. They are just accessible in different parts of the program.

        What is the difference between static global and global

        A global variable that is declared static has a scope equal to the file in which is declared. It can not be accessed form another file of data.

        Is there a limited time for information to be stored in an identifier

        The data is stored for the while life time of the variable. Global and static variables keep their values and meaning for the whole life of the program. Local variables and parameters in functions keep their values until the end of the function or block in which they are declared. Data members (variables in objects/classes) keep their values until their object is destroyed -- and the object follows the rules of its declaration.

        Do static local variable keep their value when the function returns

        Yes.

        When to use enum

        When you need a variable to have one of a fix number of values, and you have a ready made set of names for them. Examples might include
        1. Colors of the rainbow
        2. Days of the week
        3. Months
        4. Gears in an automobile

        Notice the two requirements: a fixed set + known names. Otherwise "enum" may act as a problem not a solution.

        In arrays and vectors -- what if I start my indexes at 1 not 0

        It works, you waste a little storage. I've done this.

        Can vectors store strings etc

        Yes. You can have a vector of any kind of object: int, double, char, string, even vector!

        What do lables do to a program

        Case labels are ok. Other labels are confusing.

        What is Randomization

        Any process that gives unpredictable results -- result that are unlikely to be correlated with other things that are going on.

        What are pseudo-random numbers

        These are numbers that appear to be chosen at random. Their function is to simulate real random processes like throwing dice, tossing coins, and shuffling cards. Very useful in games, statistics, and so-called Monte Carlo numerical methods.

        Whats with srand and rand!

        You always have two functions when generating random numbers. One gives you the next number. In C++ this is called "rand" and it has no parameters. The other function sets the random number generator to a particular internal number. In C++ this is "srand". It must have an parameter to generate the starting point. In C++ this is always done like this
         		srand(time(0));
        at the start of any program that needs random numbers.

        Unless you want to spend time studying random number generators... its best to treat them as magic -- learn the spells and recite them correctly (See the Harry Potter series).

        What does an enumeration do in a program

        It saves you remembering what a set of integers mean by giving them names.

        Can enumerations skip numbers

        Yes:
         		enum Example(START=17; MEANING=42};

        Can you increment by other than 1 an enumeration variable

        Yes.

        If there is a gap in the enumeration what does ++ do

        It gives a value that you did not list in your constants!
      1. . What is scaling Scaling is multiplying a set of related numbers by a constant to change their range of values while preserving the relative sizes. Like zooming in and out.

        What is unsigned for, why not use int

        Unsigned is used for compilers, operating systems, and working close to the hardware. Other than that you might as well use signed numbers.

        How much memory is assigned to registers.

        Registers are inside the CPU. Memory is outside the CPU. So: zero. But the size of the registers in the CPU depends on the chip.

        Explain the differences between auto register extern mutable and static

        The only one of these that you need in CS201 is "static". Nearly all variables you will use are "auto" -- which means stored on the runtime stack. They are created by a declaration and deleted when you exit the surrounding block.

        Static variables are created by the linker when the program starts and are deleted when the program terminates. If they are local variables declared "static", however, you can only access them in that block, even though they exist outside the block.

        Global variable are in the static storage, and if you declare them as "static" then they are hidden from other files. However, if they are not declared "static" then another file can use them by declaring an "extern" variable.

        Register variables are not really needed -- a good compiler does this automatically for you anyway. Even if you specify "register" the compiler can ignore it!

        As a rule.... don't use anything but local variables in CS201.

        Note: the meanings of these keywords when applied to data members in a class is related but not identical to their use inside a function. The life time of normal data members is equal to the lifetime of their object, for example. If you declare a variable as a "static" data member" then it is attached to the class not the insances of a class. There is a single variable, any function in the calss can use it, and its life is equal to the whole program.

        This is a complex set of distinction that we will review in CS202 and CS320.

        What happens if you don't put () after a function name

        It don't get a function call, you get the address of the compiled code that starts the function! So
         		printit();
        calls the function... but
         		printit;
        compiles and does nothing.

        Can a function inside of another function return values

        You can not just write a function declaration inside another one.

        But you can call a function, and return the result

         		return sqrt(myfunction(x));

        Clarify the difference between pass-by-value and pass-by-reference

        Download and run this [ calls.cpp ] it shows how pass-by-valaue transfers a value from an expression in a function call into a parameter.... that stays inside the function, but pass_by_reference acts directly on the variable that is given to the function.

        How and when to use call by reference

        (1) Use reference parameters when you need a function that changes the value of the variables it is given. (2) Use reference parameters to avoid copying large objects (and vectors). In this case add "const" to signal you won't change them.

        When returning a reference to a local non-static variable

        You return a piece of garbage. Seriously-- we call a piece of storage that has been given up for reuse as garbage. On exit the local varaible become garbage and you return the address of the garbage. This is not a good idea.

        .What is a function prototype A function prototype is just like that function header except it has a semicolon after it:

         		type name(parameters);

        It's purpose is to tell the compiler that such a function exists, and how to compile calls to it.

        The linker connects up the calls with the actual function declaration.

        In essence a function prototype is a promise that you will supply, sometime, a complete function that can be called.

        How are default parameters used

        They let you omit some values in a call. They are replaced by the defaults.

        If f has default values for its parameters can I write a call like this f(,,34)

        No. The omitted parameters are always at the end of the parameter list in the current version of C++. Perhaps later standards will allow this freedom, or something like it, since it is part of Ada.

        What is the difference between f(void) and f() in a declaration

        In C++ there is no difference. In C the second forms allows any parameters at all. In C++ you write this f(...), and have to use special libraries to handle an unknown number of undefined parameters. Using a reference parameter in a call is just like any other call.... but you can only give the function a variable. Constants and expressions are rejected by the compiler. The function needs a variable to work on...

        How is an everloaded function distinguished by its parameters

        The name and parameters
         		type name(parameters);
        are combined (this is called Name Maangling ) to give a longer name that contains both the name of the function and all the types of the parameters. It is complex and works without us worrying to much about it.

        When the function is called.... the values are matched to the right function. For example, [ overloaded.cpp ]

        What happens if overloaded functions have the same signatures

        The compiler rejects them (I think).

        How to use function overloading

        Don't worry about it! It just means that you don't have to think about keeping all the function names different. Make the name describe what it does and the parameters the data it uses.

        Can we use overloading and default arguments to recreate C printf

        By using the (...) you can get exactly the functionallity of printf! You will find it in the <cstdio> library. Try [ http://www.cplusplus.com/reference/clibrary/cstdio/ ] for details.

        What is the unary scope operator useful for

        Not much. Except when you have a local and a global variable with the same name.

        How big can you build arrays

        (1) how much RAM or primary memory can you afford?

        (2) The subscripts must be stoable as int's -- so less than 2^32 on a 32 bit CPU.

        Explain the differences between auto register extern mutable and static

        The only one of these that you need in CS201 is "static". Nearly all variables you will use are "auto" -- which means stored on the runtime stack. They are created by a declaration and deleted when you exit the surrounding block.

        Static variables are created by the linker when the program starts and are deleted when the program terminates. If they are local variables declared "static", however, you can only access them in that block, even though they exist outside the block.

        Global variable are in the static storage, and if you declare them as "static" then they are hidden from other files. However, if they are not declared "static" then another file can use them by declaring an "extern" variable.

        Register variables are not really needed -- a good compiler does this automatically for you anyway. Even if you specify "register" the compiler can ignore it!

        As a rule.... don't use anything but local variables in CS201.

        Note: the meanings of these keywords when applied to data members in a class is related but not identical to their use inside a function. The life time of normal data members is equal to the lifetime of their object, for example. If you declare a variable as a "static" data member" then it is attached to the class not the insances of a class. There is a single variable, any function in the calss can use it, and its life is equal to the whole program.

        This is a complex set of distinction that we will review in CS202 and CS320.

        What happens if you don't put () after a function name

        It don't get a function call, you get the address of the compiled code that starts the function! So
         		printit();
        calls the function... but
         		printit;
        compiles and does nothing.

        Can a function inside of another function return values

        You can not just write a function declaration inside another one.

        But you can call a function, and return the result

         		return sqrt(myfunction(x));

        Clarify the difference between pass-by-value and pass-by-reference

        Download and run this [ calls.cpp ] it shows how pass-by-valaue transfers a value from an expression in a function call into a parameter.... that stays inside the function, but pass_by_reference acts directly on the variable that is given to the function.

        How and when to use call by reference

        (1) Use reference parameters when you need a function that changes the value of the variables it is given. (2) Use reference parameters to avoid copying large objects (and vectors). In this case add "const" to signal you won't change them.

        When returning a reference to a local non-static variable

        You return a piece of garbage. Seriously-- we call a piece of storage that has been given up for reuse as garbage. On exit the local varaible become garbage and you return the address of the garbage. This is not a good idea.

        .What is a function prototype A function prototype is just like that function header except it has a semicolon after it:

         		type name(parameters);

        It's purpose is to tell the compiler that such a function exists, and how to compile calls to it.

        The linker connects up the calls with the actual function declaration.

        In essence a function prototype is a promise that you will supply, sometime, a complete function that can be called.

        How are default parameters used

        They let you omit some values in a call. They are replaced by the defaults.

        If f has default values for its parameters can I write a call like this f(,,34)

        No. The omitted parameters are always at the end of the parameter list in the current version of C++. Perhaps later standards will allow this freedom, or something like it, since it is part of Ada.

        What is the difference between f(void) and f() in a declaration

        In C++ there is no difference. In C the second forms allows any parameters at all. In C++ you write this f(...), and have to use special libraries to handle an unknown number of undefined parameters. Using a reference parameter in a call is just like any other call.... but you can only give the function a variable. Constants and expressions are rejected by the compiler. The function needs a variable to work on...

        How is an everloaded function distinguished by its parameters

        The name and parameters
         		type name(parameters);
        are combined (this is called Name Maangling ) to give a longer name that contains both the name of the function and all the types of the parameters. It is complex and works without us worrying to much about it.

        When the function is called.... the values are matched to the right function. For example, [ overloaded.cpp ]

        What happens if overloaded functions have the same signatures

        The compiler rejects them (I think).

        How to use function overloading

        Don't worry about it! It just means that you don't have to think about keeping all the function names different. Make the name describe what it does and the parameters the data it uses.

        Can we use overloading and default arguments to recreate C printf

        By using the (...) you can get exactly the functionallity of printf! You will find it in the <cstdio> library. Try [ http://www.cplusplus.com/reference/clibrary/cstdio/ ] for details.

        What is the unary scope operator useful for

        Not much. Except when you have a local and a global variable with the same name.

        How big can you build arrays

        (1) how much RAM or primary memory can you afford?

        (2) The subscripts must be stoable as int's -- so less than 2^32 on a 32 bit CPU.

        Which is best Mac, PC, or Linux

        I don't like to give an answer to this question.

        (1) I use a Mac and a PC laptop at home, everyday. I use a PC Laptop and Linux desktop everyday at work. They all leave me feeling disatisfied.

        (2) A computer professional should be able to use any computer and any operating system better than an amateur. You use what is available.

        (3) It is more a matter of picking a system that is best for the job in hand.... you can set up a modern laptop or desktop to run two or more operating systems and switch as needed.

        When to use recursion

        In CSCI202.... and when the data has a recursive structure -- for example hogh level language input.. What the difference between v.empty() and v.clear() v.empty checks to see if a vector v is empty. It returns true if the vector has no elements. It does not change the vector in any way

        v.clear() removes every item from v. They are destroyed! After clearing a vector v.empty() is true.

        Are arrays still use in C++

        yes. Any time we want speed or when we know how many items we need before we start programming. They are exactly like the arrays in C.

        How are strings and arrays related

        They both have a numbered set of items 0,1,2,3,... They are a fixed number of items. C Strings are arrays of chars with a special '\0' at the end -- a sentinel. Modern C++ <string> strings can grow and collapse and have lots of special functions. Hidden inside string is some clever work with fixed blocks of storage that lets us think we can make strings bigger and smaller.

        How do Multidimensional arrays work

        Later! But.... they are arrays of arrays. Or vectors of vectors.

        Why does v[0] and pop_back() crash on an empty vector

        Because there is nothing there. You attempting to access a piece of storage that is no longer yours.

        Which arrays vs strings vs vectors

        Arrays for speed and when you know how big they are.

        Strings for characters.

        Vectors most of the time.

        So to store a word use a string. To store many words use vector <string>.

        When to use v[i] vs v.pop_back()

        Only use pop-back if you want to remove the last item of data.

        Use v[i] to manipulate the i'th item of v.... without removing it.

        Can you operate a class inside of a function

        Yes.

        How many functions in an array

        As many as you want.

        How many array in a function

        As many as you want!

        What is a data structure

        Any organized collection of data -- all objects, arrays, vectors, lists, maps, sets, .... and so on a classic data structures.

        Vectors and strings

        Everything you can do to a vector can be done to a string. For example
         		s[12]

        Similarly

         		s.push_back('x');
        and
         		s += "x";
        do the same thing.

        The advanced concept of "iterator" works with both vectors and string in place of subscripts.

        Can you push whole words and sentences into a vector

        Yes -- in several ways. This may be the one you want:
         		vector <string> words;
         		string word;
        		while(cin>>word)
         			words.push_back(word);

        Why doesn't vector<vector<int>> work

        Because the compiler recognizes the ">>" as the input operator.

        Can you have arrays of arrays and vectors of vectors

        Yes.... and vectors of arrays and arrays of vectors..... with out limit.

        What are the special version of vectors

        Any time you write vector<T> you've got a special vector!

        What extra features does a vector have over an array


        1. size()
        2. push_back(a)
        3. pop_back()
        4. empty()
        5. clear()
        6. at(i)
        7. last()
        8. first()
        9. ...

        Where can we use a function like print_backwards

        First make sure you include the prototype before you call it and provide the complete definition before the end of the program.

        When is it good to have vectors of vectors

        When the problem has two dimensional data. Or a sequence of sequences, ....

        What is pop_back()

        It is a function that destroys the last element in a vector.

        Can you create an if statement with a vector

        You can use vectors inside the conditions in vectors, because you can use the accessors and subscripts to get normal values and test those. Similary you can use vectors inside the body of an if-statement.... just as if it was outside. And you can declare a local vector.... just like you declare any other local variable...

        What does vectorName.size()-1 mean

        If we have 20 salaries in the vector then it's size is 20. But the last salary is numbered 19 not 20. This is because we start at 0. 19 is 20-1, of course.

        Example you have a vector of 4 fingers on one hand. Now touch the little finger and say 0. The next finger is 1. The next is 2. And the last is 3. Which is 4-1.

        The pattern is: size()-1 is the number of the last item in a vector.

        So to access the last element of a vector called v write:

         		v[ v.size() -1 ]

        Or, you can use the short hand accessor

         		v.last()
        if you like

        Are than any more Accessor for vectors other than empty, size, front, and back

        Just subscript and at.

        What happens if vector elements are not around square brackets

        You have got into a separate universe, or you will get compile errors.

        Can an element of a vector, other than the last element by removed

        Not efficiently. The does exist an "erase" function which will in fact overwrite the existing elements and pop the last one.

        If you really need to insert and erase elements in a vector.... you should be using a <list>.

        How to vectors and arrays relate to each other

        Arrays are a lot more primitive and vectors. They do share a common notation for subscripts. Arrays are OK when you know how many elements you need and you don't want to do anything clever with them.

        Is there anything I can do with an array that I can't do with a vector

        I know of onw thing that I can do with an array, but not with a vector -- use an initializer list. This means that
        	int fib[] = {1,1,2,3,5,8,13};
        is OK but
        	vector <int> fib = {1,1,2,3,5,8,13};
        does not compile it complains about not being given a sigle value for the vector. There are three obvious ways round this. (1) use an array (when it doesn't grow). (2) Push the data directly into an empty vector. [ initializeVector.cpp ] Or (3) Put the data in an array with an initializer and then push it into the vector: [ initializeArrayFirst.cpp ]

        With objects something similar works [ vectorOfObjects.cpp ] for example.

        Can I change the size of an array by ....

        No. No. Nothing will change the size of a local array once it is declared.

        Why can I go outside the bounds of an arrray

        Because a compiled program doesn't see the boundaries. It knows the start of arrays, but not where they end. It has no way of calculating how far you can go.

        A running program sees data as a gigantic array of words with the beginning of the data for each variable is known...

        What happens if I go off the end of an array

        You overwrite the adjacent memory. It may crash the program or the computer. But usually you start to get very weird answers for no apparent reason.

        What about walking off the end of an array with a for loop

        The results are unpredictable and never good.

        What about vectors -- can you go off the end without errors

        Yes. But the results are wrong, weird, and crash software.

        What is a Smart Array

        It knows how big the array is. It looks very like an array but any attempt to go ouside it is trapped as an error. It is a safe array.... but may be slower than a raw array. One of the neater things about C++ is that you can create a class that hides its data and define the meaning of the subscript operator ([]) for objects in the class, so you can use a smart array just like a dumb one!

        What happens if someone inputs too much data into an array

        In the worst case scenario they can insert there data into your program where it will be executed. This is called "A buffer overrun attack". It is most often caused by using "gets" or "cin>>" into an array.

        Does getline(cin, SIZE, ENDCHAR) help avoid buffer over runs

        Yes.... except that you have problems when SIZE characters are read. You have to input the rest of the line after the SIZE characters. I think it even fails to terminate the array with a '\0' or something like that.

        Please use strings for unknown ammounts of data. Or read it in one character at a time...

        Can memory be reserved for several arrays with many decalarations

        Yes.

        How many different types of arrays

        Infinity. One for each type of data at least.

        What happens if people supply too much data in an intializer

        I think you get a compile error .... I hope so.

        How to avoid supplying too much data in an initializer

        Let the compiler count the elements for you
         		double s[] = {1.23, 3.45, 5.67,7.89};

        Can you initialize arrays in any part of a program

        You can initialize an array only in a daclation of a local variables. So any where where a local declaration is legal can have an array and an initializer.

        You can not initialize a data memebr/dtat field in a class... even if it is an array.

        Is using an initializer fast than a for loop

        Yes. The compiler does the initializaitiopn before the program starts, I believe.

        Why is it better to store characters in char arrays rather than string

        There are only two reasons: speed and because we are forced to. Arrays are a bit faster because they have no frills and no safety features -- just like a sports car.

        We are forced to use a character array each time we type in a string literal with double quotes:

         		"Hello"

        This is converted into an unamed array of 6 characters (notice the 6(six) chars) initialized to

         		char noname[]={'H', 'e', 'l', 'l', 'o', '\0'};
        Notice the extra NULL character at the end.

        Personally -- I use STL <string>s as much as I possible can. They may be slower but they are less confusing, more powerful, and safer.

        Which feature of character arrays is mostly used

        Their is a CSCI202 technique known as a "char*" (pronoounced "char star") that gives you tight, elegant, and fast code for many operations. They also tend to be surprisingly buggy.

        Can we us const to declare a function

        First, you can declare parameters in a function to be constant
         		type function (...., const Type parameter, ...)...

        Second you can attach "const" to a member function of a class to tell the compiler that it is an accessor -- a function that does not change its object (examples for vectors: size() and empty()). You do it like this inside a class

         	class Sample
         	{
         		...
         		double mean () const;
         		...
         	};
        and outside the class
         	type Sample::mean()const { return sum()/size(); }

        But I don't think you can define a "const function" -- it doesn't mean anything.

        Why do we need static_cast, why not write the expression so that it is in the right type

        It is often possible to write expressions so that the give data of the right type. For example
         		1/2
        uses int arithmetic to calculate 0. But
         		1.0/2
        will use double arithmetic to calculate 0.5.

        However, if you have to integers, i and j, and need their ratio

         		i/j
        gives a rounded int answer... A trick is to include a double:
         		(1.0*i)/j
        for example. And form the 1970's to the 1990's we could cast a number like this
         		((double)i)/j
        or, later,
         		double(i)/j
        however after 2000 the standard promotes the explicit static cast
         		static_cast<double>(i)/j
        which may be longer but is quite clear as to what you need to do.

        Whay sort and serach since this is inefficient

        Because people need the operations. They need to search for data -- think Google! And search can go faster if the data is in the right order.

        People also like to see data in different orders.... and each order means you have to sort the data into that order.

        Besides the algorithms are interesting and fun.

        Which companies use sorts

        All people need there data sorted and so use sort programs. This is why we study them in Computer Science. Example: A phone company lists its subscribers in a phone book that is sorted.

        Why not use insertion sort for long arrays

        Try it with a deck of cards and see:-)

        When to use Insertion sort

        A rule of Thumb: No more than 10 items!

        Because for more than 10 items there are faster ways to sort them. Covered in CS202 and CS330.

        Why is insertion sort simple but not efficient

        Like most simple things -- it is not as good as some clever algorithms -- especially when there is lots of data. More in CS202.

        Please give more details on the STL vector template class

        First check out [ samples/stl.html#Vectors ] then check out SGI's site [ http://www.sgi.com/tech/stl/ ] then look in the standard [ ../c++std/cd2/lib-containers.html ] (tough going but complete).... and then hit the library!

        Why doesn't vector at return an rvalue

        All lvalues are coerced to rvalues when an rvalue is needed.

        What is an lvalue and an rvalue

        When a variable appears on the left of an assignment
         		left = right;
        it is an lvalue -- a place where data can be put. lvalues are places to store data. On the other side (right) the variable is used as supplying a value -- this is an rvalue -- a place or expression that gives a value. Lvalues are places and rvlaues are things in those places.

        How come linear search is bad for large arrays

        It becomes very slow with lots of data to search. Remember finding the name of the person with number 123-4567 in a normal phone book. This requires a linear search and will take hours if not days. Finding "Victor Hugo" in a normal phone book is much quicker because we don't use linear search.

        [Clever algorithms work faster on big data]

        What is a template vector

        It is a long name for a vector.

        What is a template

        A template class or function is written to have some unknown types of data and adjusts to the data you supply.

        vectors are template classes.... Hence "vector <....>"

        How often are vectors used in C++

        A lot!

        The modifyArray function on page 356 has a parameter sizeOfArray -- does it change the size of the array

        Nothing can change the ammount of space you give to an array when you declare it. NOTHING!

        In this function you can input any number as the size. You can lie! But this may not be wise.

        If the parameter has a value bigger than the real size then the function can do just about anything to your program.... upto and including shutting down the computer, by way of strange bugs and errors.

        If the parameter is equal to size of the array then all should be well.

        If the parameter is less than the real size the function will probably only use part of the array. And this may be what you wanted.

        How are arrays passed by reference

        The formal parameter gets the address of the first item in the array (item [0]). In the function the items are found by cacultaion, of course:
         		item[i]
         		address of item + (i * sizeof item).
        The function gets the size from the parameter type.

        Thus it can get to any element in the original array.

        If an array is associated with a const parameter can it ever be changed

        Not by the called function. Other parts of the program can still change it.

        When to use const for local variable

        When they are constants! Good examples are π, Euler's e, Avogadro's number, Days in Week, Months in year, and so on.

        Are arrays the only things passed by reference by default

        Yes. In C++ objects are copied and elementary data are copied in unless you use the "&" in the parameter specification.

        Can we have unsigned subscripts for vectors

        Yes... but they will be converted to signed.

        What was in the final 2009

        [ mock2009.html ]

        What was in the final 2012

        [ mock2012w.pdf ]

        Questions about the Big-O notation

        Will be answered in [ cs202/ ]

        How to use elements of an array as counters

        With arrays you need a fixed number. Suppose we have some events that happen at different days.... and to count how many in each month....
         		const int MONTHS =12;
         		int counter[MONTHS]={};
         		//some kind of loop
         			//Calculate a month...
         			counter[ month ] ++;
         		//end the loop some how
        Something like the above should work.

        Can you have a vector of strings

        Yes.

        Can you return a vector from a function

        Yes, but it means copying it and will be inefficient.

        Do you have intialize strings

        You have to initialize old-fashioned character arrays: char[...].

        You don't have to initialize C++ STL strings. If you omit to do it they are set to a string with nothing in it.

        What is a scalar

        A scalar comes from mathematics -- the opposite of a vector.

        In programming a scalar is a single value with no extractable pieces. Thus int, double, char, are all scalars. Arrays, vectors, and objects are not scalars.

        When to use recursion vs iteration

        Take CS202:-)

        Think about the data the function is handling. If it is recursive then a recursive function will be easiest to write. If the data is itterative.... use loops.

        Think about the problem. Is it describe recursively -- then use recursion.

      2. Elseuse loops.

        Do variables declared in main have a scope after the end of the main function

        No.

        What is an access function

        An access function or accessor is a function in a class that computes and returns a value with out changing the object. They express properties of objects. Examples: get age, get height, get grade,... They are also called getters because their name traditionally starts "get".

        What is a predicate

        A predicate is a function that returns one of the two bool values: true or false. Thats all. The term goes bac to formal logic 2000 years ago!

        Is FOIRTRAN still being used in older equipment like weather satelites

        (1) It can take a lot of time and money to translate a lot of code from one language to another.

        (2) FORTRAN does a good job of scientific computation.

        We have a joke that the programming language used on the Starship Enterprise is called FORTRAN -- but doesn't look anything like 20th Century FORTRAN.

        Who uses UML Diagrams

        Competent proffessionals.

        Can an array have more than two dimensions

        Strickly speaking an array in C++ is always one dimensional.

        But you can combine or nest as many as you need to get higher dimensions. For example to play three-dimensional tic-tac-toe or model a Rubric's Cube you might declare

          	Cubey cube[3][3][3];

      . . . . . . . . . ( end of section FAQs on C++ and CS201) <<Contents | End>>

      Abbreviations

    1. Algorithm::=A precise description of a series of steps to attain a goal, [ Algorithm ] (Wikipedia).
    2. Class::=A description of a type of object that includes the data it knows and the functions it can execute.
    3. Function::programming=A selfcontained and named piece of program that knows how to do something.
    4. Gnu::="Gnu's Not Unix", a long running open source project that supplies a very popular and free C++ compiler.
    5. OOP::="Object-Oriented Programming", Current paradigm for programming.
    6. Semantics::=Rules determining the meaning of correct statements in a language.
    7. SP::="Structured Programming", a previous paradigm for programming.
    8. Syntax::=The rules determining the correctness and structure of statements in a language, grammar.
    9. Q::software="A program I wrote to make software easier to develop",
    10. TBA::="To Be Announced", something I should do.
    11. TBD::="To Be Done", something you have to do.
    12. UML::="Unified Modeling Language", industry standard design and documentation diagrams.
    13. void::C++Keyword="Indicates a function that has no return value".

    ( End of document ) <<Contents | Top