.Open FAQs on C++ . Why are you teaching Linux? Total cost of ownership, reliable networked systems, + hard core professionals use it. . Why are you teaching C++? Used in many industries. After C++ other languages are easy! It is also leads to programs that execute quickly. It is like a tool box full of very sharp power tools. You need to know what you are doing but you get a lot of power and speed in return. C++ is very much the parent of most modern (web-based) languages. . How is C++ used in Games? You need a good graphics and user interface library plus a "games engine" that understands the physics of objects. C++ acts as the glue connecting these components. The components are probably also written in C and/or C++. . How do you develop a program? Very carefully! First: understand the problem. Second: work out how the user will use the program. Third: sort out the data needed. Fourth: design objects to store the data and do useful things. Fifth: write code for the objects, user, data, .... . Why are you teaching UML? The only industrial diagramming language for software. . How has computer programming changed through out the years? Here is my quick and personal list. .List 1800s Ada Lovelace programs Babbage's Analytical Engine. <1940s Programs were written for human `computers` to execute in English and mathematics. 1940s Programs written by changing the machine hardware (in secret). 1950s Instructions written as numbers and stored in memory. 1960s First programming languages mimic mathematical formula(FORTRAN, ALGOL) or managerial English(COBOL). Programs became complicated so we split them up into independent pieces called modules. Flowcharts used to design programs. Many local low level languages. Mainframes. 1970s Structured programming. Programs are designed using Pseudocode and diagrams and split into functions. Pascal. C. Unix. Minicomputers. 1980s Data Abstraction. We started to group functions around data and let other parts of the program only see those functions. Ada. The IBM PC. 1990s Objects. C++. Java. The Web. 2000s Modeling: diagrams of objects etc used to analyze problems and design solutions. Perl, Ruby, C#, Python . How does a computer work Here is a model of a computer: A person sitting at a desk with a simple calculator. They read instructions in a book called the "program". They write down answers on a work pad(RAM) and also use them in future calculations. They have an in tray (input) were they get data, and an out tray where they put data (output). . What is the function of the backslash character The backslash (\) character is use in C++ and many other languages to change the meaning of the following character in a string. The backslash and the following characters/number form an `escape sequence`. or to indicate an strange character that is illegal or untypable. Here is a short list of .Key escape sequences. .Set \n Newline \t Tab \" Double quotation marks(") \\ A real backslash \007 Beep .Close.Set . Can you explain more clearly how translate human-readable code to machine code. Not really -- it is rather complex. Take CSCI320 and CS570. Meanwhile .List Recognize the basic words and symbols in the code. Use the syntax to parse the symbols into a structure and reject syntax errors. Scan the stored structure and generate some machine code. Optimize the code (a dark art). Output the result. .Close.List . What translates mnemonic instructions into machine code? The assembler. . Why is C++ faster It is compiled and so the code doesn't have to be parsed many times. It also lets the programmer get close to the machine. . What are namespaces I C++ the names that programmers create are all placed in a namespace. This lets different programmers use the same name for different purposes, even in the same program. For example, most of the standard libraries place their names in "namespace std". SO the official name for the C++ Output stream is .As_is std::cout but the .As_is using namespace std; statement makes it OK to omit the "std::". . Are there any standards for C++ Yes the is one international and American national standard C++. Any variations you meet are non-standard. . Explain how a bug gets past the compiler A compile only checks to see if you've followed the grammar, the syntax of C++. It doesn't check to see if you've written down rubbish. Computability theory shows that it is impossible for a computer to diagnose all bugs that can happen. To quote a friend: "Nothing is foolproof, fools are too ingenious". . Is HTML in use and is it like C++ HTML is still in use. It is totally unlike C++ in its purpose, syntax, and meaning. . What aren't all compilers the same (1) Economics (2) human error. . Floating point notation Floating point is John Von Neumann's invention. It lets computers do arithmetic with "real numbers" easily. The basic circuits do calculations with whole numbers: integers. It takes special hardware or software to handle numbers that are not whole numbers. You know if you want to calculate "1.23 * 32.1" that you can calculate "123*321" and then place the decimal point in the answer. This is the idea behind floating point. We express numbers as a `mantissa` and an `exponent`. The `exponent` tells us where to put the point: 1.23 = 123E-2 and 32.1 = 321E-1, for example. The "E" indicates the "Exponent" and is short for using "10 to the power". Now if you do the math you will see that you multiply the mantissas and add the exponents to get the answer: 123E-2 * 321E-1 = 39483E-3 = 39.483 In other words the point is allowed to `float` inside the number... Modern computers provide a form of floating point that uses Binary notation rather than decimal. It is easy to use (just forget it!), give approximate but good answers, and is slower than integer arithmetic. Most computers provide two different sizes of floating point number: normal and double length. Double length numbers take up twice the space and are slower.... but the give a more accurate answer. . Choosing data types: int vs double vs string Use `double` for all measurements. Use `int` only for counting things. Only use 'float' for a measurement if you have a small (20th century) computer. Beware of dividing `int`s! .As_is 2 / 3 is 0. If you don't want to do integer division -- you need doubles. For any kind of character handling (like -- "insert a comma") you need strings not ints or doubles. . Why do we include iostream .As_is #include is needed for programs that do `IO` (Input and Output). It tells the computer how to connect C++ to the user's keyboard (`cin`) and display(`cout`). . What are cin and cout Normally cin is the users input to the computer and `cout` is the place for out to the user. . Can you create a program to prompt and read variables as it runs Yes: .As_is #include .As_is using namespace std; .As_is int main() .As_is { .As_is cout << "Prompt"; .As_is type variable; .As_is cin >> variable; .As_is ... .As_is } . Explain range restrictions on numbers Most computer hardware gives a fixed amount of storage to each type of number (int has 16 bits, float 32 bits perhaps). Going outside the range (overflow) can produce bad results. You can get more storage for `int` by asking for `long int` in the program. You can also ask for `long double` rather than `double`. The old `float` data type is OK for fast calculations with larger errors. . Can we do a number theoretic modulus in C++ Yes. .As_is n % m is the modulus of n `mod` m. . Why do uninitialized numeric variables have random numbers The initial value is what ever has been left behind in the allocated memory by the previous program. This is unpredictable. The program will often work sometimes and produce incorrect answers else where. Initialize doubles and ints will loose points! . Do I like shortcutting assignment and arithmetic Only in private. Avoid it in this class! . What kind of comment do I like the // or the /*...*/ I like both. Any comment is worth more than none. I'll equal credit for both. Please use both and discover the good and bad features. . Is the underscore _ used as a space holder in identifiers Yes! . What does a compiler turn C++ into A lot of numbers. By way of "assembler code". . Are we going to get a list of C++ commands There are at least 100 basic types and you don't need them all. It is best to add them one at a time to your notes and "cheat sheet". If you really need to get a description of the options try .See ../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" ( .Key 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 .As_is "Fred" + "Flintstone" produces .As_is "FredFlintstone" with no space, unlike .As_is "Fred" + " " + "Flintstone" that produces .As_is "Fred Flintstone" . What and why substrings Substrings are parts of strings.... We need them to `slice and dice` nonnumerical data. Typically people gives character data and we need to search it and extract the pieces that we want out of it. Example: given .As_is int main() as input to a compiler we will need to extract and recognize the "main" in the line. . When to use getline and >> with strings Use >> to read in words separated by spaces. For example given .As_is 123 ++ grandma then .As_is cin >> a >> b >> c; would put "123" in `a`, "++" in `b`, and "grandma" in `c`. But .As_is 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 .See http://www.csci.csusb.edu/dick/c++std/cd2/lib-numerics.html except the ones that Horstmann lists on page 59. I did a search on the web and found Matpack .See http://www1.physik.tu-muenchen.de/~gammel/matpack/html/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 .See [AbramowitzStegun6465] (in the CSUSB library and my office). . My program rejects every string function and operation Insert .As_is #include at the start of your program. . What happens if you don't give enough room in formatted output You probably get some asterisks or a wrong answer.... why not try it in a simple program? . How is input and output used in a program Input occurs when the user types some data and it's value is placed in a variable inside a program. Typically done early in a program to get ready to compute other values that are output to the user. . What is int cents = value % 100; The "%" operate calculates remainders (moduli). If value is an integer that holds a large number of cents -- say 12345 cents, then it is 123 dollars and 45 cents. If you divide by 100 .As_is 12345/100 you will get the number of dollars and if you computer the remainder .As_is 12345 % 100 you get 45 -- the number of cents. . Can C++ do equations or algebra or calculus No. There are expensive software tools that can help solve equations, do algebra, and do much of the calculus. Example: Mathematica. These may have been programmed in C++. . Can computers do infinity No -- well not very well and usually only by accident. However -- the standard floating notation developed by IEEE and adopted on most computers has a value that prints as "inf" for the result of calculations that should have produced infinite answers. . When to use ' Only when there is a single character in the quotes: '(' and you don't need to do any string operations on it. We will return to characters later. . Explain the dot notation Some functions are only defined if they are applied to an object. They are called methods. They are used like this: .As_is object . function_name ( arguments ) Examples include "length" and "substr" that operate on strings. .As_is myName . length ( ) .As_is 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 .As_is const string comb="+--+---+--+\n| | | |\n"; for example. . What is the most efficient way to program a tic-tac-toe program The hard parts are (1) teaching the computer what the rules are, and (2) teaching it how to win. A simple idea: list every possible position and tabulate the best move for it.... but this needs a "vector" to hold a large number of positions and moves. We'll do vectors later in this class. You have to do a lot of analysis and design to do this project well. . What is the difference between a class and an object A class is a collection of many similar objects. In mathematical terms, a class is a set of objects. Thus "Fido" is an object and "Dog" is "Fido"'class. When we say that `foo` "is a" `foobar` we imply that `foo` is the object and `foobar` is its class. Does it matter: YES. Bugs and wasted time is the lot of those who confuse sets with elements. In a program an object is a little bit of memory reserved for a special purpose. The class has little memory of its own and defines what the purpose of its objects are: Time, Employee, Point, ... . Can I construct one object inside another Yes.... but the class has to define how it works. . Explain #define This is a compiler directive. Suppose you have .As_is #define answer 42 in a program then the compiler remembers that "answer" means "42" and deleted the line.... but when ever it sees a line with "answer" it replaces it by "42". So, .As_is cout << answer+1<=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 .Key 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 = \Sigma [ i=1..n ] ( i*i ) is always true: .As_is s=0; n=0; .As_is while (n<100){ .As_is s=s+n*n; n=n+1; .As_is } So at the end when n==100: s = \Sigma [ i=1..100 ] ( i*i ) This is a complex topic that needs some high powered logic to really understand. I cover them in CSci556 (senior level formal methods). . If I have an infinite loop how can I terminate the program In Windows call up the task manager, find the process and click "End Task" with your fingers crossed. In Unix, hold down the Control key and tap the letter C key. In rare cases an expert can use the Unix `kill` command to terminate a program. If a program is running on a workstation with nobody there, for a long time.... push the on/off button on the CPU. Reboots are emergency operations but sometimes it is the only way to stop a maliciously breeding program. . What is a sentinel value A sentinel value is a special input value that is found after the `real` data has been read or processed. It signals that the data is complete. . How do you test for input failure or end of file .As_is cin.fail() is a good test. You can also test .As_is cin >> blah as it is executed and inputs data: .As_is while(cin>>number) .As_is cout << sqrt(number) << endl; . What is a Boolean variable A Boolean variable is declared to have type `bool`: .As_is bool variable; .As_is bool variable=true; .As_is bool variable=false; To some extent, bool behaves as if it was declared like this: .As_is 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 .Key the loop-and-a-half pattern. .As_is bool event_happened = false; .As_is ... .As_is while( not event_happened ) .As_is { .As_is ... .As_is event_happened = (test for event here); .As_is ... .As_is } . 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: .See ../cs201/09multi.cpp . What is the relationship between a function and a parameter? There are several relationships. First, a function is declared with .Key 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 .Key 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: .Set The compiler gives you an error message. The compiler inserts casts to force the actual values to fit the formal parameters. .Close.Set . What is a predicate and how do we use it. A .Key predicate is any function that returns a Boolean value. You use it to test the truth and falsity of properties you are interested in as the program runs. You use predicates in conditions mainly: `if(....)` and `while(....)`. For example .As_is if( near(x,y) ) ... .As_is 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: .As_is Lunchp. to ask questions. . What is a side effect? A side effect occurs when a function changes something out side the function. For example: .As_is int glob=0; //evil global variable .As_is .... .As_is int f() .As_is { .As_is glob=glob+1; //sneaky change to global variable .As_is } Here calling .As_is 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 .As_is void fun(int argument); (notice the semicolon!) and define it later .As_is 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? .As_is (A) or (B) . Will we use any other #includes Perhaps.... . Can we put an #include later in a program Included files are designed to work if they come first in a program because they define functions. Bad things can sometimes happen if you do it later in the code. . Can I use C++ to create programs that I can sell? Ask Bill Gates and Paul thingie..... Microsoft makes lots of money selling C++ programs. But get a lawyer before getting into serious business. You can get badly hurt. . Explain more about the condition in a while statement. The condition is tested and the loop body is entered if the result is true. The condition can be as complicated as you like. . Which is the compile command "g++... " or "./...." The compile command starts "g++" because it calls the compiler called "g++". The "g" is for "Gnu" and "++" from "C++". . Is a class a holder for a bunch of functions? Yes. It is `not` a function but a collection of functions. A class also lists the data to be found in all its objects. So it is also a holder for a bunch of variables. A class also has a number of objects (initially none) because it defines how to construct new objects. . How do you modify or change the value of a private data field? A private data field can not be changed from outside the class. You have to call a member function of the class that changes it. These functions are called .Key mutator functions. . What is the purpose for declaring an accessor function with const? This tells the compiler to make sure that you don't accidentally create a $mutator that changes the data in the class. The `const` is short for `constant`, and the data fields are forced to be constant when the function is called. When an accessor is called the data fields in the object are retained. And the `const` enforces this! . Do you have to define functions before classes? NO. You can declare non member functions like `main` anywhere. You can only define a member function after they are declared in the class. So typically classes come first and then functions. . How does encapsulation work? The compiler won't let you do anything to an object that is not declared to be public in its class. This puts a "capsule" around the contents of the object. . What is an interface? An interface is a list of functions that you can use -- public member functions. An example: Watch interface .Table Function Returns Effect .Row get_time() Time no change .Row start() none starts the stop watch .Row stop() none stops the watch .Row get_timer() int returns number of seconds since starting the stop watch... .Row set_time(t:Time) none the watches time is set to t .Close.Table . What is the difference between implicit parameters? When you call a member function you apply it to an object and can also pass some data to it: .As_is object . function ( data ); .As_is 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: .As_is Summer::add(int data) .As_is { .As_is total = total + date; .As_is } The total is always the total that is in the object mentioned in the call: .As_is object.add(20); . How does a class differ from a function? A class contains functions.... But is not a function. You can call a function. You can not call a class. A class constructs objects. Most functions do things to existing objects. A function can return a value. Classes have no value to return. They define a new type of value that you can use. . When are global variables used in C++? When you don't know any better! When a group of functions share some data then you need a class to hold both the data and the functions. . Explain getline and >> Use `getline` to get a complete line of data from the user... ending when the tap the "Enter" key. Use ">>" only when you know what type of data comes next. Use getline when you can't predict the type of the input data. the getline function returns a string and you can then explore the string and figure out what is in it. . What do two colons do? The two colons are used in C++ to relate a name to the class or namespace in which it is a member. A function like .As_is 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 .As_is Botting::Richard. . What are the differences between && || and or? In C++ "&&" is the same as "and". They are both operators used in writing conditions: `A and B` (`A && B`) is true precisely when both `A` and `B` have the value `true`. It is false otherwise. Similarly, "||" means the same thing as "or" and these are also used in writing conditions. However `A or B` (`A || B`) is true if either `A` or `B` has the value `true`. It is false only when both `A` and `B` are false. . What do default constructors do for you? When a class has a default constructor it means you can create new objects with out worrying about any parameters -- the default constructor will define a suitable object for you. You don't have to have a default constructor and it can be anywhere in a class description. How ever they are useful whenever you know what a typical object looks like. . How do special constructors differ from the default constructor? They have parameters. C++ matches each declaration and construction by using the type of the parameters. It searches all of them looking for the right number and right types. . Can you have a class with no constructors? You can write a class without any constructors, but the C++ compiler will then add a default constructor that does nothing: .As_is MyClass::MyClass(){} To stop strangers from constructing objects you make all the constructors `private`. This is an advanced technique and needs more experience and knowledge than we have time for in CSci201. . What are mutators for? The are used to change the data values in an object. They are chosen to reflect real life changes in the real world. Mutators change the internal state of the object. . Why can't I use a constructor to mutate an object? Making a new object is different to changing an existing one. So I guess that the C++ designers decided that someone this confused should be stopped... . How do you indicate whether the implicit parameter is passed by reference or value? It is always `passed` by reference! There is no choice here. . Why do some of the book's classes have two constructors and others only one? Why not? You should have the right number of constructors for the job the class has to do. No more and no less. . How do I get the right number of constructors. With some experience you will be able to get this right by thinking about the different ways that an object might need to be created. If in doubt do the absolute minimum for the program in hand and add new ones when needed. . Are overloaded functions important? Overloaded functions (member and non-member) are important. You can not avoid using them. And you will need to create new ones as well. The C++ compiler matches function calls with function definitions. It does this by looking at the name (easy) and also by looking for a function that needs the data you have given it. . Do you have to use I in a loop? No. You can use any variable name you like as a counting variable. The traditional names are: i,j,k,l,m,n. . Can there be more than one constructor in a class? Yes. They must have different types and numbers of parameters. They are $overloaded. . Is programming an art or a science? Yes. We can teach the science part.... but the art is something you will have to develop for yourself. . Must an accessor be a member function? Yes. The purpose of an accessor is to access private data. Only functions that are members of a class can do this. . What is a CASE tool? CASE::="Computer Added Software Engineering", by analogy with "CAD" Computer Aided Design, a tool that helps you develop higher quality software typically by putting a graphic front end on the way to code. . What is the difference between implicit and explicit parameter? Explicit parameters are written in parentheses after the function name. The implicit parameter appears before the "dot" in a function call but is not mentioned inside the function definition -- it is implicit. Operations on the data members are done to the parts of the object that appears before the dot in the calls: .As_is implicit . function_name( explicit ); and hidden in the body of the function: .As_is private: .As_is Type data; .As_is ... .As_is public: .As_is Type function_name( formal_explicit_parameter) .As_is { // a ref to `data` turns into `implicit.data` from the call .As_is } . Can you define an object variable that is not initialized by a constructor? This is simple (and dumb) (1) forget to define a default constructor in the class. (2) declare the object variable with no parameters: .As_is class_name object_variable; Hey presto! You've got an object full of garbage data. And: GIGO::="Garbage in, Garbage Out". . Why are member function important to classes? Object are used via their class's member functions. No functions, no use. So you get a useless class. Functions provide limited and controlled access to data. . How does the layout of the $UML class box relate to the code? It doesn't. The $UML puts the data first, in C++ you can put it last. Similarly the $UML has the functions at the bottom, in C++ they can be anywhere. The $UML uses position to signal the difference between operations and attributes. C++ uses special syntax. . There is a lot of info needed for an $UML diagram when should you do them? Start simple and add information as needed. Don't put all the details at first. Grow the diagrams and compartments: name, then add some data, then add some functions, .... First use $UML as a rough sketch, then work out the detail and code them. Then do a nice tidy $UML diagram to summarize what you've done when you present your work to others. . What is the purpose of the ampersand in a function header? It means that the parameter in the call MUST be a variable. It also means that what ever is done to the formal parameter inside the function, actually is done to the variable that was the actual parameter. . Why does revealing less information give more flexibility to improve a class? When information about the inside of a class is not revealed, then people can't rely on what you did when they use your class. So you can safely change what you wrote without breaking their code. . Why do we have both member and non-member functions? C++ inherits "naked" functions from C, and it is too late to change that. Also sometimes you have need for a simple function and do not need the hassle of putting a class around it and declaring objects to get access to ONE LITTLE FUNCTION....(sorry to shout... I feel better now). . What is overloading a function? A function is .Key overloaded when the same name has different types of arguments. The compiler will pick the definition that fits the data types in the call of the function. . Do most programming jobs require understanding the UML? It will help..... and a lot of job adverts mention it. . Can you have a function called 1 or 2? No. . Are there any programming languages that can be used to process themselves? Yes. C++ is one of them. Our 'g++'/'c++' compiler is written in C++. . Will there be any use for computer programmers now that programs can write programs? Yes.... there is a definite future because computer programs are essentially rather stupid compared to a human being. It takes a human to figure out what the problems are and then to choose what needs to be programmed. A computer also has some definite limits (covered in the Upper Division Theory courses), and a smart human is needed to avoid the need to program these. Several times in the last 40 years somebody has produced a new language claimed that: .Table Language Claim .Row LISP We can now program an artificial intelligence. .Row COBOL Managers can now write programs in English. .Row TLO This is The Last One you'll need. .Row Prolog You can describe the problem in logic and Prolog finds the solutions. .Close.Table In every case, the claim turned out to be false. . When do we use p and q in C++? These variables can be used for Boolean variables. The `p` stands for `proposition` and the `q` is the next letter in the alphabet. However it is better to use a name that means something, like .As_is end_of_file .As_is bad .As_is 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 .As_is if(P) .As_is if(Q) .As_is A (with no elses) is simpler as .As_is if( (P) and (Q) ) .As_is A (and often the ()s can be left out). . Explain symmetric and asymmetric bounds in a loop A loop typically starts by allocating a value to a variable. In other words, the variables starts out `equal` to a value. The end of a loop can be specified in two common ways: .As_is while( variable < bad_values ) or .As_is 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: .As_is switch(Expression) .As_is { .As_is case Value: .As_is DoSomething; .As_is break; .As_is ... .As_is } 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: .As_is if(Condition) .As_is { .As_is TruePart .As_is } .As_is else .As_is { .As_is FalsePart .As_is } 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 .As_is if(Condition) .As_is { .As_is TruePart .As_is } .As_is else .As_is { .As_is if(anotherCondition) .As_is { .As_is FalseTruePart .As_is } .As_is else .As_is { .As_is FalseFalsePart .As_is } .As_is } Then we simplify the syntax to .As_is if(Condition) .As_is { .As_is TruePart .As_is } .As_is else if(anotherCondition) .As_is { .As_is FalseTruePart .As_is } .As_is else .As_is { .As_is FalseFalsePart .As_is } 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: .As_is D>=0 and sqrt(D) < 3.0 . Explain pass by reference with classes A member function is defined and called with pass by value or pass by reference just like any other function. However, the implicit parameter is actually passed by reference. . Why does Dr. Botting Hate the Do Loop? Because he has had lots of bugs when he has used it. . How does the for loop differ from the while loop? A while statement has one part: the condition tested at the start of the loop plus the body: .As_is while ( condition ) body A for statement has three parts: the initialization, the condition, and the increment, plus a body that is repeated. .As_is for(initialization; condition; increment ) body. The for loop does the work of a more complex while: .As_is { initialization; .As_is while( condition ) .As_is { .As_is body .As_is increment .As_is } .As_is } Since many loops do have the three parts of a for statement, it is worth using it rather than the more complex while. . What is the difference between a "for" loop and a "do" loop? First a do loop always executes its body before testing its condition. A for loop tests the condition before it executes the body. A do loop has a condition and a body. A for loop has initialization, condition, increment, and body. . Inside the body of any of the looping constructs while, do-while or for what does a break and continue command do? The .Key break command jumps you out of the loop entirely. The .Key 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. .As_is A table has many rows. .As_is A row has many items. So the code looks like .As_is Process Table .As_is loop .As_is Process Row in the Table .As_is loop .As_is Process Item in Row .As_is end loop .As_is 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 .As_is 1 2 3 4 5 6 7 8 9 10 11 12 .As_is 2 4 6 8 10 12 14 16 18 20 22 24 .As_is 3 6 9 12 15 18 21 24 27 30 33 36 .As_is 4 8 12 16 20 24 28 32 36 40 44 48 .As_is 5 10 15 20 25 30 35 40 45 50 55 60 .As_is 6 12 18 24 30 36 42 48 54 60 66 72 .As_is 7 14 21 28 35 42 49 56 63 70 77 84 .As_is 8 16 24 32 40 48 56 64 72 80 88 96 .As_is 9 18 27 36 45 54 63 72 81 90 99 108 .As_is 10 20 30 40 50 60 70 80 90 100 110 120 .As_is 11 22 33 44 55 66 77 88 99 110 121 132 .As_is 12 24 36 48 60 72 84 96 108 120 132 144 Here is the code .See ../cs201/mtable.cpp Now figure out what this .See ../cs201/mtable2.cpp program does. . Can you explain the char ch; more clearly? .As_is 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 .As_is '?' .As_is 'a' .As_is '\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: .As_is 'a' + 2 is .As_is 'c' In consequence, we can go through the whole alphabet like this .As_is 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: not( p and q) == ( (not p) or (not q) ) not( p or q) == ( (not p) and (not q) ) You can prove this using truth tables. Try it! . Is there any reason to seed the number generator more than once? If not, why make a function for it? Why not just add it to the beginning of main()? I completely agree. . What are the commonest errors that happen in classes with member functions First there are all the errors with normal functions -- forgetting to specify the returned type, forgetting an '&' on a reference parameter, ... and so on. You have to be sure that functions have the right names and that the prototype/header matches its definition. With member functions you can access member data... and so these give rise to extra errors using up the wrong variable. . What is an oracle An oracle is a program that is given test data (possibly random) and predicts the correct result. You can then run the real program and find out if it produces the same results. Notice that an oracle is often good enough for deployment as the real solution to the problem... In UNIX your test shell script might look like this .As_is generate >test.data .As_is oracle correct.out .As_is program test.out .As_is diff correct.out test.out Which lists the lines where the oracle has done something different to the program. . How does a test harness work A test harness is just a normal main program the exercises the class/functions by calling them. It may out put results or use the `assert` function to test them. You have lots of code like this: .As_is TestClass object; .As_is assert(object.value() == correctvalue); .As_is object.doSomething(data); .As_is assert(object.value() == correctvalue2); . When should I use arrays and when vectors? Use arrays `only` when you know the maximum number of items that can be in the array before you compile the program. Arrays have a fixed number of items. Vectors can grow and contract as items are pushed and popped. Use arrays when their size is pre-specified and you need the program to run very quickly or do a lot of calculation. Vectors are slower than arrays because they are `dynamic`. In the future you will meet an advanced technique that lets you delay fixing the size of an array until after the program has started. However, once the storage is allocated to this "dynamic array" it can not expand or contract. If more data is needed then you must get more storage, copy the data to it and change the address of the array. But now you have merely duplicated the effort of the people who programmed the "" 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 .Key drivers -- Low level functions driving hardware in an operating system. Numerical methods solving large .Key mathematical problems. .Key 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: .As_is 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 .As_is type name [ size ]; then the bounds are 0 .. size - 1 . What is a bound error This is a programmer's mistake of going outside the bounds. This is not detected by the compiler. Typically they suddenly make a program behave very badly -- segmentation faults, frozen computers, stupid output.... quite unexpectedly. They are the commonest way that hackers can break into systems. .Close .Open C++ Background . What makes a computer translate its 0s and 1s into a language we can understand Programs. Luckily most of the input and output is translated by code that is in a special library so we don't have to worry to much about how this happens in this course... it is all "High Energy Magic". . How does a Control unit talk to other devices It use the computers "bus" -- a set of "wires" that connects all the parts of the CPU. Each "wire" can transmit a single bit {0,1} of information. The power of the CPU depends on how wide this "highway" is. We have had chips with 4 bit, 8 bit, 16bit, 32 bit, and 64 bit buses. . What were the first computers used for Pretty much what computers are used for now: mathematical calculations and data processing. This was all in "batch mode". You provided the input and got the answers days or even weeks later. Then came real time and interactive applications running on minicomputers. With minicomputers the first computer-based communications systems started leading to the Internet and the Web. The invention of the chip we made it possible for computers to control things from toasters to battleships by way of automobiles. . Why do we use g++ rather than gxx to compile things The people who wrote our compiler (the Gnu Project) chose the name 'g++'. . Does MS Windows come with a C/C++ compiler No. But CSE CSUSB students can get a free copy of the MS integrated Development environment (IDE) -- Visual studio. . Can you recommend a good free compiler for home use Try the Gnu compiler. But under MS operating systems expect your own C++/C programs to crash fairly often. . In order to program something does it have to be in a language that the computer understands Pretty much. What matters is if you have software that translates your program into the language that the computer "understands". Further, the computer/compiler/software relies on you using the language correctly. It will not correct your errors and will carry out the most stupid instructions just the way you wrote them. . Is C++ only code or do you need something else to make interactive programs that are more user friendly C++ does not define ways of doing complex graphical applications. However there are several libraries that let a C++ programmer do this kind of thing. In CS201 we will stick with the fundamental skills of programming rather than doing lots of specialized user interface libraries. . Why is C++/C more efficient than Java Because Java is not executed by the real hardware, it is executed by an interpreter called the Java Virtual Machine. This slows the program down. . Why is Java so easily converted between platforms Because Java is not executed by the real hardware, it is executed by an interpreter called the Java Virtual Machine. It is easy to move the JVM to a new platform. . What is value of interpreting vs compiling Interpreted languages (smalltalk) are easier to program, but compiled languages produce faster running programs. . Why was FORTRAN popular when COBOL had better data FORTRAN was (and is) popular with scientific programmers because it does precisely what they want: Formula Translation. Scientists don't need the complex data that COBOL is good at. . What is the different between static and dynamic linking Static linking is done before the program is run. Typically the library functions etc. are inserted in the executable by a link loader. Dynamic loaded modules are added to the program after it starts running as and when they are needed. Static linking is simpler and safer but not as flexible or efficient. . What is an object oriented program This is a program built bottom up from "object" -- little pieces of data and encapsulated knowledge that work together to produce the effect that the user prefers. .Close FAQs on Chapter 1 .Open 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. .List Parentheses (and Brackets) Multiply and Divide (left to right) Add and subtract (left to right) .Close.List . Do the precedences of C++ operators change in a program No. . Are there any confusing expressions Warning: look out for "^" it is not exponentiation. Warning: Look out for expressions like .As_is 2/3 because the computer sees two integers (2) and (3) and so does integer division giving the answer .As_is 0 To get "two-thirds" you need to force the compile to use double length calculations like this .As_is 2.0/3.0 Also .As_is 17 % 5 is valid and gives the remainder when 17 is divided by 5 == 2. . What are real numbers Numbers that can have any number of digits before and after the decimal point. Talk to the math department! . Can you have a double constant and how do you do it Yes. .As_is const double NAME = value; Example -- .Key mathematical pi \pi .As_is 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 .As_is float x; .As_is 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: .As_is double name; .As_is 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: .As_is int main() rather than .As_is 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 .Key unsolvable problems and Turing was able to show that no computer would be able to solve them. This is a fascinating and tricky topic that is covered in the CSci500 level theory classes. What we can say is that if any machine can do it then C++ can program it. . Can we make the the input and output look nice like Visual Basic Yes -- if you get a copy and #include the right library. On the other hand it is very easy to do once you've got the library. For example both our KDE Linux and MS Windows have nice user interfaces that let you draw forms and generate code for them. . I didnt fully understand ++ and -- (1) It is a subtle bit of C++. C++ lets you put ++ and -- operations inside expressions. They always add (subtract) one from a variable, but they also return a value. Suppose we have .Table i j k .Row 2 4 17 .Close.Table Then after .As_is k = ++ i; we have .Table i j k .Row 3 4 3 .Close.Table If we again start with .Table i j k .Row 2 4 17 .Close.Table Then after .As_is k = i ++; we have .Table i j k .Row 3 4 2 .Close.Table Summary of the rules .Table Expression Effect on i Returned value .Row i+1 None old i + 1 .Row i++ add 1 to i old i .Row ++i add 1 to i old i + 1 .Close.Table . Why is tracing a program helpful No other method gives you an understanding of what the computer is going to do. Once you have traced a program you can usually figure out what was going on. . What does cout mean This variable is pronounced "C out" and it means: the place where C output is sent. . What is a literal This is a value like 123, 1.23, or "Hello, World". It is a symbolic constant that represents itself. Numerical literals are normally typed using decimal notation (but C++ also does octal and hex if you need it). Strings like "Hello, World" as (currently) stored as a sequence of ASCII characters. . Is C++ used in Graphics, Games, Special Effects, Movies Yes. However in Movies the C++ will be hidden inside an interface for movie makers to use. . What does -= mean This is the "subtract from" operator. It one of a series of operators: .Table Short form Long form .Row x -= e; x = x - e; .Row x += e; x = x + e; .Row x *= e; x = x * e; .Row x /= e; x = x / e; .Row etc. .Close.Table .Close .Open Questions on ifs . When do I use if statements Any time that you need to make a program choose between two (or more) alternative sequences of actions. You should expect to be using `if` in every program you write. . Can you use if statements for things other than sales YES. We discussed calculations of date, pressures in vessels, tax rules, .... etc etc . . The example discounts in the book are wrong Quite possibly. . Is there a limit on the number of if statements in a program No. You can use as many as you need to make it work the way it should work. . Do you terminate an if with something like an ENDIF No. An if-else ends at the end of the statement after the else ... which may be a sequence inside {braces}. This is historical and saves typing. . What syntax is used to construct if-statements See above. What separates two independent if statements Nothing. For example .As_is if(A) .As_is B .As_is else .As_is C .As_is .As_is if(D) .As_is E .As_is else .As_is F . If you have a } do you need a semicolon Semicolons (;) in C++ are used to terminate expressions: .As_is x = e; .As_is cin >> x...; .As_is 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 .As_is } .As_is } .As_is } Sometimes I've even done this .As_is } } } . What does nesting mean Here is the example from class .As_is if( day == THU ) .As_is { .As_is if( time == 12 ) .As_is { .As_is class = 201; .As_is } .As_is else if( time == 12 ) .As_is { .As_is class = 375; .As_is } .As_is else .As_is { .As_is class = 0; .As_is } .As_is } . Isn't it not simpler to always use braces YES. But when i a hurray, in class, or short of space I often just forget them. Just like this: Here is the example from class .As_is if( day == THU ) .As_is if( time == 12 ) .As_is class = 201; .As_is else if( time == 12 ) .As_is class = 375; .As_is else .As_is class = 0; . Can you avoid complex nesting Sometimes by writing complex conditions. See below. . Can I chain conditions together like I do in VBasic .Box Can make this shorter by starting off with an example. Example: If you spend more then $100, bought exactly 5 items, and it was on the weekend. Only then would you win the super prize. Would a nested If inside a nested If be the only way to chain these 3 If's together? Or is it possible to somehow link them together in the first If statement like you can with AND in Visual Basic? .Close.Box YES you can chain these together, probably like this amount > 100 and number == 5 and (day == SATURDAY or day==SUNDAY). .Close .Open Questions on logic . What does using namespace std mean and why do we use it A `namespace` is a collection of names. The namespace `std` contains many useful names including `cout` and `cin`. The `using namespace` allows us to write these without saying which namespace they are in. Professional tend to be more careful with "using namespace" and only use shorthand for parts of libraries that they need. . The libraries that we #include are they real files Yes. They are placed in /use/include in most UNIXes. Many of them are files with the extension '.h' for header. You get them from the same place as the compiler. . How do you code exponents in C++ Mathematical expressions `x to the power y`, for general `y` are written .As_is pow(x,y) using the <> library. The mathematical exponential function ` e to the x` can be written .As_is exp(x) using the same library. The parentheses are essential. . How many libraries can you include in one program As many as you want. . Can you have pi in a program without cmath Only if you type in the value of \pi yourself or set up a constant .As_is const double PI = 4*atan(1); . What is the reason that x and y == 0 is not (x==0) and (y==0) Tradition. It comes from the precedence rules that make 'and' have a higher precedence than '==' so that "x and y == 0" means .As_is (x and y) == 0 . What programs have logical expressions Nearly every program needs conditions and the simplest way to write these is nearly always using logical operators. . What types of programs have truth tables Not many..... BUT truth tables `are` a good way to think about complex conditions. . Can we use the comparison operators Yes. Indeed you will and must use them. . When do use the not operator You use it when you have written an expression but realize it is the opposite of what you wanted. The you put "not("...")" around it. . How many different comparison operators are in C++ 6 . How many different logical operators are in C++ 3: not, and, or. See below. .Table p not p .Row true false .Row false true .Close.Table .Table p q p and q p or q .Row true true true true .Row true false false true .Row true true false true .Row false false false false .Close.Table . How many must we know All 3 logical operators, and all 6 comparison operators. . Are there only 3 logical operators in C++ Yes -- kind of. The 6 comparison operators can also be used to compare $bool expressions. For example .Table p q p> variable); . Why does not have a different priority to and and or (1) not is a prefix operator. The other two are infix operators. (2) The is a long long tradition of having `not` act on the following simple condition rather than a group: .As_is not today and tomorrow means: .As_is (not (today)) and tomorrow not: .As_is not (today and tomorrow) . What does bool actually do It reserves a piece of storage that can hold one of two values. . Is a while statement a kind of loop Yes. . Is a while statement the same concept as a loop No -- some loops are not while loops. .Close .Open Questions . Why are break statements so bad They have been implicated in causing disasters. The `break` has two distinct meanings and some people for get this and produce code that does not work properly. Secondly, `break` skips over statements to get to the end of the loop and this is easily forgotten. The fact is you can program anything with if and while. So rather than code like this .As_is while(true) .As_is { .As_is A .As_is if( B ) .As_is { .As_is C .As_is } .As_is else .As_is break; .As_is D .As_is } You can, instead use a bool flag. .As_is bool ok = true; .As_is while(ok) .As_is { .As_is A .As_is if( B ) .As_is { .As_is C .As_is } .As_is else .As_is ok=false; .As_is if( ok ) .As_is { .As_is D .As_is } .As_is } I'll be happy if you don't use break in projects. I'll only penalize you if it goes wrong! It won't appear in quizzes, finals, or labs. . Can you explain for loops For loops are compact way of writing counting and scanning loops. .As_is for(A; B; C) {D;} is shorter than .As_is { A; while(B){ D; C; } } and does the same thing. . Should you use while or for Use for for counting and scanning. Use while for all other iterations. Most for-loops look like one of these .As_is for ( i=0; i < ...; i++) .As_is for ( i=1; i <= ...; i++) .As_is for ( i=...; i >=0; i--) . How many Layers deep have you gone in nesting while statements I'm not sure.... I've written for-loops at least 3 and possible 4 deep. I've never worried about it. . How does an if differ from a while An if selects one of two alternatives. A while repeats a sequence until a condition become false. . What does fabs mean It means "Floating-point Absolute Value". It does something like this .As_is if( x < 0 ) .As_is fabs=-x; .As_is else .As_is fabs=x; . What is your opinion on using the Microsoft Visual C++ expression editor I've found the "Visual" environments (except the original VB) to need a lot of setting up -- I've usual given up. . Are loops the same as while statements No. There are two kinds of loop (for and do-while) that are not 'while' statements. . Is Linux/Unix an OS just for programmers or can average users use it I think that Linux KDE is better than Vista! But it is striking that Apple Macintoshes come with a version of Unix and the users a smugly happy with it: "It just works". On a lighter note.... here is a fun video on the topic .See http://video.google.com/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! .Close .Open Questions . What is tracing and how is it used Tracing is a process of seeing what the computer does when a program runs. It shows every value if every variable at each step of a program. The best way to do this by hand is in a table with variables as the heading. Tracing is used as the first step to understanding a program. It is also a useful training technique and diagnostic test of how well you understand something. We traced a piece of code like this in class: .As_is int t = 0; .As_is for (int i=0; i < 5; i++) .As_is { .As_is t = t + i; .As_is cout << t << endl; .As_is } .Table Statement\Variables t i cout .Row t=0 0 ? ? .Row i=0 0 0 ? .Row i<5 .Row t=t+i 0 0 ? .Row cout 0 0 0 .Row i++ 0 1 .Row i<5 .Row t=... 1 1 .Row cout... 1 1 1 .Row i++ 1 2 .Row i<5 .Row t... 3 2 .Row cout 3 2 3 .Row ... .Row cout 10 4 10 .Row i++ 10 5 .Row i>=5 .Close.Table . What is a for statement for To count and to scan across containers. . What is another way to work with loops I only know of the ways I have taught you. . Is there a way to do both for and while statements without getting confused Practice. . What does ! mean not . if statements and iomanip You don't need any libraries to use if. . Difference between float and double Both store real numbers. Float uses less space and may run faster. Doubles have more significant figures. . How are arrays and vectors helpful Doing without them is painful in the extreme -- believe me! . Why can't we use vectors instead of arrays Their are only two reasons for using arrays: (1) they are efficient (faster, less wasted space) and (2) you have to fit with software that uses an array. . Can vectors be used in place of arrays Yes! In this class -- use vectors whenever you have the option. . When do I use vectors Nearly Always! Exception... I know that I need precisely <...> items. Example: 9 squares on a Tic-tac-toe board. . What are vectors actually used for Storing a collection of data items in memory and to allow us to reorganize the data. . What kind of program uses arrays vs vectors Old programs used arrays -- no choice. Modern programs tend to use vectors. Exception to speed up code. . How does the size of an array relate to the last subscript If the last subscript is 5 then the size will be 6 elements. . Can you give a clear definition of an array A fixed number of items of the same type numbered from 0 upward and stored in adjacent pieces of remarry memory. . What happens if we put a string into an array of ints C++ will convert the string into an address and store that! . What functions are part of the vector library Check out the documentation in .See ../samples/stl.html#Vectors .See ../c++std/cd2/lib-containers.html (from the draft standard...) .Close .Open Questions . When we write a loop must we separate the different conditions on different lines You don't have to. The compiler will compile the same condition independent of the layout you choose. But one way to make conditions clear and easier to understand is to separate them. When you format code tidily you will make fewer logic errors. . How do loops work It depends on the loop. If it is a while loop like this: .As_is while ( C ) { B } then the computer does the following .List Evaluated the condition `C`; If the result is `true` then Execute all of B and go back to step 1. If the result is false then continue .Close.List You get a pattern like this: C; B; C; B; C; B; .... B; not C; A for loop like .As_is for (A; B; C) { D } is more complex .List Execute A Execute B and test it. If the result is true then .List Execute D Execute C Go back to step 2 above. .Close.List If the result of B is false continue .Close.List (Note: memorize this!) In short the pattern is A; B; D; C; B; D; C; ...; C; not B. . When can we use loops in programming Whenever you have a set of statements that need to be repeated several times you should use a loop. Whenever your algorithm talks about "repeating steps.... until ..." or "Do .... until ..." then you must use a loop. Note: Writing an .Key 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. .As_is file...............:Line#:.... .As_is 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 .As_is 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 .As_is 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 .See http://en.wikipedia.org/wiki/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 .As_is Cat the mat on sat. is a compile (syntax) error. But .As_is 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 .Key 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! .Close .Open Questions . What are the limits of error messages The can spot syntax errors and warn you of one or two logic or execution errors. . How to combine if and while statements It depends on the algorithm you are trying to code.... when you have more than two or three ifs and whiles you need to first sort out your algorithm.... your plan of how to solve the problem. If part of the algorithm reads .As_is If A is true then do B while C is true else do D. Then you'll probably have .As_is if(A) .As_is { .As_is while(B) .As_is { .As_is C .As_is } .As_is } .As_is else .As_is { .As_is D .As_is } Notice the careful indenting to make the structure obvious. Another classic part of an algorithm puts the if inside the while: .As_is Repeat the following until A is false .As_is If B is true then do C else do D becomes .As_is while(A) .As_is { .As_is if(B) .As_is { .As_is C .As_is } .As_is else .As_is { .As_is D .As_is } .As_is } 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: .As_is vector example(1100); Then you can access the first element as .As_is example[0] The 115th item .As_is example[114] The last item .As_is example.last() More you can access a whole subset .As_is for(int i=114; i<120; i++) .As_is { do_something with example[i] .As_is } . How to character literals work The compiler spits the blip (') on the input and enters the code for translating character literals. This code puts the right character or pattern of bits into a one byte storage area: .List If the next character is a blip(') then report a compile error. If the next character is not a backslash (\) then that `is` the character to store. If the character after that is not a blip(') report compile error and exit. But if it is... store the character and exit. If the next two characters are a backslash followed by a 0 then translate the string from octal to binary. If the next three characters are a backslash followed by an x and a 0 then translate the string from hexadecimal to binary. Else compile error. .Close.List (Note 1 -- I let you work out the details). (Note 2 -- I'm guessing about the algorithm). . Can you teach us to write in binary Yeah -- easy. Just pick a few `binary digits` -- each one either a '1' or a '0'... .As_is 1101101 You interpret these as a number by using powers of 2: .As_is 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: .See ../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: .See ../cs201/backwards.cpp , you can download this and compile it into an executable called `backwards` and then try this command .As_is ./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 library where ever you use C++. The word class means that strings are objects and we can do things them like this .As_is object.operation( data ). A string, in theory, has these operations: .Table Theory C++ Concatenation s1+s2 Substring s.substr(start, size) Find matching substring s.find(match) Find number of characters in string s.size() Get the i'th character s[i] .Close.Table . How do strings differ from character arrays Strings have a lot of useful operators that arrays don't have. Arrays have a fixed size and this makes them hard to use. Strings automatically get the storage they need when they grow. Automation makes strings easier to use. Please use strings when ever you can! . Is there a limit to the number of characters in a string Not really. I think you can fill up the whole of the virtual memory given to you program in a string -- 1 byte to a character. . What is MS-DOS DOS stands for "Disk Operating System" and MS-DOS was Microsoft's first big contract -- to supply a Floppy Disk-based Operating System for the new IBM Personal Computer. When you open the Command Line/ Run Command box in Windows you can input a MS-DOS command. .Close Questions .Open Questions on Functions . Can you explain Binary Search Binary search search a collection of items by dividing them in half and then picking one half to search. It is a common example of a .Key divide and conquer algorithm. You can use the algorithm to search anything that is in the right order. The white pages of a telephone directory is one example. To find a name in the directory, you put your finger in the middle of the directory. The name is either before or after your finger. Pick the correct half. Again, divide the pages you are search into two halves, and pick the right half. Continue until the page you want is in front of you. Try it on any order list, array, or vector... . What is the purpose of functions that return a value They defines a short hand way of doing a long calculation. You can get the calculation by just calling the function. You can share it with other people as well. . Are there an infinite number of functions in C++ There is a potential for an infinite number, but any given program can only have a finite number. . Is there any limit on the number of functions No. . Can you put if and while inside a function Yes. . Can you define a function inside a function No. . Can we use functions in place of anything I guess so. . In simple words what is a function A named piece of code that you can use many times in many ways. . How are functions declared Functions a declared by writing the header: type_of_data_returned name_of_functions ( parameters ) From then on (but not before) you can use that function in the program. More in the next class on this topic. . Can you explain the fmod function Here is a working program .See ../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 .Key procedures are called .Key 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 .As_is return result; . Do you declare functions before main Yes. You have to because you can only use a function after the compiler has seen a declaration (the header) of the function. Before then the call will not compile. . Can functions produce non-numerical results Yes. Functions that return bool are good for testing and are called `predicates`. Functions returning strings and characters are also useful. Beware, however, of returning arrays from a function. The results are not good. . How do functions use parameters First they evaluate them. Then they move the values to the initialize the formal parameters -- just as if they are local variables. More on this in the next lecture/discussion. . What is a block A function with no name! More officially it starts "{" and ends "}" and has at least one declaration. . How can variables be declared in blocks Just like they are declared in the main program. . Can things be declared outside a block Yes. Functions must be outside a block (with a couple of exceptions mentioned later this quarter). Variables can be declared outside a block. They are called .Key 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 .Key global constants and are a very good way to define natural constants and numbers. The classic example being .As_is const double PI = 4*atan(1); Here is another: .As_is 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. .Close .Open Questions . How does a search know what number to search for You have to have a parameter or variable that contains the target number. I usually call it `target`. If you need to get both the `target` and the numbers into the computer from the user in this course you will either need to read in the number of numbers first and then the target (or targets). An alternative is o read in a single target first and then read in all the numbers until CTRL/D. . How do you compare to strings If you have two strings, like this: .As_is string s1.... .As_is string s2.... Then you can use the same operations as you do with ints: s1 == s2 s1 != s2 s1 <= s2 (lexical order) s1 >= s2 (lexical order) s1 > s2 (lexical order) s1 < s2 (lexical order) If the data are null-terminated character arrays (texts) then you need to use: .As_is strcmp( "abc", "abd") which returns the difference of the first two characters that a not equal. It give 0 if the two arrays are equal. . How are functions used Functions are used when they are included in a program and then called. You should use them to contain common calculations and tasks. They let a single statement of simple expression stand for a complex computation. . What functions help you round numbers in different ways You get standard rounding when ever you assign a double to an int variable. This converts the double to the nearest int. The .Key cmath library has two functions that convert doubles to integers. They are named `ceil` and `floor`. The function .Key ceil returns the smallest integer that is not less than the value of the parameter -- the ceiling above the number. The function .Key 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: .List reference parameters default values for parameters recursion etc. .Close.List . 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 .As_is #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. .Close Questions .Open Questions . How is numeric data important Counting and measuring are key human activities. Starting with money, lengths, land, volumes, weight, ... we have always needed to compute with numbers -- or get cheated. So understanding how numeric data works (and sometimes fails) is a useful piece of knowledge. . What predefined data types are most useful when starting C++ . Which predefined data types will we actually be using Use int to count and scan, use double for measurements, and strings+chars for non-numeric data. . How does a computer work A computer has a control unit(think: dumb brain), an arithmetic-Logical Unit (ALU) (think: calculator), primary memory(think: working space), secondary memory(think: file cabinet), and input/output(think: in and out trays). The primary memory is divided into numbered memory cells each holding one $byte of information. A control unit has a program counter (PC) that counts instructions and follows the Van Neuman cycle: .List Get the next instruction from location PC. Decode the instruction into operations and the address of data. Get the data form primary memory and move it to the arithmetic logic unit. Tell the ALU to do the operation Send the result back to somewhere in memory. Compute a new value for PC and return to the first step. .Close.List Note: some instructions skip steps. For example, Branch instructions often just move the address into the PC. . What determines the size of data types on a machine Nearly all machines have a fixed size for int's and one for doubles. I've only know one where you can change the "word size" as it ran. It didn't survive in the market place. . What is a float In C++ it is a number that has a floating decimal point but is not as large, slow, or precise as double length. The details do not matter much! . Is there a limit on the size of floating point numbers. Yes ... also on the precision. But it all depends on the CPU you have and the compiler you are using. However there is a library or that defines constants like FLT_MAX, DBL_MAX, and LDBL_MAX the maximum representable number in each of float, double, and long double. The or library does something similar for chars and its. By the way, these days all CPUs are using the IEEE Standard floating point notation (ANSI/IEEE Std 754-1985) which defines the limits and precisions. Notice: all computation is limited by the amount of memory available. . What is the purpose of the sizeof operator It tells you how many bytes the compiler has given to a variable or to a data type. The lab will give you many examples... . . How do bits store information A bit can be made to stand for a single true/false or 1/0 decision. Two bits can handle four different cases. All we need to do is to decide what each combination means. Similar 8 bits can handle 8 different meanings. Here is how we would make them encode unsigned and signed numbers and as Days of the week: .Table Bits Unsigned # Signed # Day of Week .Row 000 0 0 Sun .Row 001 1 1 Mon .Row 010 2 2 Tue .Row 011 3 3 Wed .Row 100 4 4 Thu .Row 101 5 -3 Fri .Row 110 6 -2 Sat .Row 111 7 -1 ERROR .Close.Table The information has to be encoded as data. In effect we give each bit a particular meaning. We usually do it character by character. But good examples include the UPC code or the International codes for Airports. Exercise: work out a one letter code for the days of the week. Exercise: work out a two letter code for the months. . Who put binary code together I think it was Liebnitz in the 1600's. The Chinese used something like it thousands of years ago. . How are letters changed to binary When you tap a letter on the key board a particular set of contacts is made. The ASCII code specified that 'A' was 01000001 and that B would be next... and so on up to 'Z', 'a' starts with 01100001, and so on up to 'z'. It was a committee decision by the American Standards people. . Does every key on the keyboard have a special number The main keyboard A-Z0-9....{}[];:....!@#$... are all one byte ASCII numbers. The arrow and function keys use a sequence of 2,3, or 4 one byte codes developed by ANSI... . Does the operating system determine the word size -- Vista comes in 32-bit and 64-bit versions I think that this indicates the size of an address in programs running under the operating system. I don't think it changes the amount of data the CPU handles in one cycle. I think that the sizeof operator may well give the same sizes, for example, whatever the operating system is. . Why are there 8 different predefined data types This is how C evolved. The book doesn't mention some of them like $wchar (wide character). . What is the method used to store positive and negative numbers It is called twos-complement... The Wikipedia article .See http://en.wikipedia.org/wiki/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 .See http://en.wikipedia.org/wiki/Boolean into the Wikipedia will lead you to more than you need to know about things Boolean. .Close Questions .Open Questions . What should I use instead of a break statement I tend to use Boolean variables plus if-else statements. As a simple example: .As_is for (i=0; i vpt; declares a variable `vpt` which is a vector of pointers to data of type T. These are often used in advance object-oriented code. . What is a lingering Pointer This happens when you use a pointer to allocate memory that has been deleted. The data is no longer there and the program (with luck) crashes. . How do you use a lingering pointer You avoid it like the plague. Some years ago I was working on a complex interpreter for the language Prolog for use in CSCI320 (Programming Language). It had a very strange bug that would some times pop up and crash the system -- in one laboratory but not the other lab! I thought it was the print routine, but I couldn't see anything wrong in it. Then I noticed that the crash only occurred when a variable appeared twice in an expression -- in one lab only -- the lab that used some IBM UNIX workstations. And I remembered that IBM computers tend to remove primary from a program when you deallocate it, but other manufacturers let you keep the storage in case you wanted to reuse it. Suddenly it dawned: When one variable appeared in two places the garbage collection routine was deleting the storage twice. The first time was ok but left a lingering pointer. The second time the IBM computers crashed the program. It took about 20 minutes of programming to fix the deletion routine to work properly..... . Can there be any use in garbage -- allocated memory with no pointer We call it `garbage` because it can't be used any more. It is wasted space. We can't even delete and so recycle it. It is in the computer's land fill: the `heap`. However when the program finishes all the memory is given back to the operating system. .Close.Table .Close Questions .Open Questions . What are declarations A declaration reserves some storage and gives it a name. It may also put data in the storage. . Please explain the void parameter and its use in more detail If you declare a function like this .As_is .... fred (void )... then the compiler will object if you ever write any call of `fred` with data in it: .As_is ...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 .As_is int sum(int a[], const int N) .As_is { .As_is int sum =0; .As_is for( int* p = a; p < a+N; p++) .As_is sum = sum + *p; .As_is return sum; .As_is } . What does the command char do The keyword `char` is the name of a predefined type -- the computers standard character type -- these days coded as 8 bit ASCII. Because "char" is the name of a data type you use it primarily to declare variables and constants: .As_is char input; .As_is 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: .As_is char example ( char para ) { return para + 1; } . What is typedef The typedef key word (notice the spelling) is used to give a new name to a complex data type. Giving things well chosen names makes them easier to understand. You use "typedef" by writing it in front of any normal looking variable declaration: .As_is typedef vector 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 .As_is 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: .As_is light=0; .As_is ... .As_is light=1; .As_is ... .As_is 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: .As_is enum StopLight {red,yellow,green}; .As_is ... .As_is StopLight light; .As_is ... .As_is light=red; .As_is ... .As_is light=yellow; .As_is ... .As_is light=green; And if you find me doing something like .As_is light = light * green; you can be pretty sure I've made a mistake! Here more examples: .As_is enum TicTacToeSymbol {empty, oh, cross}; .As_is enum LifeState {dead, alive}; .As_is enum Month{jan, feb,mar,apr,may,jun,jul,aug,sep,nov,dec}; .As_is 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 .As_is const string tttout[3]={" ", "O", "X"}; So no I can output a particular place on the board like this: .As_is 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: .As_is 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. .As_is TicTacToe board[3][3]; // 9 cells in a square array .As_is LifeState plane[100][100]; // for Conway's game of life You access elements in these arrays like this: board[0],[1], plane[24][42], etc. Once you have got a TicTacToe board and a array tttout defining how to output the symbols you display a board like this .As_is for(int row=0; row < 3 ; row++) .As_is { .As_is for(int col=0; col < 3; col++) .As_is { .As_is cout << " " << tttout[ board[row][col] ] ; .As_is if(col < 2) .As_is cout << " | "; .As_is } .As_is cout << endl; .As_is if( row < 2 ) .As_is cout << "-----" << endl; .As_is } (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: .As_is 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! .As_is 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]. .Box Be happy you have multidimensional arrays. When I started out I didn't have them in my programming languages. I will not forget in hurry a friend who need a 5><5 square and declared 5 different arrays: .As_is 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 .As_is double a[25]; and had to mentally transcribe `a[r,c]` into .As_is a[ 5 * r + c ] every where... .Close.Box . If we want to combine 2 different arrays do the rules of matrix addition and multiplication apply NO. Sadly, no. .... You can not add and multiply arrays in C++ unless you have included definitions of the operations. You'd have to hunt for these on the Internet. Don't get me on the topic of programming matrix operations. I have had to do it in two different jobs and did four years of college work on them.... .Close .Open Questions . Why is information added before the main program doesn't the compiler ignore it The only things that the compiler ignores are comments. They are used to help human beings understand the program... including your future self. There are two kinds of comment. The big comments take up many lines and start with .As_is /* and end with .As_is */ You can also add comments at the end of a line by first putting .As_is // 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 .As_is cout << signum(-17) <