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.
std::coutbut the
using namespace std;
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:
In other words the point is allowed to float inside the number...
Modern computers provide a form of floating point that uses Binary notation rather than decimal. It is easy to use (just forget it!), give approximate but good answers, and is slower than integer arithmetic.
Most computers provide two different sizes of floating point number:
normal and double length. Double length numbers take up twice the space
and are slower.... but the give a more accurate answer.
Choosing data types: int vs double vs string
Use double for all measurements. Use int only for counting
things. Only use 'float' for a measurement if you have a small
(20th century) computer.
Beware of dividing ints!
2 / 3is 0. If you don't want to do integer division -- you need doubles.
For any kind of character handling (like -- "insert a comma") you need
strings
not ints or doubles.
Why do we include iostream
#include <iostream>is needed for programs that do IO (Input and Output). It tells the computer how to connect C++ to the user's keyboard (cin) and display(cout).
#include <iostream>
using namespace std;
int main()
{
cout << "Prompt";
type variable;
cin >> variable;
...
}
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 % mis the modulus of n mod m.
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"
Example: given
int main()as input to a compiler we will need to extract and recognize the "main" in the line.
123 ++ grandmathen
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.
12345/100you will get the number of dollars and if you computer the remainder
12345 % 100you get 45 -- the number of cents.
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.
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 42in 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.
C++ programs execute the main function until they hit their
return statement. That is when they stop. And they leave the
zero as a signal to the operating system that zero errors occurred.
Can C++ calculate derivatives and antiderivative.
Not easily. You would have to teach C++ how to store and
manipulate formulas and then all the rules of the
calculus. It is easy in Maple and Mathematica to differentiate
functions. In languages like Prolog and LISP it is not to
difficult to code the rules of differentiation.
Oddly antiderivatives are difficult for human (intelligent)
mathematicians. I don't think there is an algorithm and with no
algorithm you can't write a program.
How does a member function differ from a nonmember function
object.function(data)
lengthOfStr = str.length();
diagonal=sqrt(x*x+y*y);
variable = expression ;changes the value of the variable so that it is the current value of the expression.
This expression
expression1 == expression2is a test to see if the two expressions have the same value at this time. It is often used in ifs and whiles.
The expression
test ? expression1 : expression2is 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.
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.csci.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).
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 I put an if/else inside an if/else? Should I use braces
Yes you can (and will). I use braces when ever it gets complicated.
What are loops for
Loops tell the computer to repeat the same computation many times.
They are used to process repetitive data in files, produce
interesting patterns in graphics, carry out iterative
algorithms, and wait until something happens.... and much more.
How do you avoid infinite loops
First, never write a loop that looks like this
while ( ____ == ______ )since the values of the two expressions can jump all over the place and never become equal.
Second, by being careful. In other words you choose a terminating condition that you can guarantee will become true some time. For example if the loop starts while(x<10) then x should increase each time the body of the loop is executed. If it is while(x>=17) then x should get smaller in each cycle.
A sound discipline (but not easy) is to calculate how often each loop will repeat its body as a function of the arguments. This leads to the discipline of the analysis of algorithms that is in the core of computer science.
Now some loops do not follow these two guidelines and yet they still always stop after a finite number of steps. These are subtle loops and need careful design, testing, and checking. You need to use loop invariants.
What are loop invariants
A loop invariant is any boolean expression or fact that remains true
as the loop runs. It should start true, and it won't change, so it
ends up still being true, however many times we repeat the loop.
For example in the following loop
s=0; n=0;
while (n<100){
s=s+n*n; n=n+1;
}So at the end when n==100:
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 >> blahas it is executed and inputs data:
while(cin>>number)
cout << sqrt(number) << endl;
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.
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:
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.
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)
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
| Function | Returns | Effect |
|---|---|---|
| get_time() | Time | no change |
| start() | none | starts the stop watch |
| stop() | none | stops the watch |
| get_timer() | int | returns number of seconds since starting the stop watch... |
| set_time(t:Time) | none | the watches time is set to t |
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);
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.
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.
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?
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
}
(2) declare the object variable with no parameters:
class_name object_variable;
Hey presto! You've got an object full of garbage data. And:
Functions provide limited and controlled access to data. UML class box relate to the code?">
The UML uses position to signal the difference between operations and attributes. C++ uses special syntax. UML diagram when should you do them?">
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:
| Language | Claim |
|---|---|
| LISP | We can now program an artificial intelligence. |
| COBOL | Managers can now write programs in English. |
| TLO | This is The Last One you'll need. |
| Prolog | You can describe the problem in logic and Prolog finds the solutions. |
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).
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
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.
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 144Here 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' + 2is
'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:
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.outWhich lists the lines where the oracle has done something different to the program.
You have lots of code like this:
TestClass object;
assert(object.value() == correctvalue);
object.doSomething(data);
assert(object.value() == correctvalue2);
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
Then came real time and interactive applicati