Submind YouTube summaries
Thumbnail for Lecture 9: Programming - CSCI E-1 2010 - Harvard Extension School

Lecture 9: Programming - CSCI E-1 2010 - Harvard Extension School

Watch on YouTube

Video summary

Programming is fundamentally the act of writing precise instructions, known as source code, to direct a computer's actions, a process that requires logical thinking because machines lack intuition and can easily succumb to errors like crashes or infinite loops. While there are hundreds of available languages such as C, Java, Python, and PHP, they all serve as human tools for communicating with machines, differing primarily in how they are processed; compiled languages convert code into binary files that require recompilation for changes, whereas interpreted languages execute code line-by-line allowing for immediate updates. To illustrate these concepts, the lecture contrasts syntax differences using "Hello World" examples and highlights the critical importance of avoiding logic errors, such as failing to decrement a counter in a loop, which can cause a program to hang indefinitely. Beyond basic syntax, effective programming relies on defining algorithms as step-by-step sequences to solve problems, ranging from inefficient linear searches to efficient binary searches, often visualized through analogies like looking up names in a phone book. A practical example used to teach fundamental constructs involves an algorithm for putting on socks, which introduces variables to store states, loops defined by indentation rather than braces, and conditional logic to handle decision points. However, real-world applications reveal complexities such as infinite loops caused by empty drawers or ambiguity in handling paired items, leading to the introduction of Scratch, a graphical programming environment designed to make these concepts accessible by allowing users to build scripts through drag-and-drop blocks that handle sequential execution, motion, sound, and event-driven interactions like detecting mouse proximity. As programs grow in complexity, developers must manage data using variables initialized with specific values before use, distinguishing between local variables restricted to single sprites and global variables accessible across the entire program. Advanced structures like lists allow a single variable to store multiple items for tasks such as inventory management, while multi-threading enables simultaneous operations where different sprites or processes run in parallel without interfering with one another. Communication between these independent components is achieved through events, where one sprite broadcasts a signal that triggers a response in another, mimicking real-world interactions like the "Marco Polo" game. Ultimately, mastering these core building blocks—loops, conditions, variables, lists, threads, and events—empowers programmers to decompose complex real-world problems into manageable components, fostering transferable skills that apply across various programming languages without the need to memorize intricate syntax.
Read the full video transcript
all right welcome back to computer science E1 tonight is our lecture on programming next week same time same place will be exam 2 uh we will have led by Alex our teaching fellow a review session after tonight uh in Li of the regularly scheduled section that will be filmed though for those who can't stick around or who are tuning in on this video uh this coming Wednesday we will post the upcoming assignment and also some specifications for the final project which is due several weeks hence but we'll culminate the course with a little bit of website design so today's all about programming um what does it mean softball question to program even if you've never done it before give me something writing code writing code okay so now we have a cyclical question what does it mean to write code no looking down at your papers as an alternative what's that gives instructions to the computer to do something good so giving instructions to the computer to tell it to do something so you can kind of infer this answer from weeks ago when we talked about software and what a program is something you might double click on a computer to actually run some program well to program as a verb means to write those kinds of things to write some set of instructions somehow transform them into zeros and on so that when executed so to speak they tell a computer to do something so programs can do all sorts of things right you can use them for email for web browsing for writing documents really anything you've ever seen a computer do is the result of one or more persons having written some program AKA software to tell or inform the computer how to do that but more generally um writing programs is about thinking logically and thinking methodically and unfortunately as sophisticated as you might think the computers on your desk at home or at work are they're actually pretty dumb devices because they can only do what you tell them to do and if you are not ever so clear and ever so precise what tends to happen in programs from what we've discussed they crash right you get some kind of bug some kind of unforeseen Behavior infinite Loops or uh spinning beach balls or just things grinding to a halt unexpected Behavior tends to ensue if you haven't quite thought through all of the possible consequences so you may have heard now of languages Pro computer programs can be written in all sorts of languages what languages might you be familiar with even if you've never seen them yourself okay so Java is a popular one c c is another one C++ is another came after C C sh is another one from Microsoft others HTML uh so HTML is a language but recall from last week it's not a programming language but a so it's a markup language it's a you can tell the a browser how to display something but you can't necessarily tell the computer how to save files or open windows and with HTML alone it's really about marking up data so we'll leave that off this list for today other programming languages though basic oh say basic from yester year one of the earlier languages that some of you may have grown up on myself included okay so CSS sorry I have to strike this one down too CSS is another one in the genre of last week that's used really for Aesthetics for rendering data but not instructing a computer what to do but rather how to do something aesthetically so let me leave that one off the list but you get three tries every lecture yeah what's that ah okay so we're really going backwards in time what else python okay python is an increasingly trendy one just round out the list with one or two more if you've heard of any Pearl is another popular one a lot of websites these days that are Dynamic that take input and produce output are uh implemented in a language called PHP XML uh so XML I'm going to have to put that in the last week bucket uh it can be used for different things but at the end of the day it's extensible stands for extensible markup language so that two wouldn't belong in the programming bucket okay R good some of the more Arcane ones but that's okay yeah okay so also going a little back in time there's another one where everyone was freaking out over uh the lack of people who knew this language around Y2K for so Fortran was another one that a lot of folks here might have grown up with but that has fallen into largely disuse simply as the result of more modern incarnations so suffice it to say much as there's a ridiculous number of spoken and written languages in the human world there are all sorts of programming languages in the computer world that humans have invented none of these just have existed from the beginning of time humans have implemented or designed all of these languages from scratch with which to communicate uh uh their instructions precisely to a computer so what all of these do you can you can basically just understand these as languages just like you would understand uh different uh languages to communicate with other people in other words this is just a way of communicating to a computer and so in order for a computer to understand one of these languages it has to well I mean it has to be able to understand it in order to do something with it but specifically for most of these or many of these what actually happens on sort of a higher level is is this task or this uh this activity that's performed on this source code so you write a program in one of these languages and then you use something called a compiler and then a compiler will take all of this source code and convert it all of the these these little things that you've written all of these statements all these commands that you've written in one of these languages and it will convert it to Binary ones and zeros in a fashion that a computer will actually be able to understand so the end result should be some sort of an executable file that has a pattern a specific pattern of ones and zeros that it will be able to understand so if you if you recall from um some of our initial lectures way back say to lecture one each for example the CPU the the central processing unit inside of a computer understands a fixed set of instructions so maybe uh a certain sequence of ones and zeros will tell the CPU that what you want to be able to do is actually add two numbers so then it will be able to understand that okay with this sequence of ones and zeros I want to add two numbers and so the the job of a compiler then is to convert basically or to compile all of this code that you've written in one of these languages from this higher level language that you've written into this sequence of ones and zeros that the computer will then be able to understand and so when you're writing one of these programs it's usually referred to as a couple of things and one of them is or or it is it is called generally like source code so if you writing code uh what you are writing is is a file that in in general known as source code then you typically use a compiler and it's just converted to these ones and zeros that the computer will then be able to understand and so recall that um the computer and specifically the CPU has a fixed set of instructions so for example you can tell a computer to add two numbers together with a certain sequence of ones and zeros and that you might imagine that that means that there's between different CPUs for example uh between Intel processors IBM processors or AMD processors or even different versions of processors the the instructions might be a little bit different or the the actual binary that's used to perform something is a little bit different and so that's why there's so many different compilers that can exist for pretty much all of these languages they have to be targeted specifically not only to one of the languages but also to What's called the architecture or just this the the computer uh as a whole and the instructions that that computer is able to understand so even though People Like Us certainly couldn't teach you a new spoken language like Spanish in just one night similarly tonight can we not teach you the entirety of any one of these languages but what we will use is a graphical language that was developed in just a few years ago from some folks down the street at mit's media lab this environment or this graphical language is called scratch and as you will see in just a little bit it allows you to program quite literally by dragging and dropping puzzle pieces Each of which happens to Res represent some of the low-level building blocks that Dan alluded to like addition and subtraction but the nice thing about it being very graphical and visual is that you can actually see pictorially how certain instructions fit together logically and how various programmatic constructs as we'll call them to use some lofty jargon here um fits together and allows you to go from nothing to a program that actually does something but just so that you can see this in the context of a a real so to speak programming language or something that a person might use really to solve an arbitrary problem with the computer I'm just going to go ahead and load a program here on my Mac this is a program called terminal anyone who has a Mac has this program but what's neat about Mac among other things is that you can actually uh use what's called a command line it's a somewhat Arcane interface where you interact with the computer by typing commands instead of by pointing clicking but because what I want to use here is a language called C initially it allows me to interact with the system as folks originally did when this language came out so if I wanted to write a simple simple simple program whose sole purpose in life is to say hello when you run it on the screen I can go about it in this way and this is intentionally introduced here to look a little cryptic I first have to say a little something like this this is a uh sequence of uh charactera whoops let me increase my font size so this is a sequence of characters that simply tells this program to go include some source code that someone else years ago wrote and standard io. is simply a file text file that contains that code that someone else wrote and it has some built-in functions as we'll call them some built-in functionality that I can leverage as a programmer years hence to have the computer do some very basic things for instance I have no idea off the top of my head how I can make a computer spit a certain asky character out on the screen at a given location but thankfully because others have paved the path before me and written what are generally called libraries I can use programs that other people wrote inside of my own programs in order to get started and not have to worry about writing myself zeros and ones that people years ago had to do so that's the first line of code I then have to do something like this this is main the main part of my program and then I have to do some crazy stuff with some curly braces here you might not often use them on your own keyboard but they're very common in programming and then it turns out that there's a program or really function that someone years ago else wrote whose sole purpose in life is to take a guess print something to the screen now as for that f it means print a formatted string which means you can actually format it in certain ways but this function as it's called takes what's generally called an argument and that argument is simply what it is you want the computer to print in this case so I'm going to go ahead and say print quote unquote hello now the syntax I have to use is another parenthesis and a semicolon and these are the kinds of stupidities frankly that plague a lot of programming languages certainly for new programmers because you just have to start to memorize or remember that you need parentheses here quotes here semicolons here and this is why you'll see in a moment that we intentionally choose a language like scratch because it allows us to do very similar things and make much more interesting programs in the first day without the silliness of this syntax so now I'm going to go ahead and as Dan said I'm going to save this source code so now we're here so the next step in creating a program is to run this source code through what compiler a compiler now there's many different compilers in the world a lot of them are free some of them are commercial Microsoft if you've ever heard of a project called visual C or Visual Studio visual C++ a lot of people programmers at work you might know have mentioned this at some point that's just a really big program Suite among whose tools is a compiler the one I'm going to use on this Mac which is common also on Unix and Linux systems is called GCC and I'm going to run GCC on this file called hello.c that was the name I gave this text file I'm going to hit enter nothing seems to have happened but it turns out and this again is a stupid Arcane convention the default file name that this compiler spits out is a file called a.out a because probably it's the first letter in the alphabet it's the first program I made andout because it's been outputed and I go ahead and hit enter voila I have now written a computer program so all this time if you've ever wondered how programs are actually written well there's many more steps after this to actually write a word processor and a spell checker and the like but that is what a typical programming language actually looks like so what exactly that [Music] consist programing language what exactly does that consist of uh can be more precise what do you mean consist of like it's what would it tell us light for instance oh sorry what tell the lightning what would that what does that tell like the people in general uh what does this tell the PE uh yeah what exactly does that mean as program langu oh okay so what exactly is the programming language right oh okay so it's that's my fault for not being precise so when I originally opened this blank file and started typing commands like this so think of a a reasonable analogy as being suppose my computer only speaks and understands Spanish and I want to tell this computer to say something in response to me I would have to type out like Alo like say something to me in Spanish and then hit enter and then that computer would presumably respond because the computer too understands that particular language well this computer does not understand Spanish it understands zeros and ones now I the human don't speak zeros and ones but thankfully there's this middleman that exists a program itself that other really smart people wrote long ago that takes source code that looks like this which is just an arbitrary set of rules that some humans decided if you want to write a program the first thing you do is say int the second thing you do is say main the third thing you do is open paren close parenthesis the next thing you do dot dot dot so th this is an example of a program written in a language called C much like if you looked at a printed essay that an essay would be an example of an essay written in English so when I actually run that source code that program through the compiler what I get out stored in a separate file Al together is one that I can then conceptually doubleclick or run by typing its name at the command line and that will instruct the computer to do something in a language it understands even if I don't understand all of it myself yeah so you said each source code has own compiler exactly each language so so source code is more generic each language has its own compiler but that's a bit of a white lie because there's different types of languages out there some of them are in fact compiled in this way into zeros and ones but some of the languages on this board are what are called interpreted languages whereby the computer does not convert them in advanc to zeros and ones but rather similar to a browser in HTML it reads your program top to bottom left to right and essentially converts it line by line to the actual program and let me reveal one more detail just to make clear that this uh this is one example of a language let's do really fast another one by doing hello. Java so now I happen to speak multiple spoken languages I also happen to speak multiple computer languages so here I'm going to do something like this class hello and again these are fairly arbitrary human conventions and now I'm going to say public static void main string args and then let me go ahead and indent this the indentation is just a human Convention as well and then I'm going to say system.out.print line hello and actually I'll call it print F2 so notice it looks different there's definitely some similarities there's that keyword main there's that keyword print F but it definitely looks different from the previous version there's some different syntax and in fact the procedure via which I run this program is slightly different instead of using GCC I need to use a compiler designed for Java so I use a program called Java C hit enter again nothing seems to happen but now I can run another command called Java itself no C no Java C for compiler just Java and then the name of the class I just defined and hit enter and voila now I have a program written in two languages so to summarize we have hello.c which is this program here and and then we have hello. Java which is this program there they achieve the same result but in a different way much like in reality could you say hello to someone in different spoken languages and this is actually a very useful thing so it it sounds very arbitrary just to write a program to say hello but this is the sort of introductory program that is that is very very popular and in fact it's generally called a hello world program where uh usually what people are shown the very first time they're introduced to a new language is how to do this exact thing what series of of characters they're actually supposed to type in order to print out to have the computer print out hello world and in fact uh let's see switch me over number one there's something like 200 plus different types of programming languages if not more and it's very difficult for um for people to know all of them obviously but usually once you understand uh some of the the main concepts of programming it's pretty easy to pick up uh some other programming language just because then you can figure out what the other syntax is or what the actual words are that that represent something in a different language uh and it's and so you might then be able to relatively easily pick up something else so for example uh what we saw before was a c program to print out hello but what if we wanted to look at say C++ well it would look it looks slightly different but you can see there are some similarities in order to accomplish this same goal and so there's C++ um Let's see we had a c down here and usually um this this sort of thing becomes actually kind of a a game to a lot of programmers where they actually try to figure out what the the shortest program is to make a Hello World to actually make it print out hello world and it's always some big thing whenever they can figure out how to uh print out hello world in the fewest number of characters possible but that's sort of um tangential to this and there is um other programming languages so what David mentioned before and what the examples that he provided for both C and Java are examples of of these compiled languages and Java is sort of shaky it's it's really difficult to say that um it follows this exact same model but you can essentially think of both as being compiled however he also mentioned that there were these other class of languages as well that are interpreted and in other words you can think of this as being um whereas the compiler as soon as you write some some source code you have to compile it first and then the resulting file you can run it's an actual application that you can run an interpreter is different it's sort of like what it sounds it takes a file in whatever source code and whatever language you've written and it interprets it in that directly from that source code and it interprets it into the zeros and ones directly so that you usually have to have another program an interpreted program or just some sort of a helper program to help you accomplish the same thing so to just pluck off another one another one of these languages PHP for example this is an example of an interpreted language so if we wanted to write just a very simple hello world PHP program we can just create a new file and here I'll make it bigger and then we would just do something like this well I guess we'll do print F just to make it look similar all right so now that's pretty much it now I've written this program in PHP and I will be able to run it if I can find an interpreter and in fact PHP uh does have its own interpreter uh and we can run it very simply by running a program called PHP so there's a program somewhere on my computer that's called PHP by running it and telling it that I want to run hello.php it will run it will first interpret and then it will run the code that exists within this this source code so it's important to note that there's a difference here between compiled languages and interpret it so compiled again you just you write some source code and then every time you want to run or not every time but when you want to run the program you must compile that source code into ones and zeros and then you can run that that compiled file any number of times that you want it's just a it's just an executable file that you can double click or that you can run from the command line and it will run whereas interpreted languages when you write the the application or when you write the source code you have to run it through an interpreter in order for it to actually perform its task yes for the compiled language once you've um assembled it into binary can you actually edit that binary file in open it up in theory you could yes if you knew what you were doing and when we discussed a couple weeks ago in our security lectures the idea of cracking software and bad guys figuring out how they can circumvent prompts for instance for serial numbers or the like what sometimes they do is exactly that they take the binary because they don't have physically the source code and try to figure out where the lowlevel zeros and ones are that represent ask for serial number right and along those same lines it's it's obviously now a lot easier to modify an interpreted file or to when it when rather it is a lot easier to make a change and then run it immediately because you don't actually have to compile your source code when it's an interpreted language you can just make it whatever change so if we want to actually change for example what this says we can just change change uh from Hello to hello world uh run it again via PHP and now it says a new text whereas using a compiled language we would actually have to as soon as we save the source code we'd have to recompile it we'd have to recreate this binary code so that now when the computer runs that that program it it sees that change it has that change within that that uh that executable file and it will then show you whatever changes have been made and that might seem Irrelevant for such simple programs as the ones we just just wrote that say hello because if you recall running GCC running Java C took what half a second maybe but consider that we've just written programs that are two lines long five lines long whereas real software something like Microsoft Word these days or Windows is literally millions of lines long and dozens hundreds of people will have written those lines of code so compilation the act of compiling a program can take know seconds or minutes for much larger programs yes each time that you want to run that program you have to run like we have PHP hello PHP you have to run PHP and then yes for an interpreted language every time you have to the computer won't understand this uh hello world so just to do just to mirror what David did before if I try to run hello world it's it doesn't understand it just gives me a bunch of VAR it doesn't understand what this this random gibberish is it's not in binary language so if I wanted to run it I have to run this source code through an interpreter and so then yes then for a PHP file I do have to run PHP every time I want to do it now there is the um it's possible to tell the very top of a line in the specific case of PHP just so that um you know I mention all of all of the uh all of the details here uh it is possible to put at the very beginning of this this uh PHP source code what interpreter it should use and then you don't have to type in PHP hello.php but it's still the same thing it's still using an interpreter to understand the source code uh interpret it into binary and then actually run the code as it's as is as it is shown so what I thought I'd do just to tease you now with what you can start to do with programming languages is right now we've we've written programs using only what's called generally a statement a statement is like an single instruction that tells the computer to do something in this case print something to the screen well what if we want to print something multiple times Well if I go back to my original example arbitrarily the one that was written in C well if I wanted this thing to print to the screen multiple times you know what I could do just copy paste and this will now print hello 10 or so times let me go ahead and rerun a. out and oh wait whoops a DOT out and hm why did it only say hello once you didn't recile right so see is a compiled language so we have to recompile it we're missing this step so okay GCC hello.c okay now I run this program called a. out and there's hello 10 or so times now this should already strike you as a little inefficient right if you have a lot of smart people in the world that are supposed to be writing programs that allow you the human to do things multiple times spell check your program uh your document again and again you'd hope that someone just hasn't written code that generally looks like this inside the file you'd like to think that there are other constructs or other fundamental types of uh code you can write with which you can instruct the computer to do things optionally or multiple times cyclically and in fact you can it it differs based on the language and we'll see in a moment how to do it in the graphical language called scratch but I might do something stupid let's say like this do the following while two is less than three now this is a completely inan program but it hints at the fact that you can in fact perform logic you can compare one number against another one sentence against another one word against another so very arbitrary example but one that's important because it is always true or always false this statement always true it's always true two is always less than three I'm not changing the numbers two or three so anything inside of these so-called curly braces you might imagine conceptually is going to happen again and again and again because it's going to do the following while two is less than three and that's unchanging so now let's put that's comment in the middle print uh print F hello same syntax but now it's inside what we're going to call a Loop this keyword while demarks the start of what programmers call a loop does something multiple times unfortunately this is an example of an infinite Loop which you might not necessarily have seen the source code for but you've probably experienced on Mac OS if you get the spinning beach ball or in Windows if you similarly get that annoying icon that's just kind of whirling around and nothing's ever happening or your machine's just grinding to a halt and yet it seems to be doing something it's just your hands are off you don't know what it's doing it might just be because someone hopefully didn't do something as inan as this right really a stupid mistake here but there are ways to create the same effect by not anticipating maybe what the values are going to be that you might be comparing in your code because as we'll see in a moment you don't have to hardcode numbers like two and three into programs you can use things called variables like in algebra X and Y and Z that might actually have changing values as you're for instance if you're implementing a game and it's a little like a shooting game or whatnot you might have a score that would be an example of a variable that's going to increase and increase and increase over time so certainly can you imagine numbers changing inside of a program as that program runs but let's see what happens here let's recompile hello. C and now let's rerun a.out and unfortunately this program will never ever ever stop unless the power goes out I pull the plug or you know reboot forcibly this computer but just to now this is kind of silly here but suppose I wanted to actually do some arithmetic we'll see this in scratch in a moment to I'm going to declare and this syntax is a little weird in C I want an integer just a number I'm going to call that integer X like I learned in algebra class although I can use any word I want and I'm going to initialize it set it to the default value of zero and then you know what I'm going to do I'm going to do this silly thing here while uh let's do while X is greater than well actually let's do this let's set it equal to one while X is greater than zero go ahead and do the following print something but then you know what after you print something increment the value of x x gets x + 1 so if you think through this logically odds are you've never programmed in C but even with these basic building blocks you can imagine we've declared what's called a variable set it to one I'm then saying while X is greater than zero do the following what should I do print AOW then increment one increment X by one and then do what what's that it would go back around then the program would end right because you printed at one time now equal well careful now now X is equal to 2 right cuz x = x + 1 so x = 1 + 1 so that's two so two is still greater than zero so I print a low again then what do I do to X add one so now X is three is is three greater than zero of course now we do it again and again and again so now and actually let's not print out X let's actually in this syntax is just a little weird let's print out out now let's not print hello let's print the value of x and I'm going to wave my hand at how I'm doing this but percent d means put a digit here put a number here a decimal number so now I'm going to go ahead and rerun GCC and I'm going to oh boy here we go that's how fast this particular computer can count so the difference between what you did originally hello one time and then you did it again it kept going over and over again that was because um two two three is always two is always greater whatever the two is always L three correct so you were doing that that's why it kept going over and over kep continuing exactly and now in this case I changed that I ripped out the stupidity of two less than three because that's obviously always the case and this time I put a variable while X is greater than one but the problem is because I just keep adding to X and I never subtract from it well surely X is going to be equal than zero and so we're again going to keep looping ad nauseum here as the computer counts up and up and up and up and up until maybe something bad will happen now this is an intentionally erroneous example this is showing you what can happen if somebody uh types in something that's bad or types in something that's wrong and and this is again a very simple uh idea uh that or it's very simple error that that David intentionally put into this this source code but you can you can get an idea that okay well if we have a million lines of code it would might be relatively easy to have one mistake like this that can cause some sort of a crash that can cause its own sort of infinite Loop that would cause all these sorts of problems that you might associate uh with your particular computer but it refers to and at least it alludes to a uh a concept that's a bit more abstract that's really important to be able to understand when we're talking about programming and that is this idea of algorithms and an algorithm is basically just a a sequence of steps it's just a a set fixed number of steps that can accomplish some task so let's say I am a dumb computer and I am given a phone book and what I need to do is find a person's name within this phone book what is an algorithm in just plain English you don't have to tell me in in source code or anything like that in just plain English what's an algorithm that I can use to guarantee that I will find a name or that name within that phone book yeah start the first one keep going the right very good so open the book to the very first page start looking at each name and go from you know the very first name AA to the very last name until we find the name that we want and that is an example of an algorithm but it's important to note that you you can usually skin cat many different ways right there's usually more than one algorithm that will accomplish the same goal and sometimes different algorithms might be more efficient than others some algorithms might be more error prone than others and this is really where the programming aspect becomes very very interesting it's it's trying to figure out trying to come up with an algorithm that you can express in a programming language that can accomplish some task and doing it the most efficient way possible and the least error prone way possible so that that way you will have fast code fast efficient code that will run that will accomplish the task that you want without crashing or without any sort of problems and uh so if we wanted to say a faster version of this same of the same algorithm of the same task is there something that we can do that will make this a lot faster yeah open the phone book The midle find um if the guy's name is B it would be the front half or his name is C the back half so you eliminate half of it then you keep doing that right very good so now instead of just going through every name individually one at a time which is a very valid way to do it but if we have a billion names in this very large phone book it and it takes us one second to look at a name compare to the name that we are that we're trying to find you can imagine now it can take up to a billion seconds to find the name if it's like the very last one so what we could do instead is try to have the number of names that we actually have to find so instead instead of starting at the very first page of the phone book for example let's say we open it at just in the middle and then we compare we look and we're probably somewhere in the M's or the NS and we say okay the name that we're looking for starts with a B is a b less than an M or is it more than and if it's less than then we can just throw away the complete latter half of that phone book we don't need to look at that because we know because it's in order that that b the name that starts with a B is not going to be in that latter half and so then we now have a set of a set of names or this phone book that's now half as large it's now 500 million names instead of a billion names and we can do the same thing we can again open it in half at the very very middle and say okay well where are we going to be now uh like f for or something like that okay is B less than F or is B more is B greater than F and then we can then again throw away half the phone book and so doing it this way this is actually much more efficient we can actually perform this same task in probably only about 20 steps for any name in the phone book out of a possible 100 or out of a possible billion names so this is much much faster and it's not error prone still and so it's just a much more efficient way it's just a much more efficient algorithm to be able to accomplish this same task so let's try to use not so much technical jargon but just useful jargon with which we can talk about programs now in any language and we already tossed out a couple of keywords loops and variables let's see if we can't now use this framework this example silly example from like what you might have done this morning to tease some of these Concepts apart so here's an algorithm again an algorithm is a procedure it's a set of instructions that somehow tells a computer or maybe a robot or maybe sort of a slow human what to do you have to be terribly clear and terribly precise with them now we've chosen this program specifically so that you can see an example but in English or in an english-like syntax some of these important ideas without the silly distractions of the semicolons and all that other syntax so here's an algorithm procedure for putting on your socks in the morning and we've numbered each of the steps and we put forth for consideration that this algorithm takes maybe a 17 steps this is not a perfect algorithm and that's also intentional but let's see if we can tease apart how this thing would run so in step one even though it's now in kind of this broken English like syntax what is step one and example of using tonight's jargon thus far what would you describe the thing going on in step one as yeah setting a variable yeah so setting a variable now I didn't use X and Y and Z which we were taught to use in algebra but rather I used an actual word or word with some underscores just because in programming especially if you start writing hundreds of lines of code thousands millions of lines of code if your programs are filled with x's and y's and Z's honestly what the heck do they mean in various different context so the nice thing about real programming languages and things like scratch is that you can actually give words or short phrases to your variables to just help you the human or other humans who might inherit your program and have to maintain it in the future uh keywords with which to that describe those variables so in step one we're defining some variable called socks on feet and initializing to the number zero and this should make sense unless you sleep in your socks that when you wake up in the morning you have zero socks on your feet and so thus begins our program now step two by contrast is an example of what other construct we've talked about thus far this is a loop so it's a cycle something that might indu the same behavior again and again and rather than use the silliness of curly braces which a lot of languages use we instead took the approach that actually python another language uses of just indentation because it's kind of clear to the reader that everything below step two seems seems to somehow be related to step two because it's all indented underneath it it's just some kind of hierarchy and we've seen this in what other language HTML right it wasn't required in HTML it was just us being anal last week but we did argue that humans can read it better if you nicely indent everything so that there's this nesting same deal here so step three open sock drawer that's a statement it's an instruction now it's a real world instruction but it's analogous to things like print that we've looked at thus far step four is another statement look for sock whatever that means and here's where you can start to push back on us frankly what does it mean to look for a sock if we were really being precise here we would have to tell the computer or imagine the robot exactly how to find a uh sock now step but we skip that we're waving our hands because we don't want a thousand line program just to discuss some some simple ideas so step uh five is an example of what haven't used this term just yet yeah if statement so it's an if statement or a condition or a branch or in the real world if you prefer a fork in the road you check whether or not something is true or false just like before with loops check if something is less than or greater than something else but it's a decision point and you either go this way conceptually or you maybe go this way or in some cases you could go in any number of directions totally depends on the program but in this case the computer is asking itself if you f or in this case we're asking the human if you find a sock then do what it looks like what we should do is everything from line six through line 15 because notice that's how the indentation lines up so if you just look straight down everything below step five is indented from line six to line 15 so just to make sure you're following along so what do we do if we find a sock we put it on then we increment our variable Plus+ is shorthand notation for increment this by one add one to it so now zero becomes one then look for other matching sock then oh an interesting construct another if another decision Point that's inside side of another totally legit it's because we're doing two things conditionally now if I find a matching sock then what do I do put it on then okay careful increment socks on feet by one and then finally close the drawer do I do Step 13 14 or 15 so no because again per this concept of a fork in the road either if something's true do this else do that so I should not do those additional steps and keep that in mind cuz we'll see if very similar construct in scratch in a moment and how about line 16 and 17 do I do those now so no those were part of the first fork in the road so those are also inapplicable now per the indentation what line should I be going back to next to check two right because that's how I got in here we started with step two and I said while socks on feet and I didn't I should have pointed that this out before because there's no not equal sign on a typical keyboard there is an exclamation point as one character on the keyboard and there there is an equal sign so the human convention to say not equal tends to be exclamation point which just means do the opposite of the following character equals is the second character so that meant not equals so now I've gone through this Loop once how many socks do I have on my feet at this point in our particular story two so I ask myself the question again while socks on feet is not equal to two well are is socks on feet equal to two it is so where do I go in my program that's kind of it I seem to be done put another way is socks on feet not equal to two at this point in the story actually I don't like phrasing it like that that confuses me we have two socks on our feet at this point in the story so when asked while socks on feet not equal to two do the following well clearly that doesn't apply because socks on feet does in fact equal two and so implicitly and this is where we just waved our hands because it's going to get boring quickly you're done with the program because there is no step 18 but this program is imperfect where can it go wrong are there any errors in this particular algorithm yes ass laundry and laundry doesn't rep you get okay that's a good point so if you do laundry let's say you own zero socks and you uh look in the sock drawer you don't find any socks or something like that and you just are you try to do laundry but you don't have any socks in your laundry bin and so you wash your clothes and you don't actually replenish your sock drawer then yes you could get a uh a problem with that you could get an infinite Loop because then in this particular case well this is not being replenished however we do explicitly state that we are replenishing the sock drawer so let's just assume for a moment that that is actually going to uh happen successfully are there other problems that could cause some sort of failure in this algorithm any ideas yes what if socks are already paired what if socks are already paired what do you mean M are paired I mean I'm never looking for one sock as I I'm always putting a pair in well this doesn't handle the case of hairs I would say um but well we can give you a different algorithm after you or someone else has done your laundry how do they get magically into these pairs simil so we can push back on that right at some point the matching had to happen but fair there's some real world issues here I mean still it it still might sort of work because you can find a pair and you would be able to find one sock within that pair you could take that one sock out and then the rest of the of the algorithm would still apply so still it's possible that depending on the interpretation of some of the English statements in this in this case that we could still make it work in that particular case but uh so but that is an interesting and good point point but is there anything else yes isn't it kind of undoing the first it's like saying take if you don't find then take off the first oh that's an interesting point yes so it's right so let's see if you find a matching sock then so let's see uh okay so no so what this is saying this is actually saying that so what you want to do is you want to actually remove the first sock because then what you will do is you will take off uh so you put on one sock then you look for a matching sock for that you just pick a um you pick up a sock if that if that matching sock uh let's see doesn't exist then you remove the first sock and then you put on another one y so do you put that on the sock without any matches back in the drawer I think sort of critical here yes so no these are all these are all very good points and what you're doing is you're thinking very critically about these statements you're trying to remove the ambiguity of these statements and so that is a very good point one sock in the dra and you put the after fa match you're that's that's the one so you have no matching sock if you have if you have a horrible accident and suddenly your stock drawer or your stock reserve your stock pile so to speak only has one sock within it then you will have a problem in this particular case because yes only if you put the sock back well no I mean even if you don't even if you just set it aside then you still have the same sort of problem because right but then you don't have any so sucks and so it just goes back yes but this is this is actually the failure so if you interpret it and and say that okay when you remove the first sock from foot you actually putting it back then yes you will get this this infinite Loop problem that we are that we were talking about this is why I handed this part of the class off to you usually what you're lucky that we don't we didn't actually uh ask one of you to um come up here and demonstrate this algorithm for us is there a question I just wondered once you get do you actually get back up with the clean laundry and start over yes so this statement 17 says to do laundry and replenish sock drawers so it this algorithm Waits until this statement is complete so after so if it takes you an hour two hours to do your laundry and then it and then to replenish your sock drawer it as soon as that is done then it goes up to the very top this while uh socks on foot uh socks on feet do not does not not equal two so right so as long as it equals zero or as long as it equals one even it will keep trying or you know if for some reason you have 3 fet now then it will the same thing will will happen yes so this algorithm does not um this algorithm assumes that you have two feet exactly two feet could you just put two STS on one foot yes you that is another um failure in this algorithm you're not explicitly stating which you really should have prepared better you should have written a better algorithm I did write this slide yes and so we don't explicitly state which sock or which foot to put the matching sock on so it's possible that you could have um both socks on one foot and zero socks on the other foot okay enough about socks I think yeah so uh we need someone to come up here and do a little play a little game for just a moment you have to be comfortable on camera needless to say but is there anyone who would like to come up here and play a game for about 30 seconds come on down all right so what I'm going to do is oh and this program is still running we'll come back to that later so we are about to introduce a program called scratch if you go in the future to scratch.mit.edu as you'll likely Do For an upcoming assignment and give me just one second you'll see a website like this uh scratch long story short is a graphical programming language again it was implemented down the road by mit's media lab and it's actually targeted at uh grade school or middle school children to use an after school um community centers and to actually engage them in something intellectually interesting and fun on computers but we've actually been using it for some time at Harvard College and in the extension school and other universities have started to do this as well as a language with which to introd ruce programming so what you will do in uh over the next week or two is go to scratch.mit.edu and we'll put all the instructions in an email for you on the wiki as well uh you'll download the software and that will allow you on your Mac or your PC to have this program called scratch install it's completely free and once you download it you will have an icon on your desktop or similar for this program called scratch and when you open it up and this is what we'll have you play with in just a moment is a screen like there it is already running you'll see this interface here and the nice thing about scratch is that it actually doesn't take all that long to explain it CU frankly it's targeted at young children so you really can't expect the learning T to be very high which is nice because we ourselves can dive in and start doing really interesting really fun things quickly so a few uh definitions of what you're seeing here so that guy up there at top right is scratch he's a cat but you can make him look like anything you want and he's what is called a Sprite or a computer character and you can have multiple Sprites and these are characters in whatever it is we're about to make we might make a game we might make something artistic we might make uh some kind of Animation but anything you want moving around on the screen or doing something interesting is called the Sprite and the default one you get for free out of the box happens to look like a cat now the thing uh that the scratch uh Sprite is on top of the big white square is What's called the stage so that is his little world up down left right diagonally that is the stage on which this Sprite can move on the bottom right we'll see all of the Sprites we've created at this moment we just have one such Sprite that's why we have this guy here in the leftand side though is where things start to get interesting these are the puzzle pieces we alluded to earlier or the building blocks literally of a particular computer program and what you'll do in just a moment uh or and what we'll we'll do as a class in a moment is start dragging and dropping those puzzle pieces much like a moment ago I was typing stupid things like p r i n TF for print F we're simply going to going to drag and drop the equivalent here when I typed whh i l e for while I'm just going to drag the puzzle piece that happens to represent the loop in just a moment and in the middle is where I'm going to actually drag all of those puzzle pieces to and where I'm going to write my scripts AKA programs now to wet your appetite what I thought we would do though is open up this particular one which was actually made by a former student and let me go ahead and I double clicked the wrong icon uh do you want to come on down for your game playing exercise just to give you a sense that though this might actually be targeted at Young demographic you can actually do really neat fun things with it oh come on so I'm going to make this full screen by clicking the appropriate icon and the instructions here are right here on the screen for you in a moment I'm going to go ahead and click the green flag notice at top right there's two signals green flag means go red button means stop so I'm going to click go and then you're going to play the equivalent of DDR for those familiar the game where you move your feet quickly and have to interact you're going to use the arrow keys instead so there are your definitions I'm going to click the green flag and as soon as you're ready can you crank up the volume go ahead and hit the space bar when you're ready probably going have to switch the audio over to your I did it'll start in a sec [Music] left and now as he hits the arrow key in lock step with the animation notice that the numbers at the top the so-called variables are actually being [Music] incremented and now think for yourself even though we've just begun talking about programming how would you implement some of these ideas clearly things are happening again again and again and again if you're watching closely they're happening faster and faster so somewhere there's a variable that's actually controlling the speed of all of this so we have loops somewhere we have multiple Sprites multiple programs that's just hard multiple [Music] variables we'll give you a few more seconds at it come up on the chorus one more [Music] time but you've all probably seen at least various arcade games that might be as relatively simple as this the basic building blocks that we've already covered tonight are really what compose those programs yeah it's out of control now all right big round of applause so before I hand scratch off to Dan let's now not start with maybe one of the more impressive things you can do let's take a step back just how do you do something like below and how do we begin manipulating this interface well I'm going to go ahead and just create a new file for myself which will close off this particular scratch project or program as it's called and now I just want to have the cat say hello just like I did more esoterically by typing commands before so notice at the top left here above all of the available uh puzzle pieces or blocks there are different categories of blocks and nicely enough they're all colorcoded that's consistent with their type of logic Loops are all one color statements are all another color variables are a third color so notice this guy is pretty much the equivalent of that keyword we used before called main which was the main part of my program this is kind of the same thing as main because it's saying literally when the green flag is clicked dot dot dot do something just like the main keyword did before well what do I want to do well it turns out under the looks category and you know the first time I used this I didn't know where the heck it was I just poked around clicking around the categories and oh there it is say hello for 2 seconds so I'm going to drag this and now notice as it gets close to the existing puzzle piece notice the line appears that means hey this will snap into place here if I let go so here I go letting go and it snaps together fitting together much like a puzzle piece so what's nice now is done no semicolons no indentation no stupidity honestly just the idea that I'm trying to communicate to the interface and so if I now go over here and click the green flag and I'm not going to bother filling the screen this time because it's not interesting enough here we go green flag click there it is sorry my Mac's a little slow there it is let's do it again to prove that it did actually work I think frankly the reason it's being slow is because I'm doing this in the background so let's just minimize that but I want to see how high we can get so green flag there we go hello all right let's take a five minute break when we come back we will make our own DDR or with the building blocks at least all right as Dan would say Hello everybody welcome back yeah that's right so I smelled something burning during break and I got a little suspicious after scratch being slow so I pulled up that thing called activity monitor and what strikes you about the top of this list terminal crank yeah so that infinite Loop is not such a good thing and so literally this machine this magc is getting hot to the touch because it is so operating at full duty cycle really churning away cons the entirety of my CPU of course to the detriment of scratch so I'm going to fix this while Dan drives us with his own version of scratch on his machine all right so switch me over all right here we go so scratch has a lot of these same components or these same building blocks that we saw in the first hour so these statements for example these these statements are a way that we can actually do something so what we saw before was a statement that said hello and that was the point of the statement there's a variety of statements that are available to us so we can actually do something like we can print out some text using this say statement we might be able to wait a certain number of seconds so we can actually pause the operation of this program for a certain number of seconds with a separate statement or we can even do some really fancy stuff like playing sounds for example we could import some sound files into scratch and be able to play them uh whenever we want we and doing it at a specific time requires a little bit more complexity but you can imagine that if we just have some of these statements we would then be able to do something with them so how can we actually Implement some of these um well we have this um just very basic program if recall we have the the the very beginning block that says when flag is clicked we say oh high world and then we can when we hit run it will actually say oh high world now what we might want to do is actually combine a number of statements together so that we have not just a very very simple program but that we can accomplish something that's a bit more interesting so maybe not quite yet to that complexity of the the DDR like game that we saw just a minute ago but maybe we want to do something a little bit more interesting like uh we want to wait a certain amount of time um let's see where is wait in here there it is we want to wait a second then we are going to say something else and then maybe we will wait another second and then maybe we will say one more thing and I will just change the text so that we can see how this actually changes all right so now we have this program and so what's important to realize about scratch is that you're building these these statements one on top of the other and just like with the a program that you write in a programming language the computer interprets it starting from the top and just goes one at a time it starts from the top and it just goes from top down so it doesn't necessarily or or it never unless you tell it to goes out of order so it's not going to skip from the beginning to the middle in in for any reason whatsoever with this program it's going to go it's going to uh when we click the green flag it's going to say oh high world it's going to wait a second then it's going to say hello then it's going to wait another second and then it's going to say hello again so just to prove that this can happen uh we will run it okay so it says Ohio world for 1 second then it um all right it did it faster than I can say it but you saw what happened it said exactly what I said it would do okay now um these it's it's important to realize also that all of these statements and well the say statement is relatively easy to replicate in all of these other programming languages so you saw for example the C example the Java example the PHP example and and frankly it's even though it was a little bit cryptic it's not all that difficult to get it to say or to get it to print out something so if you just copy and pasted the source code that we showed you you would then be able to relatively easily get it to print out additional things just by copying and pasting that one line of code that said hello altering the text as you wanted or doing doing what have you whatever you want with that particular text but other things that we can do in scratch are just a lot more difficult to do so this is sort of where um scratch really shows its power so a lot of this animation showing Graphics playing Sounds playing playing different things um is very easy to do in scratch but you might get a little bit disillusioned if you're playing with scratch you do this really amazing really awesome program and you try to do the same thing in one of these other programming languages you'll find that it becomes much more difficult to in order to play a sound in C for example it's just going to be a lot more complicated than it will in scratch and so it's just important to realize that with scratch you can do a lot of these things very very easily you can create these statements or well you can you have all of these statements available to you that do these really nice really fancy things like movement animation sounds Etc and it's just complicated to do most of these things except for these these very basic building blocks these programming like building blocks that we've been showing you if statements Loops Etc um it's it's difficult to replicate that in a separate programming language altogether all right so my CPU is back down to like 0% so I can be useful again uh let me grab my own point in the PDF here and let's add some some zaz now to this so we only did the equivalent of print thus far but it turns out as we saw with the example Ian played a moment ago that you can have sounds too so let's see if we can't really leverage the idea or exploit the idea that this thing is a cat here so on the left hand side we have a recreation pictorially of what Dan just did and on the right hand side just in English words what's this thing going to do if I run the program on the right hand side now play sounds all right so it's going to play sounds it's going to do the same kind of thing but this time audibly so let me go ahead and load up a new project I'm just going to reload scratch and I'm getting a little more comfortable with it so I'm just going to start from scratch no pun intended and go when green flag clicked and then I'm going to go let's see sound all right so there's a lot going on here but I'm just going to go with the first thing I see top left it says play sound meow and so notice here too Dan typed in words like hello and hello again those were what we called arguments or parameters when I was typing at the keyboard before for printf remember print F takes something and quotes in between the parentheses that was an argument same deal here sometimes scratch presents you with arguments uh with dropdowns instead of with text but this is because I could really get crazy here and record my own sound so you can actually start to have fun with this uh so I'm going to go ahead and just say one sound once first so let's see if I have my speakers up loud enough we'll hear it all right so we're on our way now that's just one meow let's see if I can't now augment it like DED with let's wait for uh 2 seconds and now let's go back to sound and let me go ahead and play the same meow again and then let me do two more seconds of waiting and then one last time will I actually meow all right so now let me go ahead and hit play [Music] all right so it's kind of cute but you can immediately see this is a bad road to start going down if I want it to meow again and again I'm already kind of starting to do the equivalent of what yeah copy paste right which I did at the keyboard before this could very easily degrade into a stupid looking program where I just copy and paste ad nauseum and then that's aesthetically ugly but what else is bad about this approach that I might take on first instinct of just copying and pasting previous blocks again and again and again why could that be a bad thing in the long run yeah you want to change have do again yeah exactly if I want to change the sound maybe change it from a meow to like a woof woof or something I record with my own voice I have to then change every darn block and if nothing else that's tedious for the human and programming is not actually supposed to be tedious it should actually be fun and interesting and so having things easily updated is a very compelling reason to do things in a more intelligent way so you know what I'm going to actually go back to the control construct here scroll down and you know what let me just click and drag so you can break these puzzle pieces apart even after you've been working on them notice this scratch doesn't quite call it the same thing as some of these more modern or more traditional languages so scratch is a real programming language but it definitely does something differently Vis of these but there is a forever block now you might think on first glance wow I can barely fit one meow inside of that block but what's nice about scratch is that these puzzle pieces will remain the same shapes overall but they'll expand to fill as as many pieces as you want to cram inside of the loop and here too is is is a nice detail the forever block is intentionally kind of horseshoe shaped much like the idea we've been trying to convey with parentheses or curly braces that open and close or just the indentation we used with our socks example so I'm going to go ahead and rip this apart and I'm just going to grab a play sound meow right in there and you know what wait I seem to have consumed the space but if I drag now my weight block I got to move them farther away so actually unstick notice that if I hover close enough it'll start to want to go in there and if I Let Go sure enough it will expand to fit the puzzle piece so now let me zoom out and hit play now and let's see what [Music] happens your turn okay now I have 2 seconds to be able to talk to you about the next thing that I actually want to say and that is is oh my gosh this is okay so if I actually want to be able to do something a little bit more interesting so maybe I want to actually have this fork in the road for example so yes we can Loop these things forever and ever and ever and ever but that's going to get annoying and repetitive very very quickly there might actually be cases where this is actually very useful very interesting for our program but playing a meow sound over and over and over it's not probably the best use of of doing this so maybe what we want to do is have some sort of control flow or having a way of of altering the direction of a particular program and so we saw how we could do this with the algorithm the socks algorithm before using those if statements so if something is true then we'll accomplish some some task or we'll accomplish some statements else if it's not true then we'll do something else and so this exact conditional statement this exact construct is available to us in scratch so just to show you an overview just of what we're about to do take a look at this program what does it say just read it out loud what does it say so when flag is clicked if one is less than two then play sound meow that's exactly ah so will this be an infinite Loop no that's right why not you have to collect that right so it is not an infinite Loop because there is no Loop in this case so it is just the conditional statement so if one is less than two it will play the sound meow and then that's it there's no subsequent step and because there's no Loop it doesn't go back up to the beginning to apply this same logic to apply the same Boolean logic as it's called it doesn't perform that test again it just ends if one is less than two it plays the sound meow and then that's it so let's just show that this works oh okay well it was now much quieter so one is less than two so in this case it plays it and then it stops it's done but how are we able to accomplish this so realize that if we have or if we are adding a so-called conditional statement and realize that all of these statements are available to us under the the control section within scratch if we want to accomplish one of these we can just drag the if block to the appropriate place where we want it and notice that there's nothing in it yet so there is this there's still this empty area right within the block where we can fit statements and in this case in this example we had the play sound meow statement but there's another empty block as well this little trapezoidal something diamond shaped I don't know what geometry was so long ago this little this little shape that allows us to put in Boolean statements that we can combine in multiple ways to be able to perform this this well in this case relatively trivial asking you know this relatively trivial question that the computer will be able to answer for us so in this case notice the third this third block from the top is that green less than and the shape of this block implies that it can fit within that that same shape in this if statement and so we can then just find this particular block drag it into the if statement and then apply whatever values we want within it so in this case you notice that again it's colorcoded so we can go to operators and we have a variety of operators available to us so it starts out with some pretty basic operators plus minus times divide but those aren't the right shape and it doesn't make a lot of sense logically either to be able to fit one of those if 2+ 2 what does that even mean that doesn't make any sense but it we could do something with that but just not right now what we need to fit inside of this if block is a so-called Boolean statement it is a statement that that actually performs a Boolean comparison to the end result of which should either be true or false if it's equal to anything else it doesn't make sense right if something is true then you do something otherwise something else there's no sort of ambiguity allowed in this case so we have to look at the statements that will answer that specific question is something less than something else that is that this an example of this Boolean statement is something equal to something else is something greater than something else all of these are Boolean statements that we can use with within this if block so I can just drag it in here and then I can literally type in some values inside of this this Boolean statement if one is less than two then I would be able to put in some statements whatever statements I wanted to be able if this statement was true then it would run those particular statements for us but here too we have a contrived example what if we actually want some dynamism well if you don't mind my steering here for a second Dan pointed out that not all of these Greenock blocks are the same shape in fact there's this guy here it turns out that even though computers only do what you tell them to do they can kind of do things a little randomly now they're actually using some fairly fancy mathematics to create the illusion of Randomness because at the end of the day a computer can only do things you tell it to do and you can't it can't do vague things like H give me a number off the top of your head like what does that even mean but the world has figured out ways mathematically to approximate that and even scratch has as well so if instead of putting in the number one and two arbitrarily let me go ahead and instead clear these to back to blank drag this guy here and so now notice that the condition says if pick a number from 1 to 10 is less than something well let me be a little clever here and I'm going to actually pick the value let's say six because what percent of the time will the number the computer pick assuming it's actually choosing random numbers be less than six yeah so half of the time so this is a way of expressing half of the time do the following or put more casually flip a coin and if it comes up heads or it comes up Tails do the following well what do we want it to do well maybe we want it to play a sound like before so let me go ahead and choose play sound meow although you know what let's actually introduce one other feature this is more of a fun feature than an intellectually interesting one but it's how you can really start to dive in and get carried away instead of doing meow here what I'm going to do is not record because I really don't want to embarrass myself but click on sounds so notice we have scripts by default costumes which is what the Sprites look like and then sounds and notice I can click import or record if you have a mic but import and then what's nice about scratch when you download and install it from mit's website comes with a lot of uh example projects a lot of example sounds a lot of example costumes and you can really get carried away if I go here into the uh let's say animal folder there's a cat uh if I go down the list can you can you raise your Vol there some crickets oh that got the the the immediate most immediate laugh so let's go with the duck sound now notice I have two sounds in my little pallet here so if I go back to scripts now and play not sound meow but duck we're going to have a pretty weird looking sounding cat but I'm going to hit the green flag now H wait a minute nothing happened why yeah it must have been six or seven or eight or nine or 10 and not one to five let's try again then uhoh coin came up heads again ah there we go let's do it again oh that's pretty good Randomness 50/50 so far no no okay so it feels like it's a coin toss and that in fact it is and so Randomness is actually a big part of computer programs even if you think of the simplest games games would be pretty darn boring if every time things happened in precisely the same way that was actually the way things were you know years ago and even now if you play Super Mario Brothers from the original Nintendo the reason people can win it incredibly fast is because everything is predictable there wasn't really all that much Randomness certainly not when you first start the game but here is the basic building block just doing something simple like simulating a coin toss can you actually have your programs behave in interesting ways are you not allowed to have like um the equal greater to or equal uh good question so scratch does not have the greater than or equal to block they just decided eh just add one number to the other side and you can approximate that but you do have that typically in more traditional languages good good observation there's no less than or equals to sign or the opposite other questions well so that for that reason it hopefully is it should be apparent why this works at 50/50 probability rather than say 60/40 and the reason is that it literally means less than six and that includes the numbers 1 2 3 4 and 5 which is half of this random block of 1 to 10 and so if it was less than or equal to 6 then yes it would be 60% probability that we would play this duck sound but because we don't have that particular capability we have to use um the this this less than sign and it is therefore 50% so now recall from our socks example that we were able to have an if condition a branch and then in inside of that so to speak was another Branch if we actually found the sock then also do this thing well we can actually achieve a similar result using most any of these languages including scratch so just like in our english-like syntax and incidentally the socks example if you hear this term again was called pseudo code it's kind of code but it's not really it's mostly English it's just our fake David and Dan language that we use it's called pseudo code you can still do the same kinds of things in scratch so if you wanted to have a fork in the road that either goes this way or that way you don't just use the if condition which pretty much says either go this way or go nowhere like Dan just did with his example or you can have this other two DEC two uh two-pronged Fork if something do this else do that now if you want to have three directions well it'll eventually get to be a little weird looking but you can certainly Nest these structures and conceptually it becomes if else if else and that in fact would be a three-way decision point and mutually exclusive if you think through the logic of a an expression like this if else if else that means you're only going to go in one of those directions not two or three optionally it's only going to be one of them so we can actually take advantage of other features of scratch now rather than only interact with like mathematics like random number generators we can interact with the user as well so I'm going to go into a folder of examples here this is version six of our high example and incidentally if we've not said it before this way of spelling high hii is just Aid stupid internet ISM that is maybe falling out of disuse we should probably get rid of this next year um let's see if we can't now make use of some of these uh additional uh features of scratch so right now just to be clear we have an example like that before it's just this meowing ad nauseum it's an infinite Loop but it's intentional you can imagine programs being uh having intentional Loops uh intentionally if infinite Loops intentionally if you actually want something to go on forever but this just quickly gets annoying but let's see if we can't have the cat meow only under certain circumstances now so let me open up this next variant and for time sake we came with some of these examples prefab so we don't have to manually do each and every one of them take a look at this guy in English what does this do just Define this program in a sentence when you put the M corner on the cat it's going to the perfect so when you put the mouse pointer on the cat or put more specifically if if you're touching the if the Sprite is touching the mouse pointer what do you do play the sound wait 2 seconds well let's see what happens I'm going to go ahead and hit the green flag nothing's happening though why okay right obviously I'm not touching the cat so if I move my mouse now oh and move away nothing so this is sort of our petting the cat example but now it's beginning to get a little more of an incarnation of a a real world problem how would you simulate petting a cat well you might do that well if we take things up a notch and use that nested construct here's another variant of this what's going to happen with this version of the cat petting cat's going to Roar when you touch it and it's just going to make noise good so this is the don't pet the cat example put another way so let me go ahead and play this and it'll make sense uh that definition in a moment cat's meiling away he's perfectly happy but then I move my cursor over to touch him and okay so not such a good idea all right so but there we have two decision points two forks in the road and just so you've seen it if you actually don't want your cat to look like that I'm going to very quickly go back to the costumes tab in the middle I'm going to click import and here's two where you can waste way too many minutes in the middle of the night picking some other appearance for your Sprite for instance we could make it look like a shark but still whoops but still meowing like a cat so you can start to do interesting things and these again are the basic building blocks that our own students um use to implement that DDR game she instead chose the Sprite to look not like a shark not like a cat but rather like an arrow pointing in One Direction and she used a loop that said move up and down so in fact we should probably do one example where at least the cat is moving okay want that to be to your charge uh well I was going to go in a separate Direction how about you did that real quick all right oops okay all right so let's actually make the shark let's say move so I'm going to go ahead and just get rid of this if you want to get rid of your scripts you can just drag it to the left let go and it disappears so now let's just make this Sharp dark move because surely we saw from the DDR example you can have movement so when the green flag is clicked what do I want to do well there's a motion tab we've not yet clicked but here too is where and this is intentional we're not going to walk you through every one of the blocks in scratch because it's very uninteresting but it's notice the richness of the what's there you can start playing around and if you can imagine a game or your interact your animation doing something the challenge the puzzle so to speak is really in figuring out how to wire these things together and that really is what programming is all about whether with puzzle pieces or with syntax like that before so let me go ahead and move 10 steps and run this program now okay not very interesting but if I run this program again and again all right I seem to have the illusion of Animation how do we fix this how do we make the thing Glide across the screen forever yeah so do that forever right maybe he'll hit the wall at some point but let's see as a first version of this forever do the following move 10 steps go ahead and click the green flag there he goes now he's gone now wait I can pull him back there he goes again and he's going pretty fast let me slow this down have him move one step at a time one step on each iteration thereby slowing the effect of this Loop and let me hit stop let me drag him manually over here whoops there we go and now click play so it's kind of a kind of a boring game but you know it occurs to me there are actually some other sensor blocks you can actually have multiple Sprites interacting with each other now I could do this manually if I play around you'll notice that if I click this link here this icon here rather I will get whoops um I will get a sort of Mac paint style thing where I can draw a new Sprite or I'm not very good at drawing certainly you can click this to choose a new sprite from a file that would give you an existing character much more effective but I'm going to skip those steps entirely and just go to something that I made in advance let me quit this and open up uh move to. SB SB is the file extension for Scratch and now I'm going to hit play you can actually have the Sprites interact with each other it seems that one Sprite in this case the cat is pointing perpetually toward the bird the game being cat and mouse okay so that was a little inappropriate perhaps but you can see now that you can start taking one Sprite figure out how do I get him to move around kind of randomly and once you have one you can add another Sprite and say all right how can I make this Sprite interact with the other and so a key takeaway when you tackle a scratch program for yourself for an upcoming homework assignment is you're not going to want to sit down and decide I am going to make DDR just like that other student where to begin you need to think about just in very real world terms what are the basic components of that program you don't have to know a priori how to implement DDR that game we played earlier with Ian but think about it all right I need an arrow to appear at the top left and you figure out how do I make a Sprite look like an arrow all right how do I position it at the top left there's a puzzle piece that says move set XY X being horizontal y being lat uh vertical set it to a specific coordinate if you think of the stage as a grid of pixels all right so that puts an arrow in one place now how do I make it move well we've seen there's a move block we've seen there's a Forever block surely I could figure out a way using these basic ideas of just making that arrow move down or move up depending on my goal in other words our student did not sit down and write DDR over the course of an hour just from start to finish she literally implemented little uh ba uh little building blocks or literally took baby steps toward the final picture and so that's important because it's very easy to get overwhelmed if you have a vision and have no idea where to start we just pluck off the easiest aspect of it to actually begin so in this case here notice that this is actually more sophisticated than most of the programs we've seen before but notice right now I have the cat highlighted the cat scripts are not all that long there's maybe 12 12 puzzle pieces there 12 lines of code if you will and if I click on the bird I'll see his scripts also it's pretty short so let's see it feels like it's the bird who's in control at first he's the one running around dictating the cat's Direction so let's zoom in on the bird how is he doing uh that so when the green flag is clicked there's a puzzle piece called go to and you specify X and Y and this was just trial and error if you didn't notice already when you move Sprites around by clicking and dragging them notice that in the bottom right hand corner you see the XY coordinates so it was there it goes again so I just trial and error to figure out where I wanted the guy to start and now if I look back at the bird let's zoom in all right point in a direction well if you recall the definition of a circle you have 0 degrees all the way around to 360 degrees so just trial and error I decided I like the angle 45 degrees that's how I want him to begin into this program but again completely arbitrary and now here's another type of loop that scratch supports but you can infer just from the English letters on it what it's doing forever if so this is kind of a special construct it's like a loop and a what combined it's a loop and a an if a condition a branch a fork in the road kind of merged into one and that's okay because if you just understand the concept on the blocks it kind of tells you what it is so do the following forever if you're not touching the cat now the point here was just to avoid a stupid mistake I might make if I have the cat and the mouse touching initially I don't want it to start moving I want it to just stay where it is why just because that's what I wanted it to do so this was there is not this is the other lesson to take away ultimately from this assignment if you want to accomplish some goal with a program there is probably an infinite number of ways you can do it now the downside is there's probably an infinite number of stupid ways to do it among them copy paste ad nauseum and but there's more than one smart way certainly to do these things so take comfort in that many different ways to do it intelligently what does the bird do well just forever he moves three steps that kind of speaks to his speed then if he's on the edge of the screen he bounces and this is a special scratch block so I don't have to figure out the angles or the mathematics just bounce off the edge and that's it that drives the entire Bird's behavior and now if I click on the cat let's see how I got to the point of this Chase game well when the green flag is clicked the cat starts at that location trial and error I just arbitrarily decided where I like the cat to start point in what direction well I did want this game to be a little little different each time I didn't want it to be completely boring for the audience so I said at least start the cat pointing in some R semi random Direction and then do the following forever if you're touching the bird we'll play that lion sound and then stop stop script else and now notice this is kind of an implicit else and here too is an example of doing things in different ways I could do an if else or I can just do an if and then put the else part after it because logically it's just going to flow from top to bottom else Point toward the bird and that is a special scratch block Point towards the bird move one step so notice the bird is moving uh ra the cat is moving faster or slower so a little slower but the idea is that even though the bird's moving three Paces the cats moving one eventually the cat will catch up because the bird again is just bouncing on the edge stupidly randomly whereas the cat is actually targeting his prey uh again and again and so the end result is this animation that's a little different each time but the end result eventually is that the cat will catch the M uh will catch the bird all right so all of these scripts so far have been relatively basic in terms of all of the the information that we've been using has been hardcoded so every time that we did an if statement or every time that we did this forever if statement we actually typed in these values except for this this random example but still it was this it's we explicitly told the um the program what values to use so you might might imagine that we want to add some additional complexity maybe we want to be able to uh have a counter of some kind so if we have a game maybe we might for example in this in this particular program maybe we might want to be able to record rather than just stopping the script we want to be able to record how many times the cat actually caught the bird and just allow it to keep going or maybe we are just accomplishing some some goal that uh a person has to be able to reach a certain number of of uh I don't know whatever it is in your game so like this DDR example for uh this DDR example where it actually counted how many of of each uh Arrow key was hit correctly so we would then need to use something that allows us to capture and retain this information be able to change it appropriately and scratch just like in these other programming languages and we just saw an example of it in that so that pseudo code in that example algorithm involving the socks scratch supports variables and a variable is just the it's just the named location it's just the place in memory that has a name that holds a certain value so we can find out what that value is just by referencing that particular name and so in this case we have created a variable called counter and at the very beginning what is that first line of code called so not the one that says when fly click but the one after that what is that we called it something earlier in the in the algorithm what is that called we're doing something yeah so we're initializing or we're setting the variable to some value we're just giving it an initial value otherwise if we don't do that we have no idea what counter would be equal to when we first start running this this program so we have to give it some initial value some known value uh so that we are sure that we give it some just something that we are aware of just so that there's no sort of ambiguity in this particular case so there's this variable that's called counter we're setting it equal to zero and then we have a loop and now what we're going to do is instead of just saying a word or a phrase we're going to use this counter to show us what this what this counter is now equal to and so we wait a second and then we do something we change that counter by one so we increment it's like that uh socks on feet plus plus line for example it just all it does is it just takes the value adds one to it and then now counter is equal to that that uh that that value that's been incremented by one so if we hit play we should then see what exactly happens so it starts at zero and then every second it increases by one so there is a counter there's a number somewhere in memory that's just increasing by one every second and then we are printing out this data and so while you may not want to do this uh unless you are unable to sleep and need to count sheep um what you can do is use use this variable to just make uh just to track some piece of information some numerical piece of information that will be very very useful and how do you do this well there's a special section within scratch called variables when you select that section you'll notice that we have not only a few statements that are available to us to allow us to modify or retrieve some of the the information from this variable but we can also do some like create a variable so you might imagine that there might be cases where we would want more than one variable maybe there's two uh states that you need to be able to maintain maybe you want more than one counter uh maybe you want to be able to keep track let's say you're making a soccer game for example and you want to be able to keep track of how many goals each team is making you don't want to have the same variable for both that's just stupid it's nobody's going to lose or nobody's going to win depending on how you look at it so you need to have one variable for each team to be able to determine who will be the winner of that particular match so to create a variable there's a little button here that says make a variable and it brings up a new window and this window you can give a variable a name now conceptually you might be able to figure out why you would not want to have two variables have the same name it's just not going to work the the computer is not going to be able to distinguish between the two and most likely it's and hopefully scratch will not allow us to actually create two variables that have the same name but what you might want to do is have two separate variables that are unique in some ways so maybe you want to be able to count the the uh Team One score and you want to be able to count team two score well you could just create a new name or a new variable um for that other one so in this case uh just counter two so the second counter in this particular case and your variable names should probably be a bit more descriptive but again this is just as an example of how you can actually create a variable now we could hit okay but there's one more option that we're given here here as well there is an option that says for all Sprites or for this Sprite only and so this um brings up this idea of of globalization or localization rather where this variable actually exists so for all Sprites means that this variable will behave pretty much like you expect all of the script so as in this example that David showed before we had two Sprites there was a bird and there was a cat and you could make it so that each uh Sprite had their own variables but uh that may or may not be appropriate for whatever it is that you are trying to accomplished instead what you might want to do is have what's called a global variable so a variable that's accessible by all of the scripts and in other words that means that if we have a counter two and we have multiple Sprites then all of those Sprites all of the scripts within those Sprites would be able to access this counter to and so this is the default for a good reason because this will behave like you would expect if you have multiple Sprites and you need to access that counter um then you will make sure that it this selection this for all Sprites or This Global variable is then created so I'll just accept the default for now and hit okay and then you'll notice that I have a list of of variables directly underneath these buttons counter and counter two and what I can do is then just modify this uh set counter to whatever to which whichever variable it is that I want to actually modify if I wanted to set both equal to zero then I would need to add an additional puzzle piece uh let's see move the forever Block Set counter two to zero and now I've initialized both of these variables to be equal to zero this case there would be two spres on scen second and one seconds so so no so in this case all we've done is we've just created a new variable because we haven't actually told the computer to create a second Sprite there is no other Sprite it's not actually going to say counter two it's not going to say both counter and counter two this is this should behave the same way that we saw before it's the sheep and it just says counter the reason for this is that we don't do anything with counter two currently we could add another spr and then we could also have another loop uh for that Sprite that increments this counter by one and then or maybe it it starts at a different number and it increments it by one or or decrements it by one it's just some other value other than this but until we actually do something with that other variable then nothing happens now you'll notice that um if you check these two boxes over here underneath the uh the make variable deleted variable if you this this lists the uh the the variables that you have and if you check them what scratch will do in this stage is actually show you the value of those two automatically and so we can get a better idea of what's happening if we just take a look at the value of counter 2 and counter we see that counter is incrementing your sheep example was very effective what I'll explain later okay so we have counter and counter two sleeping in the back [Laughter] oh all right that's not that's not very nice for you to point out on camera so we have now it's funny for everyone anyway so we have counter and counter two um and um we can see that counter two is actually not incrementing and the reason for this is that we're actually not changing it in this loop we're not doing anything with counter two so it's not going to be modified because we have explicitly told the computer to do something with it we've just set counter 2 equal to zero it's not actually going to modify that or display it we could change everything uh to counter two and then we would see sort of the opposite effect we would see counter two increment we would see counter two be printed out but then we would not see counter one change in any way so it turns out there's another type of variable that we saw toward the bottom of that set of blocks and it's called a list in scratch but in most programming languages it's called an AR or a vector or a length list comes in different forms all of which have slight differences but here is one example where you might not want an individual variable but a growing list of variables cuz that's the downside with a variable like X or Y or Z or counter it can only thus far store one piece of data like a number but what if you want to have a role playing game an RPG like this thing where this little blue guy starts walking around the screens and his purpose in life according to the instructions for this game is to pick up up the pieces of fruit notice at the top left the way the student implemented this game is they drag the variable that was of type list AKA array so what you're seeing in top left is just what Dan did with the counter but this time it's a growing sized variable if you will and this is useful so that it can collect all of these different things now how in the world does this work well I'm hitting the arrow keys up down left right and it turns out one of the PES one of the puzzle pieces under the sensing category is when such and such a key is pressed so you can actually listen for specific keys so that you can have yumian input for this game as well as for the dance dan Revolution game that Ian played before here too what does it mean to actually add something to your inventory well I'm the little blue guy when I get close enough to be touching the other Sprite the pineapple Sprite there must be a condition somewhere if touching pineapple do what add pineapple to your inventory so again the very basic building blocks and so realize too even though we're spending a good amount of time today talking about scratch and talking about this feature and that the end of the day it's all of those same fundamentals of loops and conditions and variables and statements and Boolean Expressions which are omnipresent in most all languages out there so do realize that these skills these concepts are absolutely transferable there's a few other topics that are worth keeping in mind especially as you ultimately play yourself with uh with scratch For an upcoming assignment one is just the idea of threads so we've talked about this in our Hardware lecture when you have CPUs multiple CPUs or multiple cores inside of CPUs recall that a computer can actually do two things at once because they are if programs are quote unquote multi-threaded a multi-threaded program is just something that can do multiple things at once so Microsoft Word can do this if you've ever wondered how it's able to do like the red underline when you have typos or the green underlines when you have uh grammatical errors that's because it can do at least three things at once it can listen for your keyboard commands so it actually puts words in your essay it can simultaneously be checking all of your words grammatically and it can simultaneously be checking all of your spelling uh while you type so in that sense is Microsoft's word an example of a multi-threaded program well scratch 2 is multi-threaded you can do multiple things at once case in point our little bird and cat game that program had two Sprites AKA two threads Each of which was acting simultaneously or in parallel to use a technical buzz word and so this is useful because you can actually have really interesting things going on on the screen simultaneously another example is this one uh so this is something I actually stole from a teaching assistant of mine years ago at MIT I replaced his face with mine just because I figured it would be more interesting and if I actually pick this one out you'll see that here too can you have multiple Sprites in this case three right glove left glove and then opponent or my face there if I actually blow this up and hit play what you'll notice is that if I move the up Arrow I'll start getting punched if I hit another key on the keyboard this guy goes and now notice what's happening to my face turns out there's a scratch puzzle piece that lets you control the color of a Sprite dynamically these are not different pictures this is just a little color wheel like Dan showed in Photoshop last week and if I keep there we go So eventually you actually go down but again the interesting question here here is not oh my God where uh how do I Implement that whole thing at once but rather how can I break it down into component pieces well there's a left glove and a right glove that apparently need to be able to respond to keyboard commands how do you do that well we've shown a few examples tonight not all of the source code but the neat thing about scratch coming with so many prefabbed examples is you can look at them one of them is as of a fish tank well how in the world did this kid make the fish tank well what you do is you open the project look at the Sprites and read through the logic the code the scripts if you will and you can infer and you can learn you can bootstrap yourself just like we preached last week with HTML so incredibly boring to review all the possible HTML commands but the reality is once you've seen it elsewhere in an example you can now apply it yourself here well what are some of the other designs another key feature that you might want to put tuck away in the back of your mind is something like this you can actually have two Sprites uh interact with each other not just by sensing by touching but also by talking in Compu in behind the scenes to other by sending what are called events from one Sprite to another so you can have one Sprite sort of whisper something to another Sprite and have the other Sprite listening for that whispered command so that one Sprite can influence the behavior of another and when I say whisper I don't mean show the word on the screen for the human I mean this is more of a backend underneath the hood kind of thing so that two Sprites can interact so here's an example involving a game you might have played in like the swimming pool Marco Polo where someone says Marco and then the the uh the the kid who's got his eyes closed says Marco then everyone else has to respond Polo and so that is one Sprite one human interacting with all these other humans by sending an event the event Marco and they're supposed to respond with Polo so here is an example of two Sprites boy and girl the boy's purpose in life is to do this when the green flag is clicked forever do the following if space bar pressed do what say Marco for 2 seconds and then do this other block broadcast quote unquote event and I Define the word event just to be consistent with the jargon I wanted to use tonight you can broadcast anything this does not mean show it in a cartoon bubble this means send a computer command to all other Sprites any one of which or more of which might be listening for it so on the flips side if we look at the girl Sprite now she does not have when green flag clicked it turns out under the control category there's other ways in which you can induce Sprites to start doing something one of them is when I receive dot dot dot well when I receive that event that back end underneath the hood command what does the girl do polo for two seconds so here we seem to have two threads two Sprites Each of which is operating simultaneously but waiting for one human input and the other for a message a broadcasted event as it's called from the other Sprite so the net effect is this if I zoom in on the screen hit the green flag nothing happens yet but if I hit exactly the space bar he says Marco behind the scenes she knows to say Polo if I hit the space bar again he says Marco she knows to say Polo 2 seconds later and so we do in fact have these two threads interacting and so if we put all of these building blocks together you can actually make a pretty neat uh program just like what uh David did when he had way way too much free time uh he made this um program that actually is timed to music and using all of these things that we've actually uh seen did you switch my sound over yeah I did I did um you can actually time these things so we can drop pieces of trash into Oscar's trash can and we have a counter that detects how many pieces of trash we've actually collected um and completely useless but really really neat really fun and and a great way of showing you how you can waste a lot of time with scratch developing some something that is actually really really neat and a lot of fun so go home tonight try it out it's a lot of fun and we will uh see you next week at the [Music] exam