CS31 Discussion 1E Spring 17: week 06 TA: Bo-Jhang Ho - - PowerPoint PPT Presentation

cs31 discussion 1e
SMART_READER_LITE
LIVE PREVIEW

CS31 Discussion 1E Spring 17: week 06 TA: Bo-Jhang Ho - - PowerPoint PPT Presentation

CS31 Discussion 1E Spring 17: week 06 TA: Bo-Jhang Ho bojhang@cs.ucla.edu Credit to former TA Chelsea Ju Puzzle time: How many lines will this program print? #include <iostream> int main() { for (unsigned int i = 3; i >= 0; i--)


slide-1
SLIDE 1 CS31 Discussion 1E Spring 17’: week 06 TA: Bo-Jhang Ho bojhang@cs.ucla.edu Credit to former TA Chelsea Ju
slide-2
SLIDE 2 Puzzle time: How many lines will this program print? #include <iostream> int main() { for (unsigned int i = 3; i >= 0; i--) cout << "Print one line" << endl; return 0; }
slide-3
SLIDE 3 Puzzle time: How many lines will this program print? #include <iostream> int main() { for (unsigned int i = 3; i >= 0; i--) cout << "Print one line" << endl; return 0; }

Print lines like crazy!!!!

slide-4
SLIDE 4 Overflow issue
slide-5
SLIDE 5 Puzzle time: How many lines will this program print? #include <iostream> int main() { for (unsigned int i = 3; i >= 0; i--) cout << "Print one line" << endl; return 0; } } Basic data types Type Bytes Bits Value range int 4 32
  • 2,147,483,648 to 2,147,483,647
unsigned int 4 32 0 to 4,294,967,295 double 8 64
  • 1.7 * 10^308 to 1.7 * 10^308
slide-6
SLIDE 6 Puzzle time: How many lines will this program print? #include <iostream> int main() { for (unsigned int i = 3; i >= 0; i--) cout << "Print one line" << endl; return 0; } } Basic data types Type Bytes Bits Value range int 4 32
  • 2,147,483,648 to 2,147,483,647
unsigned int 4 32 0 to 4,294,967,295 double 8 64
  • 1.7 * 10^308 to 1.7 * 10^308
} Discussion: Will double variable overflow?
slide-7
SLIDE 7 Today’s Agenda } Overflow } Good coding style part 3 } Project 4 discussion } C-style string } Hints for learning pointer (spoiler alert)
slide-8
SLIDE 8 Project 3 call graph - planed setChar() clearGrid() getChar() draw() plotLine() executeCommands() main() C F@ B@ H00 V00
slide-9
SLIDE 9 Project 3 call graph of the sample solution setChar() clearGrid() getChar() draw() plotLine() executeCommands() main() C F@ B@ H00 V00 executeOneCommand() consumeNumber()
slide-10
SLIDE 10 Good coding style guideline } (2) Indentation } One more tab inside a { } block } (6) If a function receives invalid parameters, reject the request ASAP! } And by rejecting, I mean “return false.” } (7) Use single quote character when you refer to a certain character, don’t use numbers! } ‘a’ or 97 ?
slide-11
SLIDE 11 (2) Indentation – printing rectangle int main() { for (int r = 1; r <= 3; r++) { for (int c = 1; c <= 4; c++) { cout << "*"; } cout << endl; } return 0; } } Execution result:
slide-12
SLIDE 12 (2) Indentation – printing rectangle int main() { for (int r = 1; r <= 3; r++) { for (int c = 1; c <= 4; c++) { cout << "*"; } cout << endl; } return 0; }
slide-13
SLIDE 13 (2) Indentation – printing rectangle int main() { for (int r = 1; r <= 3; r++) { for (int c = 1; c <= 4; c++) { cout << "*"; } cout << endl; } return 0; } int main() { for (int r = 1; r <= 3; r++) { for (int c = 1; c <= 4; c++) { cout << "*"; } cout << endl; } return 0; }
slide-14
SLIDE 14 (2) Indentation – printing rectangle int main() { for (int r = 1; r <= 3; r++) { for (int c = 1; c <= 4; c++) { cout << "*"; } cout << endl; } return 0; }
slide-15
SLIDE 15 (2) Indentation – printing rectangle int main() { for (int r = 1; r <= 3; r++) { for (int c = 1; c <= 4; c++) cout << "*"; cout << endl; } return 0; }
slide-16
SLIDE 16 bool plotLine(int r, int c, int dir, int distance, char plotChar, int fgbg) { // Validate arguments if (r < 1 || r > NROWS || c < 1 || c > NCOLS) return false; switch (dir) { case HORIZ: if (c + distance < 1 || c + distance > NCOLS) return false; break; case VERT: if (r + distance < 1 || r + distance > NROWS) return false; break; default: return false; } if (fgbg != FG && fgbg != BG) return false; if (!isprint(plotChar)) return false; ... (6) Be a mean person: Reject invalid request ASAP!
slide-17
SLIDE 17 bool hasCorrectSyntax(string cmd, int& pos) { pos = 0; while (pos != cmd.size()) { switch (toupper(cmd[pos])) { default: return false; case 'C': pos++; break; case 'F': case 'B': // must be followd by a printable character pos++; if (pos == cmd.size() || !isprint(cmd[pos])) return false; pos++; break; case 'H': case 'V': pos++; if (pos == cmd.size()) return false; ... return true; } (6) Be a mean person: Reject invalid request ASAP!
slide-18
SLIDE 18 int executeCommands(string cmd, char& plotChar, int& mode, int& badPos) { int pos; if ( ! hasCorrectSyntax(cmd, pos)) { badPos = pos; return SYNTAX_ERROR; } int r = 1; int c = 1; pos = 0; // At the start of each loop iteration, pos is the position of the // start of the next plotting command within the command string, or // the end of that string. while (pos != cmd.size()) { if (!executeOneCommand(cmd, pos, r, c, plotChar, mode)) { badPos = pos; return EXECUTION_ERROR; } } return COMMAND_OK; } (6) Be a mean person: Reject invalid request ASAP!
slide-19
SLIDE 19 } Discussion: What are the advantages? } Tell the readers that I’m not going to address this cases } Cross out these impossible cases to make life easier } Make the logic clear } You don’t need to worry about the correctness of parameters anymore (6) Be a mean person: Reject invalid request ASAP!
slide-20
SLIDE 20 bool hasCorrectSyntax(string cmd, int& pos) { pos = 0; while (pos != cmd.size()) { switch (toupper(cmd[pos])) { default: return false; case 'C': pos++; break; case 'F': case 'B': // must be followd by a printable character pos++; if (pos == cmd.size() || !isprint(cmd[pos])) return false; pos++; break; case 'H': case 'V': pos++; if (pos == cmd.size()) return false; (7) Don’t replace single quote as numbers
slide-21
SLIDE 21 bool hasCorrectSyntax(string cmd, int& pos) { pos = 0; while (pos != cmd.size()) { switch (toupper(cmd[pos])) { default: return false; case 67: pos++; break; case 70: case 66: // must be followd by a printable character pos++; if (pos == cmd.size() || !isprint(cmd[pos])) return false; pos++; break; case 72: case 86: pos++; if (pos == cmd.size()) return false; (7) Don’t replace single quote as numbers
slide-22
SLIDE 22 Today’s Agenda } Overflow } Good coding style part 3 } Project 4 discussion } C-style string } Hints for learning pointer (spoiler alert)
slide-23
SLIDE 23 Project 4 demystify } 11 functions: } int enumerate(const string a[], int n, string target); } int locate(const string a[], int n, string target); } bool locateSequence(const string a[], int n, string target, int& begin, int& end); } int locationOfMin(const string a[], int n); } int moveToEnd(string a[], int n, int pos); } int moveToBeginning(string a[], int n, int pos); } int locateDifference(const string a1[], int n1, const string a2[], int n2); } int eliminateDups(string a[], int n); } bool subsequence(const string a1[], int n1, const string a2[], int n2); } int makeMerger(const string a1[], int n1, const string a2[], int n2, string result[], int max); } int divide(string a[], int n, string divider);
slide-24
SLIDE 24 Project 4 demystify } 11 functions: } int enumerate(const string a[], int n, string target); } int locate(const string a[], int n, string target); } bool locateSequence(const string a[], int n, string target, int& begin, int& end); } int locationOfMin(const string a[], int n); } int moveToEnd(string a[], int n, int pos); } int moveToBeginning(string a[], int n, int pos); } int locateDifference(const string a1[], int n1, const string a2[], int n2); } int eliminateDups(string a[], int n); } bool subsequence(const string a1[], int n1, const string a2[], int n2); } int makeMerger(const string a1[], int n1, const string a2[], int n2, string result[], int max); } int divide(string a[], int n, string divider); } 2 Observations: } An array always follows in integer n, indicating the size } A const modifier in front of an array
slide-25
SLIDE 25 Project 4 demystify } Observation 1: Why passing array size to a function? } Can we not get the array size from C++? } In C++, there is no standard way to get array size! } Not like string, you can call .size() method
slide-26
SLIDE 26 Project 4 demystify } Observation 1: Why passing array size to a function? } But, can we get the array size from C++? } In C++, there is no standard way to get array size! } Not like string, you can call .size() method } This thread talks about some hacky ways to get the size: http://stackoverflow.com/questions/4108313/how-do-i-find-the-length-of-an-array } That’s why we should have the agreement with function users that please pass the array as well as the array size } That being said, providing correct parameters is the user’s duty. You shouldn’t worry about invalid parameters } If some users pass bad parameters, it’s their fault!!
slide-27
SLIDE 27 Project 4 demystify } Observation 2: Why const?
slide-28
SLIDE 28 Pass an array to a function } From caller: } In the function:
  • r
  • r
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; foo(arr); void foo(int params[10]) { … } void foo(int params[]) { … } void foo(int *params) { … }
slide-29
SLIDE 29 Pass an array to a function void fillInArray(int params[]) { for (int i = 0; i < 5; i++) params[i] = i; } int main() { int arr[5] = {100, 99, 98, 97, 96}; fillInArray(arr); for (int i = 0; i < 5; i++) cout << "Element " << i << ": " << arr[i] << endl; return 0; } } What’s the output?
slide-30
SLIDE 30 Pass an array to a function void fillInArray(int params[]) { for (int i = 0; i < 5; i++) params[i] = i; } int main() { int arr[5] = {100, 99, 98, 97, 96}; fillInArray(arr); for (int i = 0; i < 5; i++) cout << "Element " << i << ": " << arr[i] << endl; return 0; } } What’s the output?
slide-31
SLIDE 31 Pass an array to a function } So far, we have seen two examples that the passed values in a function can be altered: } A variable passed as a reference } An array passed into a function void foo(int &a) { a = 3; } void foo(int arr[]) { arr[0] = 100; arr[1] = 200; arr[2] = 301; }
slide-32
SLIDE 32 Pass an array to a function } So far, we have seen two examples that the passed values in a function can be altered: } A variable passed as a reference } An array passed into a function } There is one more way to do it: } Pointer
slide-33
SLIDE 33 Pass an array to a function } Can we pass a 2-dimensional array to a function? } Yes, but with restriction } Have to provide the size of the array int fillInArray(int params[3][5]) { for (int i = 0; i < 3; i++) for (int j = 0; j < 5; j++) params[i][j] = i * 10 + j; } int main() { int arr[3][5]; fillInArray(arr); ... return 0; }
slide-34
SLIDE 34 Pass an array to a function } Can we pass a 2-dimensional array to a function? } Yes, but with restriction } Have to provide the size of the array int fillInArray(int params[3][5]) { for (int i = 0; i < 3; i++) for (int j = 0; j < 5; j++) params[i][j] = i * 10 + j; } int main() { int arr[3][5]; fillInArray(arr); ... return 0; } Cannot omit the numbers like one-dimensional array Have to match the caller
slide-35
SLIDE 35 Project 4 demystify } Observation 2: Why const? } const means the variable value cannot be changed } Read-only } From the function’s perspective, a is input and I don’t want to change the content
slide-36
SLIDE 36 Project 4 demystify } Observation 2: Why const? } const means the variable value cannot be changed } Read-only } From the function’s perspective, a is input and I don’t want to change the content } Question: Why not put const in front of n and target, too?

?

slide-37
SLIDE 37 Project 4 demystify } Observation 2: Why const? } const means the variable value cannot be changed } Read-only } Question: Why not put const in front of n and target, too? } The true reason is that we don’t want to accidentally change the values from the caller (e.g., main function)
slide-38
SLIDE 38 Project 4 demystify } 11 functions: } int enumerate(const string a[], int n, string target); } int locate(const string a[], int n, string target); } bool locateSequence(const string a[], int n, string target, int& begin, int& end); } int locationOfMin(const string a[], int n); } int moveToEnd(string a[], int n, int pos); } int moveToBeginning(string a[], int n, int pos); } int locateDifference(const string a1[], int n1, const string a2[], int n2); } int eliminateDups(string a[], int n); } bool subsequence(const string a1[], int n1, const string a2[], int n2); } int makeMerger(const string a1[], int n1, const string a2[], int n2, string result[], int max); } int divide(string a[], int n, string divider);
slide-39
SLIDE 39 moveToBegining() } string emojis[5] = { , , , , }; } After we call moveToBeginning(emojis, 5, 3) } The content of emojis array should be
slide-40
SLIDE 40 moveToBegining(emojis, 5, 3) 0 1 2 3 4 a = } Approach 1: Declare another array 0 1 2 3 4 tmp = 0 1 2 3 4 a =
slide-41
SLIDE 41 moveToBegining(emojis, 5, 3) } Approach 1: Declare another array } Oh no, compiler error! } Even if we can successfully declare this array, it’s not memory efficient
slide-42
SLIDE 42 moveToBegining(emojis, 5, 3) 0 1 2 3 4 a = } Approach 2: In-place movement
slide-43
SLIDE 43 moveToBegining(emojis, 5, 3) 0 1 2 3 4 a = } Approach 2: In-place movement tmp =
slide-44
SLIDE 44 moveToBegining(emojis, 5, 3) 0 1 2 3 4 a = } Approach 2: In-place movement tmp =
slide-45
SLIDE 45 moveToBegining(emojis, 5, 3) 0 1 2 3 4 a = } Approach 2: In-place movement tmp =
slide-46
SLIDE 46 moveToBegining(emojis, 5, 3) 0 1 2 3 4 a = } Approach 2: In-place movement tmp =
slide-47
SLIDE 47 moveToBegining(emojis, 5, 3) 0 1 2 3 4 a = } Approach 2: In-place movement tmp =
slide-48
SLIDE 48 moveToBegining(emojis, 5, 3) 0 1 2 3 4 a = } Approach 2: In-place movement } In reality, you can only copy but not move!
slide-49
SLIDE 49 moveToBegining(emojis, 5, 3) 0 1 2 3 4 a = } Approach 2: In-place movement } In reality, you can only copy but not move! tmp =
slide-50
SLIDE 50 moveToBegining(emojis, 5, 3) 0 1 2 3 4 a = } Approach 2: In-place movement } In reality, you can only copy but not move! tmp =
slide-51
SLIDE 51 moveToBegining(emojis, 5, 3) 0 1 2 3 4 a = } Approach 2: In-place movement } In reality, you can only copy but not move! tmp =
slide-52
SLIDE 52 moveToBegining(emojis, 5, 3) 0 1 2 3 4 a = } Approach 2: In-place movement } In reality, you can only copy but not move! tmp =
slide-53
SLIDE 53 moveToBegining(emojis, 5, 3) 0 1 2 3 4 a = } Approach 2: In-place movement } In reality, you can only copy but not move! tmp =
slide-54
SLIDE 54 moveToBegining(emojis, 5, 3) 0 1 2 3 4 a = } Approach 2: In-place movement } In reality, you can only copy but not move! a[i+1] = a[i];
slide-55
SLIDE 55 moveToBegining(emojis, 5, 3) 0 1 2 3 4 a = } Approach 2: In-place movement } In reality, you can only copy but not move! Step 1 Step 2 Step 3 a[i+1] = a[i]; for (int i = ???; ????????; ????????) i++? i--?
slide-56
SLIDE 56 Today’s Agenda } Overflow } Good coding style part 3 } Project 4 discussion } C-style string } Hints for learning pointer (spoiler alert)
slide-57
SLIDE 57 String / character array } How do I print “Hello” on the screen if single-quote and double-quote are not invented?
slide-58
SLIDE 58 String / character array } How do I print “Hello” on the screen if single-quote and double-quote are not invented? #include <stdio.h> int main() { char str[6]; str[0] = 72; str[1] = 101; str[2] = 108; str[3] = 108; str[4] = 111; str[5] = 0; printf("%s", str); return 0; }
slide-59
SLIDE 59 String / character array } How do I print “Hello” on the screen if single-quote and double-quote are not invented? #include <stdio.h> int main() { char str[6]; str[0] = 'H'; str[1] = 'e'; str[2] = 'l'; str[3] = 'l'; str[4] = 'o'; str[5] = 0; printf("%s", str); return 0; }
slide-60
SLIDE 60 String / character array } How do I print “Hello” on the screen if single-quote and double-quote are not invented? #include <stdio.h> int main() { char str[6]; str[0] = 'H'; str[1] = 'e'; str[2] = 'l'; str[3] = 'l'; str[4] = 'o'; str[5] = '\0'; printf("%s", str); return 0; }
slide-61
SLIDE 61 String / character array } How do I print “Hello” on the screen if single-quote and double-quote are not invented? #include <stdio.h> int main() { char str[6] = "Hello"; printf("%s", str); return 0; }
slide-62
SLIDE 62 String / character array } How do I print “Hello” on the screen if single-quote and double-quote are not invented? #include <iostream> using namespace std; int main() { string str = "Hello"; cout << str; return 0; }
slide-63
SLIDE 63 String / character array } Change characters in a string #include <iostream> using namespace std; int main() { string str = "HELLO"; str[1] = '3'; str[4] = '0'; cout << str; return 0; }
slide-64
SLIDE 64 String / character array } How do we know the length of a C-style string (a.k.a, character array)? #include <stdio.h> int main() { char str[100] = "Hello"; // TODO: How to count the length of str? // (not array size tho) return 0; }
slide-65
SLIDE 65 String / character array #include <stdio.h> int main() { char str[100] = "Hello"; // Find the first '\0' in the char array return 0; } } How do we know the length of a C-style string (a.k.a, character array)? } Observation: C-string always ends with a ‘\0’!
slide-66
SLIDE 66 String / character array #include <stdio.h> int main() { char str[100] = "Hello"; int len = 0; while (str[len] != '\0') len++; printf("String %s has %d characters\n", str, len); return 0; } } How do we know the length of a C-style string (a.k.a, character array)? } Observation: C-string always ends with a ‘\0’!
slide-67
SLIDE 67 An array of strings } That means, an array of char arrays! A matrix Row 1 Row 2 Row m
slide-68
SLIDE 68 An array of strings } That means, an array of char arrays! #include <stdio.h> int main() { char names[20][100]; for (int i = 0; i < 20; i++) scanf("%s", names[i]); ... return 0; } #include <iostream> using namespace std; int main() { string names[20]; for (int i = 0; i < 20; i++) cin >> names[i]; ... return 0; }
slide-69
SLIDE 69 Today’s Agenda } Overflow } Good coding style part 3 } Project 4 discussion } C-style string } Hints for learning pointer (spoiler alert)
slide-70
SLIDE 70 Road map of CS31 Variable If / else Loops Pointer!! Array Function Class String
slide-71
SLIDE 71 Pointer } What the hack is….

*

?
slide-72
SLIDE 72 Memory address } All the variables are converted to memory addresses through a compiler. int main() { int apple; int banana = 3; int cat = 4; int dog = cat - banana; ... return 0; } address content
  • riginal
variable 10020 10024 10028 10032 apple banana cat dog 1 4 3 9076
slide-73
SLIDE 73 Pointer } Two important operators to deal with memory address

* &

slide-74
SLIDE 74 Seek for your opinion Data type “Use as verbs”
slide-75
SLIDE 75 Seek for your opinion Data type “Use as verbs” } int *a; } a is a variable, whose data type is int * } We often times just say a is an integer pointer } A pointer stores a memory address } Thus, a stores an address of some integer
slide-76
SLIDE 76 Seek for your opinion Data type } int *a; } a is a variable, whose data type is int * } a stores an address of some integer “Use as verbs” } & - address-of operator } &b means I want to get the memory address of variable b } * - dereference operator } *c means I want to retrieve the value in address c