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 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.
Are there any confusing expressions
Warning: look out for "^" it is not exponentiation.
Warning: Look out for expressions like
2/3because the computer sees two integers (2) and (3) and so does integer division giving the answer
0To get "two-thirds" you need to force the compile to use double length calculations like this
2.0/3.0
Also
17 % 5is 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
| i | j | k |
|---|---|---|
| 2 | 4 | 17 |
k = ++ i;we have
| i | j | k |
|---|---|---|
| 3 | 4 | 3 |
If we again start with
| i | j | k |
|---|---|---|
| 2 | 4 | 17 |
k = i ++;we have
| i | j | k |
|---|---|---|
| 3 | 4 | 2 |
Summary of the rules
| Expression | Effect on i | Returned value |
|---|---|---|
| i+1 | None | old i + 1 |
| i++ | add 1 to i | old i |
| ++i | add 1 to i | old i + 1 |
Why is tracing a program helpful
No other method gives you an understanding of what the computer is going to
do.
Once you have traced a program you can usually figure out what was going
on.
What does cout mean
This variable is pronounced "C out" and it means: the place where
C output is sent.
What is a literal
This is a value like 123, 1.23, or "Hello, World". It is
a symbolic constant that represents itself. Numerical literals
are normally typed using decimal notation (but C++ also
does octal and hex if you need it). Strings like "Hello, World"
as (currently) stored as a sequence of ASCII characters.
Is C++ used in Graphics, Games, Special Effects, Movies
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:
| Short form | Long form |
|---|---|
| x -= e; | x = x - e; |
| x += e; | x = x + e; |
| x *= e; | x = x * e; |
| x /= e; | x = x / e; |
| etc. |
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
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
} } }
if( day == THU )
{
if( time == 12 )
{
class = 201;
}
else if( time == 12 )
{
class = 375;
}
else
{
class = 0;
}
}
if( day == THU )
if( time == 12 )
class = 201;
else if( time == 12 )
class = 375;
else
class = 0;
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.
const double PI = 4*atan(1);
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
| p | not p |
|---|---|
| true | false |
| false | true |
| p | q | p and q | p or q |
|---|---|---|---|
| true | true | true | true |
| true | false | false | true |
| true | true | false | true |
| false | false | false | false |
| p | q | p<q |
|---|---|---|
| false | false | false |
| false | true | true |
| true | false | false |
| true | true | false |
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);
(2) The is a long long tradition of having not act on the following simple condition rather than a group:
not today and tomorrowmeans:
(not (today)) and tomorrownot:
not (today and tomorrow)
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.
for(A; B; C) {D;}
is shorter than
{ A; while(B){ D; C; } }
and does the same thing.
Most for-loops look like one of these
for ( i=0; i < ...; i++)
for ( i=1; i <= ...; i++)
for ( i=...; i >=0; i--)
if( x < 0 )
fabs=-x;
else
fabs=x;
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!
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;
}
| Statement\Variables | t | i | cout |
|---|---|---|---|
| t=0 | 0 | ? | ? |
| i=0 | 0 | 0 | ? |
| i<5 | |||
| t=t+i | 0 | 0 | ? |
| cout | 0 | 0 | 0 |
| i++ | 0 | 1 | |
| i<5 | |||
| t=... | 1 | 1 | |
| cout... | 1 | 1 | 1 |
| i++ | 1 | 2 | |
| i<5 | |||
| t... | 3 | 2 | |
| cout | 3 | 2 | 3 |
| ... | |||
| cout | 10 | 4 | 10 |
| i++ | 10 | 5 | |
| i>=5 |
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!
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...)
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
A for loop like
for (A; B; C) { D }
is more complex
In short the pattern is
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!
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 Dbecomes
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]
}
1101101You 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:
| Theory | C++
|
|---|
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
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:
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;
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.
string s1....
string s2....Then you can use the same operations as you do with ints:
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.
You should use them to contain common calculations and tasks.
They let a single statement of simple expression stand for a complex
computation.
What functions help you round numbers in different ways
You get standard rounding when ever you assign a double to an int
variable. This converts the double to the nearest int.
The cmath library has two functions that convert doubles to integers. They are named ceil and floor. The function ceil returns the smallest integer that is not less than the value of the parameter -- the ceiling above the number. The function floor returns the largest integer that is not greater than the value of the parameter.
Should we put a return statement at the end of a void function
Not really. The compiler will do it for you anyway.
What makes a function and advanced function
It has one or more of the following features:
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
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:
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:
| Bits | Unsigned # | Signed # | Day of Week |
|---|---|---|---|
| 000 | 0 | 0 | Sun |
| 001 | 1 | 1 | Mon |
| 010 | 2 | 2 | Tue |
| 011 | 3 | 3 | Wed |
| 100 | 4 | 4 | Thu |
| 101 | 5 | -3 | Fri |
| 110 | 6 | -2 | Sat |
| 111 | 7 | -1 | ERROR |
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
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.
001010100111is split like this
0010 1010 0111and 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 111giving 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.
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 intwill 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
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.
I have some open source software that I maintain
[ http://www.csci.csusb.edu/dick/cs320/lisp/src/ ]
is an example.... Meanwhile
How are pointers used in practical situations
(1) Parameters passed by reference uses a kind of pointer.
(2) Getting more storage as the program runs. Vectors have an internal pointer
that is points at the heap.
(3) Advanced data structures (CS202 and 330) are all built by using links. The links
are pointers.
(4) All work at the hardware level (drivers) use pointers.
(5) ...
What is different between p1=p2 and *p1=*p2
Assuming that both p1 and p2 are pointers to locations
then
p1=p2;will change p1 to point to the same place that p2 points. Here is a picture of memory before and after:
| Command | p1 | p2 |
|---|---|---|
| - | α | β |
| p1=p2 | ||
| - | β | β |
The command *p1=*p2 changes the place that p1 points to by the place that p2 points to:
| Command | p1 | p2 | α | β |
|---|---|---|---|---|
| - | α | β | a | b |
| p1=p2 | ||||
| - | α | β | b | b
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.
int main ( int argc, char* argv[] )which are the arguments of the program when executed as a command!
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.
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.....
|
. . . . . . . . . ( end of section Questions) <<Contents | End>>
Questions
.... 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;
}
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; }
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 lifeYou 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].
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...
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....
/*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.
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++
| Relation | C++ |
|---|---|
| has | declare a data member |
| knows | declare a reference or pointer data member |
| is a | derive the class from the other class [ ../cs202/ ] |
Very useful in complex programs. But shouldn't be needed in CS201. Covered in CS202...
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).
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.
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 > fileBut '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);
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)
Gthen 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.
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.
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():ColorQueries are also called accessors and are coded in C++ with the "const" keyword
Color getColor() const { return color ;}
Why do we use classes -- they make a simple program complicated
We use classes because they make complex programs simpler. They
separate the concerns into different classes so we only have to
think about a small part of the problem at one time. We can also think
about the solution of the problem in terms that are used by our clients.
We can model the problem and make a visible connection between the problem and
our code.
We also use them because they are the only way to do drive modern graphical user interfaces.
Finally there are some useful and powerful class libraries for certain
kinds of problem.
Can we create our own types with type conversions
Yes. There is one subtle problem that sometimes happens.... that is in
CSCI202.
What is the purpose of a function call operator
We use it when we need an object that works just like a normal function.
You can skip the rest of this answer....
I had a recent case of a student who had written a program to integrate functions of one variable. Here is how we used it:
cout << integrate( sin , 0, PI/4 ) << endl;
cout << integrate( exp , 0, 1 ) << endl;
cout << integrate( recip , 1, 20 ) << endl;(where we declared
double recip (double x) { return 1.0/x; }
)
Our problem was that we wanted to integrate this function with respect to x:
double chisq(double x, double f ) {return /*horrible*/; }
which has an extra parameter f the degrees of freedom.
So we defined a function object:
class ChiSq
{ double f;
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...