SLIDE 1 CS31 Discussion 1E
Spring 17’: week 06
TA: Bo-Jhang Ho
bojhang@cs.ucla.edu
Credit to former TA Chelsea Ju
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 - - 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 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 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 Overflow issue
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
- 1.7 * 10^308 to 1.7 * 10^308
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
- 1.7 * 10^308 to 1.7 * 10^308
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 Project 3 call graph - planed
setChar() clearGrid() getChar() draw() plotLine() executeCommands() main()
C F@ B@ H00 V00
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 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 (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 (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 (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 (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 (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 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 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 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 } 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 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 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 Today’s Agenda
} Overflow } Good coding style part 3 } Project 4 discussion } C-style string } Hints for learning pointer (spoiler alert)
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 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 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 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 Project 4 demystify
} Observation 2: Why const?
SLIDE 28 Pass an array to a function
} From caller: } In the function:
- r
- r
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 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 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 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 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 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 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 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 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 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 moveToBegining()
} string emojis[5] = { , , , , }; } After we call moveToBeginning(emojis, 5, 3) } The content of emojis array should be
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 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 moveToBegining(emojis, 5, 3)
0 1 2 3 4
a =
} Approach 2: In-place movement
SLIDE 43 moveToBegining(emojis, 5, 3)
0 1 2 3 4
a =
} Approach 2: In-place movement
tmp =
SLIDE 44 moveToBegining(emojis, 5, 3)
0 1 2 3 4
a =
} Approach 2: In-place movement
tmp =
SLIDE 45 moveToBegining(emojis, 5, 3)
0 1 2 3 4
a =
} Approach 2: In-place movement
tmp =
SLIDE 46 moveToBegining(emojis, 5, 3)
0 1 2 3 4
a =
} Approach 2: In-place movement
tmp =
SLIDE 47 moveToBegining(emojis, 5, 3)
0 1 2 3 4
a =
} Approach 2: In-place movement
tmp =
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 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 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 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 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 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 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 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 Today’s Agenda
} Overflow } Good coding style part 3 } Project 4 discussion } C-style string } Hints for learning pointer (spoiler alert)
SLIDE 57 String / character array
} How do I print “Hello” on the screen if single-quote and
double-quote are not invented?
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 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 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 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 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 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 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 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 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 An array of strings
} That means, an array of char arrays!
A matrix Row 1 Row 2 Row m
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 Today’s Agenda
} Overflow } Good coding style part 3 } Project 4 discussion } C-style string } Hints for learning pointer (spoiler alert)
SLIDE 70 Road map of CS31
Variable If / else Loops Pointer!! Array Function Class String
SLIDE 71 Pointer
} What the hack is….
*
? 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
SLIDE 73 Pointer
} Two important operators to deal with memory address
* &
SLIDE 74 Seek for your opinion
Data type “Use as verbs”
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 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