Upgrade to Pro — share decks privately, control downloads, hide ads and more …

CS50 at Yale: Fall 2015 Sections

Frank Wu
September 21, 2015

CS50 at Yale: Fall 2015 Sections

A compilation of my section slides from CS50's first semester at Yale

Frank Wu

September 21, 2015
Tweet

More Decks by Frank Wu

Other Decks in Programming

Transcript

  1. Why section? “Sections are a time to dive in and

    get some hands-on experience with topics measured in class or in study materials”
  2. Agenda • Grading and logistics • Arrays • ASCII •

    Functions • Command-line arguments • Problem set 2
  3. Creating an array <data type> name[<size>]; // 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
  4. 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
  5. 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
  6. 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';
  7. 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’
  8. Defining a function #include <stdio.h> 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; }
  9. Your turn Write a function that takes 2 parameters, number

    and exponent, and returns number raised to the power of exponent. #include <stdio.h> 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) { // ... }
  10. 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
  11. 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]?
  12. Your turn Create a program that takes in a command-

    line argument and prints out the first letter. fjw22@ide50:~/workspace $ ./first test t
  13. 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);
  14. atoi() • Converts a string into an integer • Remember:

    command-line arguments in argv[] are strings #include <stdlib.h> int atoi(const char *str)
  15. 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
  16. Agenda • Problem set 1 • Debugging with gdb •

    Asymptotic notation • Binary search • Sorting algorithms • Problem set 3
  17. 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)?
  18. Comment your code! /** * caesar.c * Frank Wu <[email protected]>

    * 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) { // ... }
  19. 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?
  20. Useful commands break (b) main run <arguments> next (n) step

    (s) list print (p) info locals continue (c) disable quit (q)
  21. 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]
  22. Merge sort • O(n) space complexity • O(n log n)

    time complexity • Ω(n log n) time complexity
  23. 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
  24. 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
  25. 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); }
  26. 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); }
  27. Your turn Create a program that takes an input string

    from stdin using GetString() and then prints it into an output file.
  28. Pointers #include <stdio.h> #include <stdlib.h> 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; }
  29. 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);
  30. Hashtables 0 apple 1 banana … 10 kiwi … 12

    mango apple banana kiwi mango Hash function
  31. Collisions! 0 apple 1 banana … 10 kiwi … 12

    mango berry Hash function Now what?!
  32. 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
  33. 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
  34. 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;
  35. 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); }
  36. 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) { }
  37. 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) { }
  38. Linked lists # Malan’s list-0.h typedef struct node { int

    n; struct node *next; } node; 9 n next
  39. Hashtables 0 apple 1 banana … 10 kiwi … 12

    mango apple banana kiwi mango Hash function
  40. Collisions! 0 apple 1 banana … 10 kiwi … 12

    mango berry Hash function Now what?!
  41. 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()
  42. 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/
  43. 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
  44. 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
  45. <html> <head> <title>My Website</title> </head> <body> <h1>Main heading</h1> <p>Hi! Welcome!

    <a href=“http:// google.com”>You should check out Google.</a> </p> </body> </html>
  46. <html> <head> <title>My Website</title> <link rel="stylesheet" href= "styles.css" /> </head>

    <body> <h1>Main heading</h1> <p>Hi! Welcome! <a href=“http:// google.com”>You should check out Google.</a> </p> </body> </html>
  47. <body> <div class="wrapper"> <div class=“top"> … </div> <div class="about"> <div

    class="column" id="column1"> <h2>Feature 1</h2> </div> <div class="column" id="column2"> <h2>Feature 2</h2> </div> <div class="column" id="column3"> <h2>Feature 3</h2> </div> </div> </div> </body>
  48. HTTP Requests • GET • POST • PUT • PATCH

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

    • DELETE These request methods are the verbs! GET / HTTP/1.1 Host: www.google.com …
  50. HTML hello.html from pset6 <!DOCTYPE html> <html> <head> <title>hello</title> </head>

    <body> <form action="hello.php" method="get"> <input autocomplete="off" autofocus name="name" placeholder="Name" type="text"/> <input type="submit" value="Say Hello"/> </form> </body> </html>
  51. PHP hello.php from pset6 <!DOCTYPE html> <html> <head> <title>hello</title> </head>

    <body> <?php if (!empty($_GET["name"])): ?> hello, <?= htmlspecialchars($_GET["name"]) ?> <?php else: ?> hello, world <?php endif ?> </body> </html>
  52. PHP <?php $foo = 'Bob'; $bar = “Sally"; $foo =

    1; echo $foo; echo $bar; echo "\n"; ?> fjw22@ide50:~/workspace $ php first.php 1Sally
  53. PHP <?php function load($dictionary) { global $table; foreach(file($dictionary) as $word)

    { $table[$word] = true; } return $table; } if (!$argv[1]) { echo("php load.php DICTIONARY\n"); } else { $table = load($argv[1]); echo("Dictionary loaded with " . count($table) . " words!\n"); } ?>
  54. 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
  55. PHP in your HTML hello.php from pset6 <!DOCTYPE html> <html>

    <head> <title>hello</title> </head> <body> <?php if (!empty($_GET["name"])): ?> hello, <?= htmlspecialchars($_GET["name"]) ?> <?php else: ?> hello, world <?php endif ?> </body> </html>
  56. PHP & HTML { "email": "———@————.com", "password": "——————" } Passes

    data via HTTP message body: POST <?php $email = $_POST["password"]; ?>
  57. PHP Superglobals • $GLOBALS • $_SERVER • $_GET • $_POST

    • $_FILES • $_COOKIE • $_SESSION • $_REQUEST • $_ENV
  58. SQL

  59. SQL

  60. 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')
  61. 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'
  62. 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`
  63. 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"
  64. 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};
  65. Javascript function print_words(words) { for (var i = 0; i

    < words.length; i++) { console.log(words[i]); } return true; } http://jsbin.com/?js,console
  66. 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
  67. The DOM <!DOCTYPE html> <head> <title id=“title">The Document Object Model</title>

    </head> <body> <div> <img id="pic" src="pic.jpg" alt="pic"> </div> <div> <p id=“quote">What a time to be alive</p> </div> </body> </html>
  68. Javascript + HTML <script> 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"; </script>
  69. 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.