Slide 1

Slide 1 text

Frank Wu Fall 2015 CS50 Yale

Slide 2

Slide 2 text

Section 2

Slide 3

Slide 3 text

Why section? “Sections are a time to dive in and get some hands-on experience with topics measured in class or in study materials”

Slide 4

Slide 4 text

Why section?

Slide 5

Slide 5 text

Agenda • Grading and logistics • Arrays • ASCII • Functions • Command-line arguments • Problem set 2

Slide 6

Slide 6 text

Arrays 0 1 2 3 65 41 23 10

Slide 7

Slide 7 text

Creating an array name[]; // Example: string problems[99]; int scores[4]; scores[0] = 65; scores[1] = 41; scores[2] = 23; scores[3] = 10; // OR int scores[] = {65, 41, 23, 10}; string problems[99] = { NULL }; 0 1 2 3 65 41 23 10

Slide 8

Slide 8 text

Accessing elements in an array for (int i = 0; i < 4; i++) { printf("%d\n", scores[i]); } 0 1 2 3 65 41 23 10

Slide 9

Slide 9 text

Your turn Create the array below and calculate the sum of all of its members. Once you’ve calculated the sum, print it out. 0 1 2 3 65 41 23 10

Slide 10

Slide 10 text

Multi-dimensional arrays 0,0 0,1 0,2 o 1,0 1,1 1,2 x o 2,0 2,1 2,2 x char board[3][3]; board[0][1] = 'o'; board[1][0] = 'x'; board[1][1] = 'o'; board[2][1] = 'x';

Slide 11

Slide 11 text

Strings Strings are simply arrays of characters. string word = "Hi!"; 0 1 2 3 H i ! \0

Slide 12

Slide 12 text

Your turn Create a string and print it out, letter by letter.

Slide 13

Slide 13 text

Strings as ASCII chars string word = "Hi!"; for (int i = 0; i < 4; i++) { printf("%d\n", word[i]); } 0 1 2 3 72 105 33 0 ‘H’ ‘i’ ‘!’ ‘\0’

Slide 14

Slide 14 text

Functions Input Output int main(void) { return 0; }

Slide 15

Slide 15 text

Why functions? • Organization • Simplification • Reusability

Slide 16

Slide 16 text

Defining a function #include int square(int number); // function prototype int main(void) { int x = 2; printf("x is %d\n", x); x = square(x); printf("x is %d\n", x); return 0; } int square(int number) { int output = number * number; return output; }

Slide 17

Slide 17 text

Your turn Write a function that takes 2 parameters, number and exponent, and returns number raised to the power of exponent. #include int power(int number, int exponent); // function prototype int main(void) { int x = 2; int third = power(x, 3); printf("%d raised to the power of %d is %d\n", x, 3, third); int fifth = power(x, 5); printf("%d raised to the power of %d is %d\n", x, 5, fifth); return 0; } int power(int number, int exponent) { // ... }

Slide 18

Slide 18 text

Command-line arguments int main(void) { return 0; } int main(int argc, char *argv[]) { return 0; } argc is an integer representing the number of arguments passed to the command line argv[] is an array of strings that contains the arguments passed to the command line

Slide 19

Slide 19 text

Command-line arguments fjw22@ide50:~/workspace $ ./copy infile outfile 1. What is argc? 2. What is argv[0]? 3. What is argv[1]? 4. What is argv[2]? 5. What is argv[3]? 6. What is argv[4]?

Slide 20

Slide 20 text

Your turn Create a program that takes in a command- line argument and prints out the first letter. fjw22@ide50:~/workspace $ ./first test t

Slide 21

Slide 21 text

A look at your computer’s memory stack heap

Slide 22

Slide 22 text

Problem set 2 • ASCII • Command-line arguments • Modulo

Slide 23

Slide 23 text

ASCII chars

Slide 24

Slide 24 text

ASCII math printf("%d\n", 'a' - 'A'); printf("%c\n", 'B' + ('a' - 'A')); printf("%c\n", 'B' + 32); printf("%c\n", 'b' - 32); printf("%c\n", 'B' + 1); printf("%c\n", 'B' - 1);

Slide 25

Slide 25 text

atoi() • Converts a string into an integer • Remember: command-line arguments in argv[] are strings #include int atoi(const char *str)

Slide 26

Slide 26 text

Modulo • Modulo provides the remainder when dividing two numbers • In Caesar, what happens if we are given a really large number as our key? • In Vigenère, what happens if we reach the end of our target word? 26 % 10 // 6 13 % 12 // 1 8 % 8 // 0 2 % 15 // 1

Slide 27

Slide 27 text

Section 3

Slide 28

Slide 28 text

Agenda • Problem set 1 • Debugging with gdb • Asymptotic notation • Binary search • Sorting algorithms • Problem set 3

Slide 29

Slide 29 text

Grading • Scope: to what extent does your code implement the features required by our specification? • Correctness: to what extent is your code consistent with our specifications and free of bugs? • Design: to what extent is your code written well (i.e., clearly, efficiently, elegantly, and/or logically)? • Style: to what extent is your code readable (i.e., commented and indented with variables aptly named)?

Slide 30

Slide 30 text

Comment your code! /** * caesar.c * Frank Wu * September 23, 2015 * * Encrypts user-supplied plaintext using a Caesar cipher. */ /** * Returns number^exponent (and ignores all negative exponents) */ int power(int number, int exponent) { // ... }

Slide 31

Slide 31 text

An example // ??? if (isupper(message[i])) { message[i] = ((message[i] - 'A' + key) % NUM_LETTERS) + 'A'; } else if (islower(message[i])) { message[i] = ((message[i] - 'a' + key) % NUM_LETTERS) + 'a'; } In a few months, will you still remember what this block of code does?

Slide 32

Slide 32 text

Postmortems

Slide 33

Slide 33 text

Debugging with gdb fjw22@ide50:~/workspace $ gdb ./caesar Reading symbols from ./caesar...done. (gdb) gdb ./filename

Slide 34

Slide 34 text

Useful commands break (b) main run next (n) step (s) list print (p) info locals continue (c) disable quit (q)

Slide 35

Slide 35 text

Debugging with gdb fjw22@ide50:~/workspace $ check50 2015.fall.pset2.caesar caesar.c :) caesar.c exists :) caesar.c compiles :) encrypts "a" as "b" using 1 as key :) encrypts "barfoo" as "yxocll" using 23 as key :( encrypts "BARFOO" as "EDUIRR" using 3 as key \ expected output, but not "EAUIRR\n" :) encrypts "BaRFoo" as "FeVJss" using 4 as key :) encrypts "barfoo" as "onesbb" using 65 as key :) encrypts "world, say hello!" as "iadxp, emk tqxxa!" using 12 as key :) handles lack of argv[1]

Slide 36

Slide 36 text

Asymptotic notation O(n) upper bound Ω(n) lower bound

Slide 37

Slide 37 text

Binary search • O(log n) • Ω(1) • Only works if our list is already sorted!

Slide 38

Slide 38 text

Bubble sort • O(n) space complexity • O(n^2) time complexity • Ω(n^2) time complexity

Slide 39

Slide 39 text

Selection sort • O(n) space complexity • O(n^2) time complexity • Ω(n^2) time complexity

Slide 40

Slide 40 text

Insertion sort • O(n) space complexity • O(n^2) time complexity • Ω(n) time complexity

Slide 41

Slide 41 text

Merge sort • O(n) space complexity • O(n log n) time complexity • Ω(n log n) time complexity

Slide 42

Slide 42 text

Problem set 3 • We’ll be using distribution code! • In find.c, your goal is to fill in the sort() and search() functions • In the game of fifteen, your goal is to write a few core functions to finish the game • Hacker edition: create a solver for the game of fifteen

Slide 43

Slide 43 text

Section 4

Slide 44

Slide 44 text

Agenda • Redirection commands • File I/O • Memory management • Pointers

Slide 45

Slide 45 text

Redirection ./hello > output.txt ./hello >> output.txt ./hello 2> errors.txt ./hello 2>> errors.txt ./hello < input.txt ./hello1 | ./hello2 ./hello < input.txt > output.txt

Slide 46

Slide 46 text

File I/O Process stdin (0) stdout (1) stderr (2)

Slide 47

Slide 47 text

Files in C // Open file "input.txt" in read only mode FILE *in = fopen("input.txt", "r"); // Make sure fopen() doesn't return NULL! if (in == NULL) { return 1; } else { // Close the file at the end to avoid memory leaks fclose(in); }

Slide 48

Slide 48 text

Files in C // Get character from input file int c = fgetc(in); while (c != EOF) { // Write character to output file fputc(c, out); c = fgetc(in); }

Slide 49

Slide 49 text

Your turn Create a program that takes an input string from stdin using GetString() and then prints it into an output file.

Slide 50

Slide 50 text

File functions fopen() fread() fwrite() fgets() fputs() fgetc() fputc() fclose() Use “man fopen” to learn more about it.

Slide 51

Slide 51 text

Memory management stack heap

Slide 52

Slide 52 text

malloc() // Allocate memory int *ptr = malloc(sizeof(int)); // Free memory when we’re done free(ptr);

Slide 53

Slide 53 text

Pointers #include #include int main(void) { int *x = malloc(sizeof(int)); int *y = malloc(sizeof(int)); *x = 42; *y = 13; printf("%d %d\n", *x, *y); y = x; printf("%d %d\n", *x, *y); return 0; }

Slide 54

Slide 54 text

Pointers int x = 50; 50 0x123 0x123 int *p = &x; 0x456

Slide 55

Slide 55 text

Pointers * value of & address of

Slide 56

Slide 56 text

Pointers void swap(int *a, int *b) { int tmp = *a; *a = *b; *b = tmp; }

Slide 57

Slide 57 text

Pointer exercise int x = 2, y = 8, z = 12; int *ptr_x = &x; int *ptr_y = &y; int *ptr_z = &z; z = x * y; x *= y; y = *ptr_x; *ptr_x = x * y; ptr_x = ptr_y; x = (*ptr_y) * (*ptr_z);

Slide 58

Slide 58 text

Section 5

Slide 59

Slide 59 text

Agenda • Linked lists • Hashtables • Quiz 0 review

Slide 60

Slide 60 text

Linked lists 9 4 5 head head->next head->next->next

Slide 61

Slide 61 text

Linked lists

Slide 62

Slide 62 text

Linked lists typedef struct node { int n; struct node *next; } node; 9 n next

Slide 63

Slide 63 text

Linked list search 9 4 5 head

Slide 64

Slide 64 text

Linked list insertion 9 4 5 head new_node->next = head; head = new_node;

Slide 65

Slide 65 text

Linked list deletion 9 4 5 head prev_node->next = to_delete->next;

Slide 66

Slide 66 text

Hashtables 0 apple 1 banana … 10 kiwi … 12 mango apple banana kiwi mango Hash function

Slide 67

Slide 67 text

Collisions! 0 apple 1 banana … 10 kiwi … 12 mango berry Hash function Now what?!

Slide 68

Slide 68 text

Quiz 0 http://cdn.cs50.net/2015/fall/quizzes/0/yale.html • CPSC 100 01 (lectures on Mondays and Wednesdays) • last name A - N: go at 1:00pm on Wed 10/14 to the Yale Law School Auditorium • last name O – Z: go at 1:00pm on Wed 10/14 to Davies Auditorium in the Becton Center • CPSC 100 02 (lectures on Tuesdays and Thursdays) go at 2:30pm on Thu 10/15 to SSS 114

Slide 69

Slide 69 text

Practice Question 1 • What’s 0x50 in binary? • What’s 0x40 in decimal?

Slide 70

Slide 70 text

Practice Question 2 • True or false: • gdb is a debugger • make is a compiler • the float datatype can store infinitely precise decimal numbers • all .c files must have a main function

Slide 71

Slide 71 text

Practice Question 3 • What happens when I call the following commands: • printf(“%p” , wp); • printf(“%d” , *wp); int w = 2, x = 3, y = 4, z = 5; int *wp = &w; int *xp = &x; int *yp = &y; int *zp = &z;

Slide 72

Slide 72 text

Practice Question 4 This code was meant to simulate counting from 1 to 10, pausing one second between numbers, it instead appears to do nothing for ten seconds, after which it finally prints everything all at once before quitting. Why? for (int i = 1; i <= 10; i++) { printf("%d, ah ah ah... ", i); sleep(1); }

Slide 73

Slide 73 text

Practice Question 5 #include #include int main(void) { //... }

Slide 74

Slide 74 text

Section 6

Slide 75

Slide 75 text

Agenda • Stacks and queues, briefly • Linked lists, in detail • Hashtables, in detail

Slide 76

Slide 76 text

Stack Suppose that a stack for integers is defined per the below, wherein numbers is an array for the stack’s integers, CAPACITY (a constant) is the stack’s capacity (i.e., maximal size), and size is the stack’s current size. typedef struct { int numbers[CAPACITY]; int size; } stack; Complete the implementation of push in such a way that it pushes n onto a stack, s, if s isn’t already full. Assume that s has been declared globally. Consider s full only if its size equals CAPACITY. No need to return a value, even if s is full. Your implementation should operate in constant time. void push(int n) { }

Slide 77

Slide 77 text

Queue Suppose that a queue for integers is defined per the below, wherein numbers is an array for the queue’s integers, CAPACITY (a constant) is the queue’s capacity (i.e., maximal size), and size is the queue’s current size, and front is the index of the integer at the front of the queue. typedef struct { int front; int numbers[CAPACITY]; int size; } queue; Complete the implementation of enqueue in such a way that it inserts n into a queue, q, if q isn’t already full. Assume that q has been declared globally. Consider q full only if its size equals CAPACITY. No need to return a value, even if q is full. Your implementation should operate in constant time. void enqueue(int n) { }

Slide 78

Slide 78 text

Linked lists 9 4 5 head head->next head->next->next

Slide 79

Slide 79 text

Linked lists

Slide 80

Slide 80 text

Linked lists # Malan’s list-0.h typedef struct node { int n; struct node *next; } node; 9 n next

Slide 81

Slide 81 text

Linked list search 9 4 5 head

Slide 82

Slide 82 text

Linked list insertion 9 4 5 head new_node->next = head; head = new_node;

Slide 83

Slide 83 text

Linked list deletion 9 4 5 head prev_node->next = to_delete->next;

Slide 84

Slide 84 text

Linked lists http://cdn.cs50.net/2015/fall/lectures/5/w/src5w/list-0.c http://cdn.cs50.net/2015/fall/lectures/5/w/src5w/list-0.h # Malan’s list-0.c void delete(void) void insert(void) void search(void) void traverse(void)

Slide 85

Slide 85 text

Hashtables 0 apple 1 banana … 10 kiwi … 12 mango apple banana kiwi mango Hash function

Slide 86

Slide 86 text

Collisions! 0 apple 1 banana … 10 kiwi … 12 mango berry Hash function Now what?!

Slide 87

Slide 87 text

dictionary.c # dictionary.c TODOs # 0. node/hashtable data structure # 1. hash function # 2. check(const char *word) => search() # 3. load(const char *dictionary) => insert() # 4. size(void) # 5. unload(void) => delete()

Slide 88

Slide 88 text

Section 7

Slide 89

Slide 89 text

Agenda • chmod • HTML & CSS • TCP/IP • HTTP

Slide 90

Slide 90 text

chmod chmod changes the access permissions of file system objects fjw22@ide50:~/workspace $ ls -l total 4 drwx------ 2 ubuntu ubuntu 4096 Oct 26 05:14 directory/ fjw22@ide50:~/workspace $ chmod 711 directory fjw22@ide50:~/workspace $ ls -l total 4 drwx--x--x 2 ubuntu ubuntu 4096 Oct 26 05:14 directory/

Slide 91

Slide 91 text

ls -l fjw22@ide50:~/workspace $ ls -l total 4 drwx--x--x 2 ubuntu ubuntu 4096 Oct 26 05:14 directory/ permissions owner name owner group file size (bytes) number of links last modified time name

Slide 92

Slide 92 text

File permissions drwx------ d rwx --- --- Directory? User Group World Read Write Execute

Slide 93

Slide 93 text

File permissions rwx --- --- r-- r-- r-- rwx r-x r-x 700 444 ??? chmod 711 directory — For any directory chmod 644 file.txt — For any non-PHP file you create chmod 600 file.php — For PHP files

Slide 94

Slide 94 text

HTML HyperText Markup Language

Slide 95

Slide 95 text

How does this work? Imagine that you see all of this on a website.

Slide 96

Slide 96 text

How does this work?

Imagine that you see all of this on a website.

Slide 97

Slide 97 text

How does this work?

Start Tag End Tag

Slide 98

Slide 98 text

Bold Italics

Header 1

Header 2

Bold Italics Header 1 Header 2

Slide 99

Slide 99 text

Slide 100

Slide 100 text

My Website …

Slide 101

Slide 101 text

My Website

Main heading

Hi! Welcome!

Slide 102

Slide 102 text

No content

Slide 103

Slide 103 text

You should check out Google. Most HTML tags can have attributes

Slide 104

Slide 104 text

My Website

Main heading

Hi! Welcome! You should check out Google.

Slide 105

Slide 105 text

No content

Slide 106

Slide 106 text

CSS Cascading Style Sheets

Slide 107

Slide 107 text

My Website

Main heading

Hi! Welcome! You should check out Google.

Slide 108

Slide 108 text

h1 { color: red; } styles.css

Slide 109

Slide 109 text

No content

Slide 110

Slide 110 text

h1 { color: red; } Selector Declaration

Slide 111

Slide 111 text

h1 { color: red; } Property Value

Slide 112

Slide 112 text

h1 { color: red; text-align: center; }

Slide 113

Slide 113 text

No content

Slide 114

Slide 114 text

.class #id vs

Slide 115

Slide 115 text

Feature 1

Feature 2

Feature 3

Slide 116

Slide 116 text

.column { color: white; background-color: blue; } #column1 { color: yellow; }

Slide 117

Slide 117 text

Padding Margin Div

Slide 118

Slide 118 text

http://frankjwu.com/posts/intro-to-web- development-mit-blueprint-2014/

Slide 119

Slide 119 text

TCP/IP SYN SYN-ACK ACK

Slide 120

Slide 120 text

TCP/IP

Slide 121

Slide 121 text

HTTP Request Response

Slide 122

Slide 122 text

HTTP Requests • GET • POST • PUT • PATCH • DELETE These request methods are the verbs! GET / HTTP/1.1 Host: www.google.com …

Slide 123

Slide 123 text

HTTP Responses HTTP/1.1 200 OK Content-Type: text/html …

Slide 124

Slide 124 text

Section 8

Slide 125

Slide 125 text

yhack.org/cs50

Slide 126

Slide 126 text

Agenda • PHP • SQL • MVC

Slide 127

Slide 127 text

HTTP Request Response

Slide 128

Slide 128 text

HTTP Requests • GET • POST • PUT • PATCH • DELETE These request methods are the verbs! GET / HTTP/1.1 Host: www.google.com …

Slide 129

Slide 129 text

HTML hello.html from pset6 hello

Slide 130

Slide 130 text

PHP hello.php from pset6 hello hello, = htmlspecialchars($_GET["name"]) ?> hello, world

Slide 131

Slide 131 text

PHP PHP Hypertext Preprocessor

Slide 132

Slide 132 text

PHP fjw22@ide50:~/workspace $ php first.php 1Sally

Slide 133

Slide 133 text

PHP

Slide 134

Slide 134 text

Your turn Create a program that takes in command-line arguments and prints out the first letter of each one on a new line. Hint: use foreach! fjw22@ide50:~/workspace $ php first.php test arg f t a

Slide 135

Slide 135 text

PHP in your HTML hello.php from pset6 hello hello, = htmlspecialchars($_GET["name"]) ?> hello, world

Slide 136

Slide 136 text

PHP & HTML Passes data via URL: https://www.youtube.com/watch?v=Yzdb4gEaF6E&t=52 GET

Slide 137

Slide 137 text

PHP & HTML { "email": "———@————.com", "password": "——————" } Passes data via HTTP message body: POST

Slide 138

Slide 138 text

PHP Superglobals • $GLOBALS • $_SERVER • $_GET • $_POST • $_FILES • $_COOKIE • $_SESSION • $_REQUEST • $_ENV

Slide 139

Slide 139 text

SQL Structured Query Language

Slide 140

Slide 140 text

SQL

Slide 141

Slide 141 text

SQL

Slide 142

Slide 142 text

SQL INSERT INTO table VALUES values # insert into table the row of values INSERT INTO table (col1, col2) VALUES (val1, val2) # insert into table under columns col1 & col2, val1 & val2 INSERT INTO Insert specific values into a database table Example: INSERT INTO `users` (username, hash) VALUES('andi', '$2y $10$c.e4DK7pVyLT.stmHxgAleWq4yViMmkwKz3x8XCo4b/u3r8g5OTnS')

Slide 143

Slide 143 text

SQL UPDATE table SET col1 = val1, col2 = val2, ... # update table, changing values in particular columns UPDATE table SET col1 = val1 WHERE identifier = "name" # update table, changing col1 to val1 where "identifier" equals "name" UPDATE Update data in a database table Example: UPDATE `users` (username, hash) SET name = 'andy' WHERE name = 'andi'

Slide 144

Slide 144 text

SQL SELECT col FROM table WHERE col = "identifier" # select the "identifier" column from table to compare/view SELECT * FROM table # select all columns from a table SELECT Select data values from a database table Example: SELECT * FROM `users`

Slide 145

Slide 145 text

SQL DELETE FROM table WHERE col = "identifier" # delete a row from table DELETE Delete data from a database table Example: DELETE FROM `users` WHERE name = "andy"

Slide 146

Slide 146 text

Your turn Open up pset7.sql and walk through what is happening, line by line.

Slide 147

Slide 147 text

MVC Model The object View The presentation Controller The arbitrator

Slide 148

Slide 148 text

Section 9

Slide 149

Slide 149 text

Javascript // a simple variable var problems = 99; // an array var mic_checks = [1, 2, 3]; // a string var str = "Testing, testing"; // an object var obj = {receptions: 9, yards: 105, average: 11.7};

Slide 150

Slide 150 text

Javascript function print_words(words) { for (var i = 0; i < words.length; i++) { console.log(words[i]); } return true; } http://jsbin.com/?js,console

Slide 151

Slide 151 text

Your turn Write a function that takes in an array of words and returns a new array with the first letter of every word capitalized. var cap = capitalize(["joe", "mike", "steve", "kevin"]) cap should now be ["Joe", "Mike", "Steve", "Kevin"] http://jsbin.com/?js,console

Slide 152

Slide 152 text

How do we use JS?

Slide 153

Slide 153 text

How do we use JS?

Slide 154

Slide 154 text

How do we use JS?

Slide 155

Slide 155 text

The DOM The Document Object Model
pic

What a time to be alive

Slide 156

Slide 156 text

The DOM HTML head title div body div img p

Slide 157

Slide 157 text

Javascript + HTML var title = document.getElementById("title"); title.innerHTML = "Changed the title"; var pic = document.getElementById("pic"); pic.src = "newpic.jpg"; document.getElementById("quote").innerHTML = "For whom the hotline blings";

Slide 158

Slide 158 text

Javascript + HTML http://cdn.cs50.net/2015/fall/lectures/9/m/src9m/form-1.html

Slide 159

Slide 159 text

jQuery http://cdn.cs50.net/2015/fall/lectures/9/m/src9m/form-2.html

Slide 160

Slide 160 text

AJAX $.getJSON(url, function(data) { // Process fetched data });

Slide 161

Slide 161 text

Your turn As Professor Malan demonstrated during class, we can AJAX-ify fetching a stock price for pset7. Without referencing the code he showed in class, write a function quote() that will call the appropriate endpoint and then adds the fetched price to the DOM in a span with id ‘price’. You can assume that any required HTML has already been setup.

Slide 162

Slide 162 text

frankjwu.com @frankjwu Frank Wu