Week 2

Opening with talk about different reading levels. Cryptography the art of encrypting/securing information. Debugging techniques are also going to be discussed. Debugs some issues like finding missing ;, not including libraries for functions that are run. Next gave a variable a value without giving it a type on initialization. Following this he was trying to use string which isn't a C variable so the include cs50 functions. Next talks about logical problems in code like not printing the right variable. One way to solve logical errors is to use printf in order to see the values of errors. Then talks about putting a function below main but not prototyping to generate an error. Then it talks about using debug50 which is a debugger allowing slowed down execution of code so errors can be found. You can click to the left of the line number in order to add a break point. Garbage value is a value stored in a variable until it is given a value. The value of a debugger is that it allows you to pause and break down code so you can understand the problem causes. The compiler used by VS code is clang even though we use make we could use clang to make files. If you use clang, it will make the program into an assembly out file like a.out. If using clang hello.c you may need to clarify the library with compiler like clang hello.c -lcs50. Command line arguments are the words after the command in CLI. You could use clang -o buggy in order to name the program at compilation. The make command is really doing clang -o hello hello.c -lcs50. When you compile code it is doing 4 processes preprocessing, compiling, assembling, linking. Preprocessing - compiler goes inside the library included and gets the code and gets the necessary information and puts it into the code. Compiling takes the preprocessed code and converts it into assembly code, then it will go and copy paste the relevant things into your program at compiling. Assembling is when the file is converted from assembly into binary or machine language. Then there is linking which combines all the necessary library codes and program code in their machine version forms. The computer knows which represents which based on the location in the file of the binary as to what function it corresponds to. Decompiling - which is when someone takes the machine code and reverse engineers the binary into code to make a program. This process is much more difficult than it sounds, since some of the binary will still be really ambiguous. It is often more complex to read and interpret the machine code than just recreating the program that you wish to recreate. bool - 1 byte, int 4 bytes, long 8 bytes, float 4 bytes, double 8 bytes, char 1 byte, string ? bytes varies heavily based on the string length. In a stick of memory or a DIMM. On the memory there is black chips that store all the zeros and ones. You can imagine this chip as a grid where each cell allows the storage of data types like your variables. Consider a program in which we are trying to find the average of hardcoded variable scores. If you originally do the calculation with integers you would get a truncated average. If you use %f you can use both double or float. You can also convert a value to a float at computation by adding a decimal like / 3.0 or you can specify the variable in the computation like printf("Average: %f\n", (score1 + score2 + score3) / (float) 3); Now consider in this chip on the memory we can consider that each score has 4 bytes for each of the variables for score. When considering a problem try to consider additional complexity like what happens if you want to do it 100xs more etc. How does it handle those more extreme scales? Consider that you could gather 3 scores like this int scores [3]; which would give you 12 bytes of variable space. You could assign the scores like scores[0] = 72; scores[1] = 73; scores[2] = 33. An arrays values will be in a continuous sequence of the bytes since arrays have a reference to the start of the memory storage. You could use a get_int for each of these scores to make the code more dynamic than the hard coding. However, that would still be a little clunky and would be a better design to choose to use a loop where each score was assigned using scores[i] = get_int("Score: ");. However instead of using i < 3 as a condition. You could use a const int N = 3; and then i < N so the constant can be used. It could also improve the code to instead put this average code in a function. Prototype it with float average(int numbers[]); which can be further improved by also passing in a length variable so the length can vary like this: float average(int length, int numbers[]). Remember that chars are in single quotes like 'A' and strings are in double "apple". Consider a program that prints 3 characters, 'H' 'I' '!', if you assign a printf("%i%i%i\n", c1,c2,c3); print command you will get back 727333.This is because the ASCII value of each of these is 72, 73, 33 respectively. The compiler is smart enough to convert the char values into integers for the sake of outputting these values. (What would be the detriment of naming all integers in a similar way?) If you do the same thing with string s = "HI!"; this would be stored as an array of characters in the memory with the same amount of bytes but just connected together in assignment to s. You could also print the values by assigning them like printf("%i %i %i \n", s[0], s[1], s[2]); in order to print the 72 73 33 output. If we try to access a 4th letter from this same array it will print out the number 0. When storing a string of 3 characters, it will actually store 4 bytes. This final character is the null character which is the end of the string. If I have a string like string t = "BYE!"; there would be 5 bytes since at the end of BYE! there is a null in order to signify the end of the string. If I create an array of strings then in actuality I am creating an array of nested arrays. You could print these characters like H with words[0][0] or E from BYE! with words[1][2]; You could initialize the array like int scores[3] = {72, 73, 33};. Consider a program you have a loop like int n = 0; while(name[n] != '\0') { n++; } printf("%i\n", n); which is a way to find the length of a string or an array through a loop. For C you can also use #include which will give you a library that will give you many of the string functions. This includes the length loop listed just before for finding length with just a simple length command. printf("%i\n", strlen(name)); which would give you the same output through the function strlen() which would give you the length of a string. This library just includes a set of code similar to the while loop that gives us this functionality in this simple function. It can be very awkward to use a function as a condition check like i < strlen(s); since each time it will have to run the code of the function. When you initialize an array you need to use all of the same data types. Consider a new program like this #include #include #include int main(void) { string s = get_string("Before: "); printf("After: "); for (int i = 0, n = strlen(s); i < n; i++) { if (s[i] >= 'a' && s[i] <= 'z') { printf("%c", s[i] - 32); } else { printf("%c", s[i]); } } } this program uses the number 32 because that is the exact value between the characters lowercase version and uppercase versions. You can also include a different library for the ctype.h to help you to raise cases for upper to lower. You can make the whole loop print with printf("%c", toupper(s[i]));. This is demonstrative of the fact that usually if there is a common problem there is a library function that has that function in some kind of library. Main is a special function and there is a reason for the int main(void). void just means that the function does not take command line arguments. You could also make main like this int main(int argc, string argv[]) {}. int main(void) { string answer = get_string("What's your name? "); printf("hello, %s\n", answer); } You could also take away the include statements at the start besides stdio.h, cs50.h and use int main(int argc, string argv[]) { printf("hello, %s\n", argv[1]);} Now when you make greet you can do ./greet David you will get hello, David. You can make the program a little smarter like this int main(int argc, string argv[]) { if (argc == 2) { printf("hello, %s\n", argv[1]); } else { printf("hello, world\n"); } } which is a bit smarter so that way if the user doesn't specify a name on the program initialization that it still prints a default. The value that main returns is the exit status. This is similar to error messages like the 404 file not found error message from browsers. Consider a program: int main(int argc, string argv[]) { if (argc != 2) { printf("Missing command-line argument\n"); return 1; } printf("hello, %s\n", argv[1]); return 0; } You could use echo $? the command line which will print out the return value of the program which in this case would be zero. One of the ways check50 works is through using these command line checks which are sort of secret to everyone except the developers. You could use cowsay moo in which it will print a ascii cow. You could also use cowsay -f duck quack which will make a little duck. cowsay -f dragon RAWR which will make a dragon with ascii arts. This is due to the original developer creating code that enables the functionality of these commands. Cryptography - the art of scrambling information for the security of that information. We will explore different ways in which we can use encryption in order to scramble the messages and secure it. Which would be like plaintext -> cipher -> ciphertext. In order for this to actually work then you will need to have a secret which is known as a key. A special number in computer circles is 13 like rot13 which just be using letters 13 letters away from the intended character. If you use 26 as the key it will just bring the letters full circle and print the same letters. This form of encryption is known as the Caesar cipher which is a cipher allegedly used by Caesar to communicate with his generals.

Week 3

Opener contains some artists renditions of various sorts in sorting. Starting with an algorithm for taking attendance, all attendees stand up and think of the number 1. Pair off with a person standing, add their number to yours and remember the sum. One person sits, then repeat this process until all attendees are accounted for. Count by 1s would be a straight line on time to solve/size of problem can be thought of as n. Then n/2 would be like counting by 2s which would be faster but still linear. The algorithm above would be something more like log2n and more logarithmic function. Consider an array and the chunks of memory storing values like 1,5,10,20,50,100,500. These arrays are kind of closed doors from a bird eye view, which means that a computer needs to access each value one at a time. Each value needs to be visited in say a locker of 0,1,2,3,4,5,6(indexes). In each locker there is an amount of money. First algorithm used to just go one at a time left to right. Kaitlyn used an algorithm where the lockers were sorted she went to the middle then decided which direction would lead to the 50. Introduce pseudo code like For each door from left to right | If 50 is behind door return true | return false. Which would be wrong since it would only execute once. Then transitioned into a loop pseudo code like For i from 0 to n-1 | If 50 is behind doors[i] Return true | Return false. Binary search If 50 is behind middle door | return true | else if 50 < middle door| search left half | else if 50 > middle door | search right half. Go back and add if no doors left return false to the beginning to eliminate an edge case where it doesn't have more doors to open. Finding middle pretty easy just divide by 2 round down (for index value). Running time we can use a graph with different functions graphed. Introducing big O notation, first algorithm O(n), O(n/2), O(log2n). Some algorithm times O(n^2), O(n log n), O(n), O(log n), O(1). Linear search big o O(n), binary search O(log n). Also compared omega value which is teh best case, so in teh search it would be potentially one try and get the locker. Binary search is also omega 1. Lastly is theta which is when big O and omega are the same. There is no examples so far of a theta algorithm. These are all ways of doing asymptotic notation. Going through coding a few points were brought up. When initializing an array that we plan to assign all values on initialization we do not need to add an array length and it may in fact be better to not do this. Second, you cannot compare two strings using ==. You will need to use the string.h library and use strcmp to compare the strings. strcmp returns 0, -1, 2 which helps to sort the values in ASCII order when they are not the same. Also brings up that a lot of programming is about making sure that the systems you implement kind of help to prevent future mistakes like two arrays that don't actually link values but just are supposed to be ordered to match. Person data type desired, we can do this by creating our own data types to make a person data type. typedef struct { string name; string number} person; Selection sort runs by searching all values and finding the lowest, swapping to the front searching the values finding the lowest, moving to the next spot etc. The next sort was the bubble sort where the bigger values kind of bubble up by swapping with the next repeatedly until it reaches the appropriate destination. Selection sort pseudo code for i from 0 to n-1 | Find smallest number between numbers[i] and numbers[n-1] | Swap smallest number with numbers[i]. O(n^2) and omega(n^2) and theta notation is (n^2) is the value of selection sort. Repeat n times | For i from 0 to n - 2 | If numbers[i] and numbers[i+1] out of order | Swap them. O(n^2) and omega(n). Bubble sort can be improved unlike selection sort by saying if no swaps | quit. Because it is possible to abort early and still have all the sorted values, unlike selection which has to check all to make sure they are the lowest value or 2nd lowest, etc. The omega of bubble sort is n, because it only has to pass through once and then it can terminate so it doesnt give us a theta. recursion function is a function in terms of itself, or a function that calls itself. If no doors left | return false | If number behind middle door | return true | else if number < middle door | search left half | else if number > middle door | search right half | else quit. When building a recursive function you are calling itself over and over and creating progressively smaller versions of the same thing. the merge sort utilizes recursion to sort quickly. If only one number | Quit | Else | Sort left half of numbers | sort right half of numbers | merge sorted halves. So david takes a set of 8 numbers and throws half on one side half on the other sorts them. Then the sort basically just asks which ones bigger and merges into the 3rd list based on the rest based on that one condition. Big o of merge sort is n log2 n. Merge sort also has omega n log2 n, therefore theta of n log2 n.

Week 4

Opens with students creating pixel art using two different colors of sticky notes. This is to represent pixels and introduces students to the concept of pixel art. Showing an image at a close zoom also demonstrates the pixelation used. Shows a 1 bit image where there is a smilie face created by just using zeros and 1s in an ascii art sort of form. Taking it to the next level by showing a grid or graph with the smilie. 255 is the biggest number 8 bits can represent as we start talking about RGB and how each color is represented with values for red green blue between 0-255. When CS want more than 10 digits they start to add letters so 0-9a-f is for hexadecimal for a base 16 system used to name colors. This of course means that each value is 16^a number the same way as the other bases. In hexadecimal you go to a new place value when going above the letter f. If you want to represent 255 using hexadecimal you would just need to use FF. In binary this would be 1111 1111. This is because base 2 is very similar since 2^4 is just 16 meaning 1 hex is 4 digits. In memory, it is common that people use hexadecimal because its easy to think of 0-f for the first 2 rows. Then after that it would be 10-1F, since there is a bit of ambiguity there is often 0x in front of it to represent that 0x10 is 16 not 10 when it is represented as 10. Created a program that just makes a single variable n = 50 and printing it. The n=0 variable is using 4 bytes aka 32 bits. This variable may be at location 0x123 which just means hexadecimal 123. If you use $n you are asking for the address in the memory and %p for the print statement. Starts on the topic of pointers. Pointer is a variable that can store an address of a value in memory. A pointer can look like int *p = &n; * means that this stores the variables address. You can put the asterisk anywhere between int and the variable name to create the pointer. A pointer is 8 bytes large by convention inside the memory. p is a variable that points to the location 0x123 in memory. If you have a print statement for an integer, and you dereference the pointer variable by saying *p(p is the pointer variable name) then it will print out the value of the integer that the pointer is pointing to. In strings, a string of HI! would take up 4 bytes. This is for H, I, !, and the null operator. The addresses are stored in 0x123, 0x124, 0x125, 0x126 since they all have to be stored in sequence. In the variable of s the actual value stored is a reference to 0x123 because the array is a reference to the start of the array. The s string has always been a pointer that points to the beginning of the array. If we modify our program to display all 4 characters pointers to their address the program will display 4 numbers in sequence of each other incrementing by 1. The string just includes the reference since with the beginning and the end you can find everything in between with a loop easily. String has really meant char *s since the beginning, in the library string is really typedef char * string;. If I want to print out characters I can use the pointer reference to the string. For example we could use *s and *(s+1) to get the first 2 characters. When comparing 2 strings we include the string library to make the comparisons. In the memory the variable s is just the reference of 8bytes 64 bits that includes the starting address of the characters H I ! null. When I create the second variable it's made the same way with a new set of characters that are H I ! null where t stores the start of that set of characters. So the strcmp will loop through these 2 pointer references from the start to the null values to see if each character is the same. If the program is recreated and we print the pointer, we would see that even if the strings are the same the pointer references are not the same. Start copy program, set two strings = to each other and change one to upper but both are made into capitol upper. This is because the two strings are copied and they are both pointing to the same String. This means that when they are printed they are both going to the same location. Memory allocation or malloc is a function used to help this problem. Also introduce strcpy from stdlib.h where you pass the intended copy and then the original. Null memory address that 0x0 that isn't used unless something is wrong. If the user types in too long of an input or other user errors for the input value which will result in NULL. To prevent memory leaks end the program with free(t); where t is the variable name. If you malloc you need to free it at the end to prevent leaks. valgrind - good to specifically chase down memory related errors. Starts with a program where x is pointing to a malloc of 3 * sizeofint or 12. Valgrind is a program that helps us to find memory errors in our program. Run valgrind with your program to see the memory errors related. One error was invalid write of size 4 which means that there was an attempt to access an element of an array that was larger than the array. In leak summary tehre was a definitely lost of 12 bytes because there was no freeing. When we use valgrind and all heaps are freed its a good thing and recognizes no memory leaks in the program. Pointer fun, in this section there are 2 integer pointers. When you use dereference and an invalid value is assigned it can result in errors or program crashes. Pointers do not initially point to anything, and the pointee needs to be created on its own. You can allocate memory for a pointee using malloc(). You can dereference *x = 42; so that the pointer points to 42. If you try to skip over to just *y = 13 the dereference will not work. You can instead point it to the same place as another pointer and then assign it to the value which would switch both pointers value they are pointing to. This illustrates some of the potential power of c where you can really have performant programs. Swapping, student goes up and is given 2 glasses one with blue water one with orange. They are asked to swap the liquid colors but they are hestitant becasue htey need a third glass. The third glass is given to them. The student put the red water in a temporary cup, filled the blue into the red, temp into blue. Create a swap program where it does this exact process with a variable a and b integer values but it doesn't actually swap. This is due to an error in scope. Any time you pass arguments to a function you are passing copies to the functions you are calling. Memory is assigned in a deliberate fashion, machine code is loaded in the top. Globals are below the machine code. The heap is chunk of memory that malloc uses to allocate memory for you. The stack is the area of memory that is used when you create local variables or for functions. Analyze the stack main <- int x(1) and y(2) <- a b tmp. Passing by reference, or using pointer values. This is how we will fix our swap function instead of passing by value. We can do this by assigning addresses for a and b as *a and *b. This will change hte program so that the values get the address of x and y. This will create a potential problem since you are basically adding to the heap and to the stack which will eventually collide. It's important to only use malloc and equivalents exactly as much as needed so that they do not end in a heap overflow or stack overflow. A buffer overflow is when an array is trying to receive too many values. Scanf is the c version of the cs50 training wheel of get_int etc. Create a get program where we declare n and then we scanf with the reference n so that it can be assigned the value to the variable. Then to change the program to get a string starting with char*. When running valgrind it produced a ton of errors despite seemingly working with lots of inputs. This is difficult because the string needs to be assigned a value. This is part of the reason why when you are typing in values in an input there is often a character limit. File I/O or input output. Starts by talking about volatile memory or ram and hard drive or persistent memory. Some commands that allow you to do stuff with files in c: fopen, fclose, fprintf, fscanf, fread, fwrite, fseek. In the first iteration of the program for this step as we type in an input it goes into the csv and rerun the program the values are lost. The fix for this problem is to change the opening fopen command to instead of "w" to a "a" for append. Where it will append to the end of the file. Also important that any time that you start to use pointers that you check for null values. Pointers are required for file i/o in C. Moving to a segment about buffering.. A buffer is a chunk of memory. In order to declare bytes we use a typedef so we can have a place to store it, and we use an unsigned char which does not allow negative values. You can also use for the file command "r" for read "w" and "rb" "wb" to make sure that it is in raw data or bytes only. In the next problem set we will experiment with BMP which is bit map photos which is like a grid of pixels which is each represented by a color. You will also be able to create your own filters so that the pictures can look different. Implement sepia or black and white photo filters. You can also apply a blur filter and do edge detections.

Week 5 Lecture

Last week of C and more data structures. Then we watch a video about jack and stacks and queues. Jack needs to change his style so he recruits help. Lou learns that Jack keeps things in a stack and cleans things and puts them on the stack. So he is constantly picking up the same clothes. Lou recommends that Jack needs a queue. He hangs all the clothes on a hangar so he can get clothes one at a time from the rihgt side and put new things In on the left. Queues is typically what you experience when you get in a line. Queues have a FIFO, first person in line, first person out of the line. A queue has two operations enqueue - getting in line and dequeue getting out of the line. You could create a queue in c like this : const int CAPACITY = 50; typedef struct { person people[CAPACITY]; int size; } queue; the catch or limitation of this implementation is.. that it's only for 50 students. Stacks have a LIFO property which is last in first out. This is pretty much the way laundry works since the last one you take out is the first one you take off the stack. To use a stack you need to implement push - push something on top of the stack and pop take something off the top of the stack. Stack code could look like: const int CAPACITY = 50; typedef struct { person people[CAPACITY]; int size; } stack; . Dictionaries abstract data type which is really a 2 column table containing the words and definition. You can also see this data structure like a phone book. A computer scientist would associate this with a key and a value. There may be lots of design choices when creating a dictionary. Arrays chunk of memory where datas of the same type are stored back to back. In order to give a new value to an array you would typically need to copy all the array to a new place in order to add the new value. We can use realloc to reassign the values from a malloc into a new place. Realloc does two things which is allocate the bytes to a new place that has teh space or check to see if it can be added to the current array. First alternative to arrays is the linked list. Moving away from just making the values contiguous and instead make each element linked to the others. Arrays are statically allocated. Two chunks of memory for every value where each second value is a pointer to the next value. A node is just data with meta data which is just a pointer to the next value or information to another variable. To keep track of the values you will need one additional value which stores the address of the first node. The last value would have a pointer to null to have the typical array ending. The integer is 4 bytes, pointer is 8 bytes so each node is technically around 12 bytes. In code this may look like typedef struct node { int number; struct node *next; } node; have to make some of these extra node names similar to prototyping so that the compiler knows that we are using the struct earlier. A list is a referenced variable since it uses the pointer node that points to the first element or head as the initial value and core data value. node * list = NULL; which this line basically makes it to where the nexts value is not a garbage value. n points to the next number after this line, then the next meta data is going to point to null. Then in the next value we get a new value and get a new memory value for a node clear out the garbage and set the int to the user input, but the problem is that the original arrow is no longer pointing at the first one. This needs to be changed to n->next = list; this will give a continuous change like a sewing needle after the n value is removed. Inevitably this will result in the whole list going backward. Big O notation of prepending each element to the front of the list is 1 or O(1). If appending at the end the O notation would be O(n). The problem here is that even though we now have a way to create an array that is more dynamic and can take up a lot of different spaces it is not faster for many different things than arrays. A common alternative to linked list is a double linked list. This basically attaches the linked list to the next and the previous for easier travel. This simplifies the code writing but it does not solve the issues the data structure's performance difficulties. A proposed alternative is a mixed data structure which is a tree. The roots are at the top but its also a 2 dimensional data structure. This will have binary search trees which will enable binary searches again for the performance. The leaves(leaf nodes) are the bottom because they are children without children. Nodes in trees have 2 nodes a left and right pointer. Data in a tree are in order so that the left pointer is less the right pointer is more so they can use binary searches. Most tasks with a tree are big o O(log n) and a key part to remember about what determines this is that the data is repeatedly halved. The issue with a tree structure is that there is a lot of memory usage is high because there is 2 pointers. The node struct only need to have the one extra pointer in code writing. To traverse the tree bool search (node * tree, int number) { if(tree == NULL) { return false } else if( number < tree->number) { return search (tree->left, number); } else if ( number > tree->number) { return search(tree->left, number) } else { return true } }. The onyl bad part of trees is that if the information is entered in a certain way you can end up with a linked list. Hashing infinite domain into a finite range. First example is a deck of cards being put into different buckets to separate the problem into 4 problems instead of just one. So for contacts.. mario as input would give back the output of how many ms contacts there are. A hash function may look like #include int hash(char *name) { return toupper(name[0]) - 'A'; } . If you are passing in a value by reference use const so that way we can avoid accidentally change the value at the reference. Hash tables are how you would implement keys and values, a hash table is an array with linked lists. One of the issues with hashmaps is called collisions which is when there is some difficulties which is when there is say too many people with the same starting letter. A potential solution is to use more letters like spacing out all things with the first 3 letters. Big O will end up being O(n\k)which still ends up being just O(n) even though it is technically faster than a linked list. Tries is the real way to get to O(n). Goes to the first letter of the name and makes a pointer to their name. Changes each letter into the letter from a pointer from null. The last letter would keep null so that it marks the end of a string. Each letter you need to hash to find the letter when searching in order to find whether a value is there or not. The O run time will end up being the length of the names in order to find them. The issue with tries is that its a huge amount of memory being 26 nodes for each character.