Exam 2 Review - Engineering 101 Quote of the Day There are...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Engineering 101 Quote of the Day There are 10 types of people who understand binary, those who do and those who don't. - Overheard in WoW Exam 2 Review Outline Lectures 1 through 7 (you still need to know them) them) Lecture 8 Loops Lecture 9 Data Types Lecture 10 Static variables/scope/lifetime Lecture 11 Strings Lecture 12 Vectors and Vectors of Vectors Lecture 13 Sorting and Recursion Lecture 8 Loops Outline Lectures 1 through 7 (you still need to know them) them) Lecture 9 Data Types Lecture 10 Static variables/scope/lifetime Lecture 11 Strings Lecture 12 Vectors and Vectors of Vectors Lecture 13 Sorting and Recursion Not All Loops Count For example you could have a loop that prompts a user for input until it gets a number between 1 and 10: 10: cout << "input a number from 1 to 10:" << endl; endl; cin >> x; while (x<1 or x > 10){ cout << "Outside range! Try again:" << endl; endl; cin >> x; } Simple Counting Loops Commas can be used to include multiple initializations or counters i=1; n = 5; while (n<N){ do something i = i*n; n = n + 3; } Initialization Continuation Counter for(n = 5, i=1; n<N; i=i*n, n = n + 3){ do something } 1 Loops Can Reside Inside Other Loops 1x1=1 2x1=2 3x1=3 1x2=2 2x2=4 3x2=6 1x3=3 2x3=6 3x3=9 Loops Can Reside Inside Other Loops 1x1=1 2x1=2 3x1=3 2x2=4 3x2=6 3x3=9 int a, b; for(a=1; a<=3; a++){ for(b=1; b<=3; b++){ cout << a << " x " << b << " = " << a*b << " "; } cout << endl; } int a, b; We can eliminate the upper for(a=1; a<=3; a++){ triangle by varying the loop for(b=1; b<=a; b++){ cout << a << " x " << b << " = " << a*b << " "; } cout << endl; } Outline Lectures 1 through 7 (you still need to know them) them) Lecture 8 Loops Lecture 9 Data Types Lecture 10 Static variables/scope/lifetime Lecture 11 Strings Lecture 12 Vectors and Vectors of Vectors Lecture 13 Sorting and Recursion Data Representation All data inside the computer is represented by bits. Bits can have only two values 0 or 1. 4 bits make a nibble 8 bits make a byte 11001010 10101011 How many things can you encode with a byte (8 bits)? Each bit allows two possibilities. 1 bit: 0 1 (2 things) 2 bits: 00 01 10 11 (4 things) (8 things) 3 bits: 000 001 010 011 100 101 110 111 n bits: 2n things 8 bits: 256 things Base 2 is a number system like base 10 110001 32 25 1 16 24 1 8 23 0 4 22 0 2 21 0 1 20 1 1 x 25 + 1 x 24 + 0 x 23 + 0 x 22 + 0 x 21 + 1 x 20 110001(base 2) = 32+16+1 = 49(base 10) 2 Adding Binary Numbers 11 01100 01110 11010 (8 + 4 = 12) (8 + 4 + 2 = 14) (16 + 8 + 2 = 26) Overflow in Binary Addition Typically we are limited to representing a number by a certain number of binary digits. Let's say we are using 4 bits and want to add 1110 and 0010 The answer is 10000, but we only have 4 bits so the extra 1 is lost and we reset to 0000 This is like the odometer on your car. Such overflow can lead to funny unexpected results. + Subtracting Binary Numbers 02 01120 00110 00110 Negative Binary Numbers How do we encode negative numbers in binary? Consider our 4 bit overflow problem. - But we may have to carry much as we would in decimal subtraction. 1111 + 0001 = 0000 Also, 0000 0001 = 1111 This implies that 1111 in our 4 bit representation could stand for -1 Negative Binary Numbers (32 bit, 2's-Complement) 2's00000000000000000000000000000100 = 4 00000000000000000000000000000011 = 3 00000000000000000000000000000010 = 2 00000000000000000000000000000001 = 1 00000000000000000000000000000000 = 0 11111111111111111111111111111111 = -1 11111111111111111111111111111110 = -2 11111111111111111111111111111101 = -3 11111111111111111111111111111100 = -4 You can find the negative of a number by flipping all the bits and adding 1. int Other Integer Types standard integer 4 bytes -2147483648 to 2147483647 unsigned int cannot be negative 4 bytes 0 to 4294967295 char bool a character: `a', `D' 1 byte true or false 1 byte 3 char type holds individual characters Characters can be converted to integers. We denote char literals by enclosing them in single quotes like: `F' There are a number of whitespace characters to denote spaces ` ', tabs `\t', newlines `\n', etc. ', t', n', Lecture 8 Loops Outline Lectures 1 through 7 (you still need to know them) them) Lecture 9 Data Types Lecture 10 Static variables/scope/lifetime Lecture 11 Strings Lecture 12 Vectors and Vectors of Vectors Lecture 13 Sorting and Recursion Constants If you want a variable to never change in the context of the code you can define it to be a const const double speedoflight = 3e8; Note that const does not replace the type, but rather it modifies the data type. Aliases (References) We can declare a new variable that is a stand-in for an standother variable. double v = 5.0; double & w = v; cout << w << endl; endl; The above code will print 5.0 because v and w are the same variable. Note: References cannot be changed after they are created (i.e. you can't make `w' refer to something else). Aliases (References) We have already used such variables implicitly when we do pass-by-reference. pass-byWe can make a reference that is a const. That means that the reference version cannot be changed. double v=5.0; const double & w = v; v = v + 1.0; w = w + 1.0; This can be useful for passing data without having to copy it, but also without allowing changes. Scope Scope: the context in which an identifier is meaningful. meaningful. An identifier in a compound statement has local scope. It is in scope from the time it is scope. declared to the end of the enclosing braces. A function parameter is in local scope from the beginning of the function body. 4 Scope void f ( double x) { int i = 1; cout << i << " "; int j = 2; cout << j << endl; cout << x << endl; } Scope You cannot declare two identifiers with the same name in the same compound statement. statement. You can declare an identifier with the same name in a different compound statement. x i j If there are different possible identifiers that could be referred to, the most local version is always chosen. The less local versions are chosen. "hidden" this is also referred to as being "shadowed". Scope main () { int i = 5; { cout << i << endl; endl; int i = 2; cout << i << endl; endl; } } int main( ) { int i = 10; Messy Scope // This will print 5 // This will print 2 since // the new i shadows // the old i } while (i > 0) { cout << i << endl; int i = 5; cout << i << endl; i--; --; } return 0; // This sets up a local scope "i" that // prevents the loop from terminating Lifetime The lifetime is the span of time during which a particular data object can be accessed. accessed. When the lifetime expires the data object is returned to memory for general use. Referring to the identifier after this time can produce strange results. Lifetime main () { int i = 10; while (i > 0) { (i 0) if (i > 5) { (i int j = i; // j has no lifetime unless i > 5 cout << j << endl; endl; } cout << i << endl; endl; i--; --; } } 5 Global Constants Some objects have local scope. A good example are functions and procedures themselves. You can make identifiers have global scope. Global identifiers are a bad idea for non-constant nonidentifiers, since they can change in a procedure or function without explicitly being passed in. Lecture 8 Loops Outline Lectures 1 through 7 (you still need to know them) them) Lecture 9 Data Types Lecture 10 Static variables/scope/lifetime Lecture 11 Strings Lecture 12 Vectors and Vectors of Vectors Lecture 13 Sorting and Recursion Data Types and Classes Data Types Definition a set of possible values plus, plus, a set of legal operations on those values Declaring and Defining Data Objects General form: T identifier(arg_list); identifier(arg_list); Where: T is the type (class name) identifier is an identifier arg_list is a comma-separated list of zero or more commaarguments (depending on T) for example (int): (int): Integers within a given range Operations: addition (+), subtraction (-), etc. (+ (- C++ class mechanism: A general way to define new data types Example classes: istream, ofstream, string, ... Object-oriented programming : an approach emphasizing design and use of classes of data objects In this course we use classes, but will not define our own Examples: ifstream infile("input.dat"); infile("input.dat"); int i(0); Same as: int i = 0 Invoking Methods To call a method for class member X: x.method(arg_list) method(arg_list) Where: . is the member selection operator method is the name of a method (member function) (member function) arg_list is a comma-separated list of zero or more arguments comma(depending on method) #include <string> Often the data we want to work with is not number, number, but rather text. text. Declare a string: string name; Initialize a string: name = "Jeff"; -or- string name("Jeff"); or- Examples: infile.open("myinput.txt") infile.open("myinput.txt") infile.close() infile.close() cin.fail() cin.fail() Add strings: name = name + "Ringenberg"; "Ringenberg"; 6 Comparing Strings s < s2 Evaluates alphabetic order s > s2 s == s2 s <= s2 s >= s2 Note, however, that upper and lowercase letters are considered different. Uppercase letters come before lowercase letters alphabetically. Spaces and other characters are counted also. Line Input void getline(istream & in, string & line) Reads a whole line from an input stream, stores in a string Useful for extracting input with whitespace Operation >> getline Leading whitespace skipped included Termination condition any whitespace char newline ('\n') Consumes terminating character? no yes Strings as Compound Data Objects Compound data object: object: composed of more primitive data objects Arrays Compound data objects: Comprised of a (potentially large) number of data items (elements) of the same type elements) Maintained in a sequence Supports reference by index (number in sequence) Strings are compound data objects, because they are composed of sequences of chars. In fact, the internal representation of a string is essentially this: "Michigan" 'M' 'i' 'c' 'h' 'i' 'g' 'a' 'n' Array Index: Allows for random access Starts at zero (first element) Subsequent elements defined by offset from first element Reference an element of the array using the indexing operator : : array_name[index] array_name[index] identifier of array type integer expression Referencing Warning C++ allows you to reference outside the range!! string s("Michigan"); cout << s[-1] << s[10]<<endl; s[This will produce some unpredictable results! Strings: at( ) We can use the safer version of addressing, the at method string t("Silence"); t.at( 2 ) = t.at( 1 ); t.at( 1 ) = `c'; cout << t << endl; The at( ) method checks to see that you don't address beyond the length of the string. It does not always check for negative addresses. 7 Other String Methods s.size( ) s.append(s2) s.push_back(c) s.find(s2) Number of chars in the string Appends s2 to s Appends char c to s Search for s2 in s and returns the location of the first character of the first match starting with zero or s.npos if not found string s("alex"); cout << s.find("ex"); // outputs 2 More Methods s.insert(offset, s2) s.erase(offset, num) s.replace(offset, num, s2) s.substr(offset, len) Insert s2 in s starting at offset erase num chars from s erase plus insert returns a new string that is the part of s that starts at offset and is len long if(s.find("la") == s.npos){ cout << "didn't find la in " << s << endl; } string mystring("Michigan"); cout << mystring.substr(1,4); ichi Outline Lectures 1 through 7 (you still need to know them) them) Lecture 8 Loops Lecture 9 Data Types Lecture 10 Static variables/scope/lifetime Lecture 11 Strings Lecture 12 Vectors and Vectors of Vectors Lecture 13 Sorting and Recursion #include <vector> Often times we want to make lists of things that are not characters Vectors can be used to make lists of anything: int, double, char, string, .... int, To declare a vector you have to specify the type you are making a list of. of. vector <type> identifier; identifier; Vectors A vector is a Generic Type: It can only be created by parameterizing it on another type Vectors Typically we also want to tell how long this list will be: be: vector <int> intlist(5); <int> intlist(5); We can also specify what to initialize the values in the list to: vector <int> intlist(5, -1); <int> intlist(5, Individual parts of the list can be accessed using array semantics or the .at() method: intlist[ intlist[ 1 ] = 10; intlist.at(1) = 10; intlist.at(1) For example: vector <int> intlist; <int> intlist; vector <double> doublelist; doublelist; vector <string> stringlist; stringlist; 8 Vectors Other methods also exist to manipulate vectors: v.back( ) v.front( ) v.empty( ) v.clear( ) refers to the last element refers to the first element true if the vector is empty empties the vector Vectors Other methods also exist to manipulate vectors: v.pop_back( ) v.push_back(e) v.resize(newsize) v.resize(newsize,e) removes the last element appends another element changes size of the vector and puts e into any new elements Vectors Vectors can also be used to store lists of lists vector< vector <int> > table; Vectors of Vectors Creating of Vectors of Vectors: The easiest way of assigning data to the elements vector <double> row(3, 0.0); vector <vector <double> > PlanetData(3, row); Don't forget the space here! Vectors of Vectors Accessing of Vectors of Vectors: Printing the data vector <double> row(3, 0.0); vector <vector <double> > PlanetData(3, row); int i, j; for(i=0; i < PlanetData.size(); i=i+1){ for(j=0; j < PlanetData.at( i ).size(); j=j+1) PlanetData.at( ).size(); cout << PlanetData.at( i ).at( j ) << " "; PlanetData.at( cout << endl; } Outline Lectures 1 through 7 (you still need to know them) them) Lecture 8 Loops Lecture 9 Data Types Lecture 10 Static variables/scope/lifetime Lecture 11 Strings Lecture 12 Vectors and Vectors of Vectors Lecture 13 Sorting and Recursion 9 Exercise Recursion A program that calls itself is called recursive. recursive. Example: int factorial (int n){ if (n==0) return 1; else return n* factorial(n-1); factorial(n} find( ) locates a number in a sorted list. What parameters should be passed in the last call to find()? 1- list, mid+1, end, num 3- list, mid-1, end, num mid2- list, begin, mid+1, num 4- list, begin, mid-1, num mid- int find (const vector <int> & list, int begin, int end, int num){ int mid = (begin + end)/2; if (list[mid] == num) return mid; if (list[mid] < num) return find(list, mid+1, end, num); if (list[mid] > num) return find( list, begin, mid-1, num); mid- num); } Good luck on the exam! 10 ...
View Full Document

This note was uploaded on 05/04/2010 for the course ENGIN 101 taught by Professor Jeffringenberg during the Spring '07 term at University of Michigan.

Ask a homework question - tutors are online