[ROCK MUSIC] [MUSIC - "HAPPY TOGETHER" THE TURTLES] DAVID MALAN: Today, we begin our exploration of the fundamentals of computer science and our introduction, now, to the art of programming, of which that is just one example. But in the same vein of problem solving, know that CS50's traditional Puzzle Day is tomorrow. If you've not yet RSVPed for this event, you can go to cs50.net/rsvp. You can bring teams of two or three or four. You will be challenged with problems like the one you saw up there in the beginning. All new problems this year if you partook last year, and you will have a chance then to win some fabulous prizes. Among them, a Wii and some gift certificates and like, all while hanging out with CS50 students and classmates and pizza and Facebook. So more on that tomorrow if you would like. This then is CS50, for those of you joining us for the first time. And know that this course is particularly determined to get you through this course to its final end, at which point you will have not only an understanding of these fundamentals of computer science, but you will have this very practical skill set that you can then take back to your own department, whether it's engineering sciences, applied mathematics, the physical sciences, natural science, or the like. Indeed, what's so exciting about computer science these days is that it is just so applicable to all sorts of fields. And even though today, we will only scratch the surface of a very traditional programming language known as C, we'll instead look at something called Scratch, something with which that cookie love story was implemented by one of your predecessors in years past, to tell stories, to create games, to create interactive art, and to actually start to wrap our minds around some of the fundamental constructs that underlie programming but in a context, as you'll see, that's much less scary, that's much less arcane, than you will see before long. And realize, too, for those of you just joining us this semester, the phrases on which we ended Wednesday's lecture, it is not so important where you end up relative to your classmates in this class, but where you, by semester's end in week 11, end up relative to yourself right this very day. So without further ado, this is also worth noting that those less comfortable, those somewhere in between, are also, by design of this course, not at any disadvantage vis-a-vis those more comfortable coming into this class. As you'll see over the weeks to come, we have different tracks for disparate back background, sections for those less comfortable, more comfortable, those somewhere in between. As you'll see this weekend and next week, two versions of most problem sets in both standard and hacker edition so that you all can self-select down the path with which you are most comfortable. So today, we dive into this programming language called Scratch. It's a graphical programming language, and yet it has the same features of some of the higher level languages we'll explore later in the semester, among them C and JavaScript and PHP. But it's going to allow us to avoid some of the distractions early on of syntax, things like semicolons, parentheses, and other arcane details that, at first glance, are just not at all intellectually interesting and tend to get in the way from some fundamental understanding. In terms of now the support structure ahead, realized this tool, CS50 Discuss, which will be linked on the course's website later today, is the online discussion forum in which you'll be able to ask questions of each other and staff, and it's also a tool, as we'll see next week, that we'll use quite integratedly in office hours as well. Indeed, office hours begin on Monday, and frankly, the first week of office hours is fairly low key. I don't think you'll find Scratch all that inaccessible. It's rather self-explanatory, as we'll see, and so what we'll use it for today is to extract some of the fundamental ideas that will, then, persist throughout the rest of the semester. But starting Monday, at 8:00 PM through 11:00 PM will be office hours in Annenberg over brain break. Sectioning two will begin this evening, so sometime this weekend, go to cs50.net/section, and you'll be asked a number of questions. Among them, how would you describe your comfort level as of today? There's no hard, fast rule as to who's in which bucket. It's just the sort of thing that you probably know if you are among those the less comfortable or otherwise. And now, walkthroughs. The problem set specification for this week, both standard and hacker edition alike, is online at cs50.net as of now. And you'll see that the first of these editions, the standard edition each week, is accompanied by something we call a code walkthrough, a session led by one of the course's teaching fellows to guide you through, provide tips on, and get you down a particular path when it comes to starting these problem sets. So with each of these problem sets, if you're ever wanting for yourself where do I begin, you begin with these walkthroughs. And in fact, allow me to introduce Zamyla Chan, this year's teaching fellow who will be leading each and every one of these walkthroughs. Zamyla? [APPLAUSE] ZAMYLA CHAN: Oh, hi, everyone. My name is Zamyla. I'm a junior studying engineering in Winthrop House. But I try and fit in as many computer science courses as I can, which is why I'm really excited to be leading this year's walkthroughs. Walkthroughs, for me, were an essential part of my CS50 experience. During the walkthrough, for every p-set, we'll go through the problem set together, look over the problems, kind of divide them up into manageable bites. I'll give you tips, techniques, for getting through and getting started. I hope to see you all at the walkthroughs. If you can't make it in person, then please do tune in online. DAVID MALAN: Excellent. Thank you, Zamyla. So realize that walkthroughs are, indeed, on a Friday afternoon, but this is deliberately by design so that even if you'd rather not attend class on a Friday afternoon, the videos will be up all the more quickly over the weekend. So realize that cs50.net will be all of Zamyla's walkthroughs. And that there is today's date and time, 3:00 PM, Harberd Hall, 104. And some of the teaching fellows have also prepared some remarks for you in absentia to give you a bit of perspective as to what their experience coming into and going out of CS50 was like. So if we could dim the lights for just a moment, I give you some of CS50's staff. JACKSON STEINKAMP: I took CS50 last year as a freshman in the fall, and it absolutely blew my mind. I had never taken any programming classes before, and never came in with any computer science experience at all. And just, I heard the buzz about the class and decided to take it. JULIA MITELMAN: It was really fun, really engaging. I still, to this day-- I just recently saw I have the floppy disk that David gave us on our first day of lecture. I had hung it on my wall. This is probably a little nerdy, but I hung in on my wall during the class as a reminder of how cool it was. TRAVIS DOWNS: It's so embarrassing. JACKSON STEINKAMP: Computer science is something you should try even if you're not one for the traditional sciences. It's its own experience, and CS50 will make sure you're supported well through it with its veritable army of TFs. ALI NAHM: I took it as a freshman, and so I made a lot of new friends. I also got introduced to this entire concentration and entire school of engineering, and so I highly recommend it and welcome you to our CS50 family. YANIV YACOBY: CS50 just teaches you how to use tools that are widely accessible. You just need a laptop, you need a web browser, and you need to learn to write some code, and you can really build neat things. KAREN XIAO: It's just so cool to be able to make something and have people use it and have people see it, and that's what I really love about it. TIM MCLAUGHLIN: --a sense of community, I think, in this course more than any other course I've taken so far. You're not just taking another-- you're not filling another requirement. You're not just going to lectures and going to section. But you're doing tons of things that are all about programming and all about technology, but it doesn't really feel like a class most of the time. TRAVIS DOWNS: And on the first day, they handed out cake, and I was instantly sold. JACOB PRITT: Free candy and pizza. ZAMYLA CHAN: --regardless of your interest level, I think that CS50, you'll have fun, and you'll be intellectually stimulated. MARK GROZEN-SMITH: It's always a party in class, and it's a party every night working on your p-set. JACKSON STEINKAMP: Each time you finish a problem set, you will feel like you've finished a project. MELISSA NIU: It was freshman year, and I was done shopping. I had my four classes ready, and I was in Annenberg. And I bump into a friend, and he says, hey, I'm shopping this class called CS50, and you should come with me. Ended up taking it that fall, and after that class, I thought maybe I'm going to minor in CS. But here I am, three years later, still studying computer science and actually doing it as a major, and I loved every moment of it. ROB BOWDEN: I have no idea. ALI NAHM: Let's see. MELISSA NIU: Craziness. SPEAKER 1: I feel like I'd be very cliche. I'd just say, like, awesome. YANIV YACOBY: Accessibility. JACOB PRITT: Free candy and pizza. TRAVIS DOWNS: Can't turn down a class that hands out cake. TIM MCLAUGHLIN: Energetic. VIPUL SHEKHAWAT: Essential. ROB BOWDEN: Let me think of an answer. I think I got something. Oh, god. Yeah, my name's Rob Bowden, and this is CS50. [APPLAUSE] DAVID MALAN: All right, so let's start to paint a picture of the direction in which we can go, and let's introduce this concept here known as pseudocode. So pseudocode is not a programming language unto itself. It's nothing technical per se, but it's just sort of a general way of expressing yourself fairly precisely, fairly algorithmically, fairly procedurally, but without having to worry about what language you're expressing yourself in. It's some model of English and programming languages with which you happen to be familiar, so we can start writing this sort of thing as we go. And in fact, Joseph, could I borrow you up on stage to be scribe here? I've gone ahead here in advance and forgotten to put on some socks today, and this'll be among our more ridiculous examples. Now, I need you over here. I'll do the socks part. So here we have a little scratch pad. This is literally just TextEdit in a Mac. We're not actually going to write a runnable program, but we're just going to start sketching out pseudocode based on some of the counsel you provide to me here. So here is my pile of socks at home. I have no socks on when I wake up in the morning, and we now need to write a program, an algorithm of sorts, with which to get these socks on my feet. And along the way, let's see if we trip over, or encounter, some of the ideas that you're going to have to start thinking about much more seriously when programming lest your programs don't behave quite as intended. So I sit down here. I've got my pile of socks. What's the first thing a reasonable human being would do when the goal is to put on a pair of socks? Someone give me one step, and only one step. Yeah? AUDIENCE: Bend down. DAVID MALAN: Bend down, Okay. Step two. Step two. AUDIENCE: Pick up your sock. DAVID MALAN: Pick up your sock. Okay, so slight ambiguity here, and this is one of the first stumbling blocks that we're supposed to deliberately encounter here. It's a little ambiguous, so pick up your sock. Fine, I'll take this one, but a computer, realize in just a bit, is not going to have that sort of human instinct to just pick the nearest one. We're going to have to start, before long, expressing ourselves more precisely. All right, so step two is pick up your sock. We'll take it. Step three. In the back. AUDIENCE: Find a matching pair. DAVID MALAN: Find matching pair. Okay, so this is good. I had to choose this sock. So the goal is to find a matching sock, now, but what does that mean? A reasonable human being, much like on Wednesday when I just knew how to find Mike Smith in a phone book, just kind of went with their instinct. But here, it's obviously this sock here, but a computer's not going to be so instinctive. A computer is going to have a collection of bits, as we discussed on Wednesday, and those are organized somehow in memory. But the point is that a computer has only the ability to look at things one at a time, and in fact, even we humans-- even though it feels like I glanced down and a split second later I know where the sock is, my brain and my eyes presumably did a quick skim of those socks, and then latched on to the one in question. So if we be all the more deliberate now as a computer, how do I find this matching pair? Well, we have to iterate. We have to perhaps loop over this mess of socks on the floor whereby I say something like FOR EACH sock, pick it up, AND IF the same shape and size as the other one, THEN dot, dot, dot, we'll continue the story. So for each sock, so I pick up this one. I check is this equal to this one. It's not, so I put aside side. Then I iterate again. Is this one equal? No, it's not, so I put it aside. Is this one? No. This one? No, and so forth. And then finally, hopefully, I will encounter this sock here. So if it's the same shape, size, take it. And now, what would be our next step here? Yeah? AUDIENCE: Identify right from left. DAVID MALAN: Okay, identify right and left, so fortunately, that kind of works. A little symmetric, or I've just worn them that way. All right, so I've identified the right. And now, before we proceed, let me point out what Joseph's been doing here as sort of a versed programmer. So again, there's no one way of doing this, but beyond just numbering the lines, Joseph has already started to do this sort of indentation. Indeed, this is a very common convention in programming, whereby when you do something iterative, looping style, as we're implying with the English phrase "FOR EACH sock," the convention in pseudocode and, as we'll see, normal programming languages, is to just indent. Hit the space bar a few times, hit the Tab key or the like, so that nested underneath "FOR EACH sock" is the chunk of stuff that you need to do as a result of that loop. So that's all that's conveying semantically. Now meanwhile, the "If it's the same shape and size," the fact that "Take it" is indented further just means that's the only thing you should do if that condition, if that branch, that fork in the road, is in fact true. So now here, we're on step four, identify right and left. I've identified right. Give me step five. And technically, we could really call the FOR EACH thing-- you should probably number all the lines if we're going to do this. JOSEPH: [INAUDIBLE] DAVID MALAN: [INAUDIBLE]? Okay, fine, all right, we'll do it your way. All right, so step five, how do we do the right sock? How do we proceed next, here? Yes? AUDIENCE: Lift up right leg. DAVID MALAN: Lift up right leg, Okay. Step six? Quickly. Yeah. AUDIENCE: Find an open end of the sock. DAVID MALAN: Okay, find the open end of the sock. So good. So here, honestly, a very common instinct would just be put on right sock, but that too is fairly ambiguous. Unless the computer or human knows exactly what that means, it's not going to be to execute that, so here, I've found the opening of the stock. Step seven? AUDIENCE: Touch your toes. DAVID MALAN: Touch toes. Okay, so now we go-- All right, I'm going to take some liberties here. Thanks. Step eight? Put on sock. Okay, so now I, think we're close enough to sort of take this one at home. All right, so this goes up. I'll take some liberties with what it means, actually. Put the sock on. All right, now step nine? AUDIENCE: Put foot down. DAVID MALAN: Thank you. Step nine, put foot down, and now, we can repeat. So presumably, we can now go into step 10 and say identify left sock, but that's presumably already done. And so then, I can sort of repeat these steps. But this sort of begs the question. Before, the last time we wanted to repeat something, we did it iteratively, again and again, a FOR EACH loop so to speak. Would it make sense to use a loop in order to handle both the left and the right sock? Because it feels like these operations are pretty much identical except for the fact that one starts here and one starts here? Do we loop, or do we just keep writing steps 10 and 11 and 12? AUDIENCE: Loop. DAVID MALAN: Okay, so loop. I actually might have said just keep going. So why is this the case? Well, this is actually the first of our non-obvious design decisions, and in fact, one of the metrics with which we'll begin to evaluate, for ourselves and for you, the quality of a program is just how well designed it is. Have you done the minimal amount of work necessary to get the job done the most quickly, either in terms of your time or in terms of the computer's running time? How many operations does it takes to execute? So arguably, this is an opportunity for a loop because as soon as I start copying and pasting, as Joseph effectively would start doing in a moment, you're kind of wasting your time, and you're being doubly expressive. But at the same time, these are really just two special cases, left and right. And whereas before, I might have 10 or 20 or more socks in a pile, it definitely makes sense not to have 50 lines of code saying check this sock, then the next one, then the next one. Here, it's a little less obvious, and I would proposed that we could go either way. We could either have that loop, although it only loops twice, or we could simply copy and paste just a little bit here in order to get the job done. But this program is buggy, so to speak. It might have some mistakes, errors, or corner cases, so to speak, that we didn't really anticipate. Nothing went wrong this time, but what could have gone wrong while executing this program? AUDIENCE: You don't have any socks. DAVID MALAN: So there could be no socks there whatsoever. So let's consider that corner case. So if we could scroll back up to step one, so step one was bend down, so that checks out. Step two, pick up your sock, but then find matching sock, identify right. We kind of made a whole bunch of assumptions, and this is, frankly, why program sometimes crash. If you, the programmer, have made certain assumptions, like surely there's going to be socks or surely there's going to be memory left in the computer, surely there's going to be disk space left on the hard drive-- Well, if you make these assumptions, and that's not, in fact, reality, who knows sometimes what the computer's going to do? And sometimes, when you get the spinning beach ball or the frozen Windows or the like, that's precisely because some programmer did not anticipate those so-called corner cases. What else could have gone wrong in this program? Yeah? AUDIENCE: You don't have a right leg and a left leg. DAVID MALAN: Okay, might not have both a right leg and a left leg, and so this program might not be universally applicable. Others? AUDIENCE: You might have picked up an orphan sock. DAVID MALAN: I might have picked up an orphan sock, so a non-matching sock that just has no siblings because I've lost it, it's torn, it's in the wash still, or the like. So that, too, hasn't really been handled. Yeah? AUDIENCE: You might already have socks on. DAVID MALAN: I might already have socks on. I didn't actually check. IF you don't have socks on, THEN proceed to do line one and two. And that could happen. You fall asleep with your socks on and the like, so that, too, a very reasonable corner case. And maybe one other? AUDIENCE: The sock is inside out. DAVID MALAN: So the sock is inside out, so we did no error checking, in short. We didn't check if the state of the world is as we expect. We didn't check if we actually found what we're looking for. And even though this is sort of a ridiculous example involving socks, at the end of the day, this is exactly the sort of mindset you need to have while writing programs, even in Scratch as well as in C, in JavaScript, in PHP, because otherwise, your programs will exhibit the equivalent of that spinning beach ball or just yield inaccurate results. So many thanks here to our scribe Joseph. [APPLAUSE] DAVID MALAN: All right, so what is, in fact, a computer program? Well, let's take a quick glance at a representative one here. So this is a program written in a language called C. C is fairly old these days, but many newer languages are built on top of it. Indeed, PHP, one of the web-centric languages we'll use toward term's end, itself has what's called an interpreter, a program that's written in C, but more on that in many weeks from now. But this program, and this is what it means to write a program, albeit a very simple one. We have some fairly cryptic syntax here, but you can probably guess, even if you've never programmed before, what this program does. Indeed, I don't know what printf is, but print certainly conjures up the idea of printing something out. And so yes, this program is ultimately going to print out the words "Hello, World." Now, whether you have a Mac or a PC or a Linux computer, odds are, at least if you downloaded some freely available software, you could have been writing programs on your own laptop for quite some time now. On Mac OS, for instance, there's this program called Terminal that comes with a Mac, that's usually in your Utilities folder, and it generally opens a black and white or a white and black window at which you have a prompt at which you can type commands. So this is actually reminiscent of what computers used to be before graphical user interfaces, GUIs, came along. Now, in Windows, you have a similar mechanism in the form of the command prompt. But what I'm going to do here is open up, let's say, TextEdit again, so the same program we were using for pseudocode a moment ago, and I'm going to go ahead and write my first program. Include stdio.h, whatever that means, int main void, whatever that means, and then in the middle here, printf("hello, world."). And then close quote, close paren, semicolon. Now I'm going to go ahead and just hit Command-S. I'm going to go ahead and save this as hello.c, so the convention in the world of C programming is name the file dot c. I'm going to just put in John Harvard's Home directory, here, click Save, and now I'm going to go over to this terminal window, which again is this black and white prompt where I can execute commands. I can run programs by typing their name, not by double-clicking icons in the usual sense. But the thing is about C is that a language like C first comes in this form, something called source code. Something that looks a little like English but is definitely less like English than Joseph's pseudocode a moment ago. It's a little more arcane. It seems to follow some patterns or rules. The fact that I have curly braces, semicolons, quotes, angle braces, feels like a computer came up with this sort of language. But if I go, now, to this terminal window, I can run a command that's going to convert that source code is something called object code. That's going to convert English-like syntax to zeros and ones, the same sorts of zeros and ones we talked about Wednesday. Now, I'm going to run a command called Clang. More on this in the weeks to come, but it's a program with which I can convert hello.c into a whole bunch of zeros and ones. Now, I've run this command. I've run Clang, and then I said run yourself on this file called hello.c, which I created a moment ago, and nothing seems to happen. But indeed, if I poked around my home directory, I would see that this stupidly named program a.out now exists. This is just the default name for a program when writing in C. We can override this eventually, but a.out is the name of the program I just converted into zeros and ones. And now that it's zeros and ones, my Mac, in this case, or your Windows PC, can understand those bits, those zeros and ones. And so when I hit Enter, I see "hello, world!" But it's a bit buggy. I didn't quite say "hello, world!:air:- jharvard." Air is the name of my computer. Jharvard's the name of the account, so what did I clearly omit from the program? Some kind of line break. I didn't hit the equivalent of Enter or the carriage return, and this is, again, testament to the fact that computers can only do what you tell them to do. And the fact that I didn't tell the computer move the cursor to the next line-- well, it's certainly not going to just do it presumptuously for me. So if I go back to my program, and I say \n-- So \n, as we'll soon see, is the way of representing weird things like new line characters, things that would otherwise be the result of hitting the Enter key. But for now, just know that hitting the Enter key would just make our code look odd, so the world decided, you know what, to keep things prettier, to keep it on one line, let's just say \n represents a new line. Let me resave my file, go back to the terminal window, and re-run a.out, Enter. Still buggy, but why? AUDIENCE: [INAUDIBLE] DAVID MALAN: Yeah, so I need to recompile it. So to compile a program just means convert it from source code to object code, source code to zeros and ones. Now, the mere fact that I hit Save in this TextEdit has no bearing on those zeros and ones because I first need to tell Clang hey, I've changed those lines of code, the source code. You need to regenerate a.out. Nothing appears to have happened, but in a computer, at a command line, so to speak, when nothing happens, that usually means all is well. When something does happen, it means you messed up, generally. So let's now go to a.out, and indeed now, I have "hello, world." And now, what about these zeros and ones? Where, in fact, are those? Well, I can't really just kind of poke around very effectively. Let me open up TextEdit. Here's a.out. Let me go ahead and open this, and this is apparently what my program looks like. So I've opened, not hello.c, but a.out. But this is actually not what my program really is. Clearly, this is some kind of alphabetical characters. I see no zeros and ones, but this is because a.out is a program. Zeros and ones-- but TextEdit, as the name suggests, it's just like Notepad on Windows, is just a text editor, so it's confusing all of those zeros and ones as though they were, what? ASCII characters. So recall on Wednesday, we just came up with this arbitrary mapping of numbers, or bits, to letters of the alphabet and punctuation symbols and the like. So TextEdit, that it's a text editor is misinterpreting those patterns of zeros and ones that are supposed to be printing words, like "hello, world." It's displaying them as ASCII, and that's why it looks a little messy. Now, there are some hints of correctness in here. Notice if I highlight, there is a hint of actually "hello, world," so somewhere in that program is the sentence I wrote. But let's go ahead and now see with a different program. This is not one we'll use that often, but it also comes with a Mac and will be inside of the CS50 appliance. Let me go ahead and open with a program called XXD. Back in the day, most programs were named fairly cryptically, and so the trend continues. But -b means spit this program out as binary. Don't run it. Display it to me as zeros and ones, and this is the C program we just wrote. Now, I, as a human here, I honestly have no idea what these various patterns of zeros and ones represent. Back in the day, I, with my punch cards or the like, would actually have to look up what these various patterns of 01111000, actually represent. Or worse, I would need to do the punching or the creation of these patterns of zeros and ones. But for now, take on faith that a CPU, Intel inside, so to speak, inside of all of our computers these days, knows how to interpret these zeros and ones. And some zeros and ones mean print. Some zeros and ones mean play a sound. Some zeroes and ones mean take user input from a keyboard. There's all sorts of different patterns, but we thankfully, as humans, only generally need to worry about programming at this fairly higher level. And in other CS classes can you delve down deeper and look at things like those zeros and ones, or yet other things still. So now let's convert this. Let's move very quickly away from C and move to something a little more comforting, a little more exciting, in that we can get back our animations and sounds and the like that clearly have escaped us in this fairly primitive interface. So this same program in C can be represented now in this programming language called Scratch as follows. This is the equivalent of this hello world program written in this puzzle piece style language called Scratch. So let me go ahead and open up this very program. It's again called Scratch. It's freely available, and this is the same thing we started today on. So this here is Scratch, and it's broken up into a few different pieces. On the very top right, we have the so-called stage, and indeed, that's where the cookies performed just a bit ago. And on that stage are things called sprites, characters, or objects, or entities. It doesn't really matter how you think of them, but they are programmable, movable things, and in this case, this program that our student wrote has a couple of gingerbread cookies, a couple of circular cookies, a whole bunch of hearts, a whole bunch of eyeglasses. Because of this, he or she is able to program each of those individual characters separately. Now, what does it mean to program these characters? Well, let me go ahead and click on this left hand cookie and scroll over to the top left here. In the top left of my screen now is the so-called scripts area. This is sort of a blank slate, initially, onto which I can drag and drop puzzle pieces that, frankly, do exactly what they say. At the very top of this stack of puzzle pieces is the word When Green Flag Clicked, and if you didn't notice before, the way I started that cookie song was clicking, literally, a green flag. So that puzzle piece at top left there means when the human clicks the green flag, proceeded to do the following things. Now, what did they cookie proceed to do? I don't really know how to interpret this yet, but the cookie apparently set its groove to zero, then it waited three seconds, then it changed its group to one, then it waited a second, then it changed its groove back to one. And then this actually looks like a bit of a bug, shouldn't have to change its groove again and again unless it's being changed elsewhere, but this series of steps is what's dictating the behavior of this particular cookie. So let's actually scroll back and not look at something quite so complex yet. Let me go ahead and go to File, New, and get a clean slate. So now, I indeed have an empty script area, an empty stage, with our default sprite Scratch, and at the top left on my screen do I have the pallet of all of their available puzzle pieces. And we won't go through nearly that many of these things today because, again, most are self-explanatory, but we will try to categorize them and point out the similarities with these future languages to which we will dive. And at top left here is the first When Green Flag Clicked, so let me drag this over here, zoom out a bit. And if I click the green flag, nothing really happens because I haven't attached any logic, any statement so to speak, to that green flag, so let me go up to the categories over here. I'm currently in the Control category. I'm instead going to go down to the Looks category, and there's a whole bunch of things here that say Say, Think, Change Color, Switch Costume. So you can do silly things with costumes and sounds and the like. Let me go ahead and just say Say, and now notice as I drag and drop this puzzle piece, it's going to want to latch into the corresponding shape. So when I go ahead and let go of my mouse, they lock together, and now if I go over here and click the green flag, the cat does in fact say hello because that's what is inside of this white box. We'll soon see that this white box is what's called an argument, or a parameter. It's a way of changing the behavior of, in this case, a puzzle piece, but if I want to say exactly what I said before, say hello, world, I can now go back over here, click play, and "hello, world" is what's said. So we are literally programming now. It's not all that compelling of a program, but at least it's a little more compelling than something that looks, at first glance, like this. And we can very quickly get all the more expressive because in Scratch, like in other languages, there's all sorts of statements, not just Say or printing something, but you can do things like waiting, as we just saw with the cookie, some number of seconds. You can play sounds in the environment of Scratch just like you can in a normal computer program play sound. You can check what are called Boolean expressions. So now, let's start to add to our toolkit some terminology that actually relates to the example that Joseph and I did here with the socks. So statements are just statements of fact. Do this. A directive for the sprite, or me the human, to do something. A Boolean expression is something that has a value, a so-called truth value, that's either a zero or one, false or true, off or on, no or yes. Doesn't really matter how you think of this, but it's a binary state. As Nate discussed in Wednesday's video, two different things. So in Scratch, Boolean expressions happen to look like these blue objects here, and in this case, the question mark implies that you're asking a question. Is the cat, or the sprite, touching the mouse pointer? So this is just one example of a Scratch block that's going to allow us to check yes or no, is the mouse touching the sprite on the screen? And this can be useful if you actually want to do things with your mouse. In addition to Boolean expressions, we have things like is the mouse down, so you can detect that kind of question as well. We can do mathematics if you actually want, and there's actually more compelling uses for this than just pure of arithmetic, as we'll see. Pseudo randomness and making your program appear to think or behave differently based on some seemingly random values, and then we have things like Boolean expressions like AND. So if you actually want to check two values, we'll see in Scratch that we can actually test if this is true and this is true. For instance, in the case of my socks, I could've at the very end asked the question if left sock is on and right sock is on, quit. You're all done for the day, so that would be an opportunity for that. So let's go ahead and try to piece some of these together and go into a couple of examples more compelling than this one. So let me go ahead here and open up some of the examples that will always be on the course's website as well, and open up hello2. So in hello2 here, we have a program that's doing a few things, but it's not doing it as effectively as we might. So here it says "hello, world" for one second and then waits for a second. And then does it again, and then does it again. So if I click the green flag, Scratch says "Hello, world. Hello, world. Hello, world." And this is obviously candidate now for improvement. What's the marginal improvement, hopefully, we can now make if Scratch supports the concept? Some kind of loop. Some kind of repetition, now, would be nice, so let me actually try that. Let me actually go and move this. So notice can detach blocks as easily as you can add to attach them. Let me go under Control, scroll down here, and indeed, there's this puzzle piece here, Repeat and Forever and Forever If. So there's a number of ways of expressing looping constructs in Scratch. The one I probably want here is not Forever because I only want this to happen three times, but probably Repeat. So let me drag Repeat over here, drag and drop it, and now instead of saying "hello, world" three separate times, let me drag this puzzle piece in here. And even though it doesn't seem to fit, the program is smart enough to realize it will grow to fill, so it's the shapes that matter and not the absolute size. Let me change the repetition to three, and now let me go ahead and drag Wait One Second in there as well. It's going to snap in as well, and so now I'm going to drag these guys over here and just throw them away because I don't need them anymore. Let me zoom out and click the green flag now, and we have the same program but, as I predicted before, better designed because you can imagine how bad this program would get, certainly aesthetically, if you had to start copying and pasting, copying and pasting, or dragging and dropping the same darn things again and again. Now, simply saying stuff on the screen, printing to the screen, really all not that exciting, so let's open a third variance here. And now, as you'll see, this'll quickly get annoying-- [MEOW] DAVID MALAN: --but it's also kind of cute. [MEOW] DAVID MALAN: Okay, so better, and we can certainly use that same transition of chunking this up into a looping structure, but let's make it more interesting still. Let me go ahead and open up a fourth variance here, where I take things one step further. So according to this, silly though this is at first glance, what is this program going to do? It's going to meow once. Why? Well, one is, as far as I know, always less than two. There's no notion of randomness here. I've literally hard-coded one and two, but this is an example now of actually using a Boolean expression. Much like as Joseph did in his pseudocode, the indentation IF you find matching socks THEN do the following, here we have an expression IF one is less than two THEN-- and in fact we even have a little bit of indentation, where the purple is slightly indented to the right-- THEN you're going to play the sound meow. Now, in this case, that one is always less than two, so this is kind of a waste of a condition. But we'll be able, as we'll see, to plug other things into these placeholders where one and two now are. So let's now advance to example five of these several hellos and look at what this program's going to do. So now, in an English sentence, how does this program behave? AUDIENCE: Meows half the time. DAVID MALAN: Meow's half of the time, so this is a way of conveying a very simple idea. Even though we happen to be using some inequalities here in some numbers, this is really just a programmatical way, a precise way, of saying if the coin comes up heads, go ahead and meow. Or conversely, if the coin comes up tails, don't meow. And in this case, how do we express that? We'll pick a random number from 1 to 10, and if that number is less than 6, go ahead and meow. And how did this get in here? Well again, notice just the dragging and dropping and things latches into place. So now let's see if this randomness works. Let me go ahead and click the green flag. [MEOW] DAVID MALAN: Okay. [MEOW] DAVID MALAN: Okay. Okay, good, so we got heads, heads, tails effectively. Tails. [MEOW] DAVID MALAN: Heads. [MEOW] DAVID MALAN: Excellent. It's always awkward when just statistically you get a bad run, and it's all heads, and the program actually doesn't work as you'd hope. But this time, it worked, and we seem to have, if we did this an infinite number of times, 50% odds. Now again, not all that interesting, just making cats meow, so let's see if we can't advance this a bit further here in version six. So now, we have really annoying version-- [MEOWS EVERY FEW SECONDS] DAVID MALAN: --and this is what's known, general, as an infinite loop. So infinite loop in this case feels bad. It's definitely going to start sounding bad, and yet infinite loops aren't always bad. Can you think of context in computer programs where you'd actually want an infinite loop? Yeah? AUDIENCE: When you want to check a condition. DAVID MALAN: Okay, when you want to keep checking a condition? Like what? AUDIENCE: [INAUDIBLE] DAVID MALAN: Okay, good, so if you had some program, some kind of home automation thing, where you want to constantly monitor is something the case. Are the lights on? Are the lights on because maybe you have a timer, and you want them to go off, you might need to do something again and again. And in fact, speaking of timers, any of you who have clocks on your computer or digital watches, that's an infinite loop. It continues to update the time because it's constantly checking and checking and checking has the time changed, and if so, oh, my god. The clock's finally changed. It needs display that value to you. So whereas most of the time infinite loops are a mistake, or at least a poor design decision, sometimes they do have their value. Well, let's advance further here to hello7. So now the program will get a little more interactive. Let me zoom in here, and again, this is what's nice about Scratch. And we'll use it to be clear, Scratch, just today and into next week's problem set. But on Monday, we dive into C. In this program here, it does, forever, the following. IF touching the mouse pointer-- now, who's the context here? Well, and notice that who's selected down here at bottom right is the cat, sprite one, so these scripts, this program, applies to him specifically. So if that cat is touching the mouse pointer, then it's going to play this down and wait two seconds, and then repeat ad nauseum. So let's go ahead and hit play. Nothing happens, but if I want to pet the cat now, I can simply. [MEOW] DAVID MALAN: Adorable. [MEOW] DAVID MALAN: Okay, less annoying, but also gets dull, so let's move on and see if we can't inject a little more logic. That was example seven. Here in example eight, we're going to introduce an ELSE condition. So much like a literal fork in the road, in which you can go left or you can go right, a condition in a programming language like Scratch, or as we'll see C, can allow you to go in one direction or another via an IF ELSE construct. So quite literally, IF touching mouse pointer, this will play some sound, ELSE it's going to play this other sound, meow. Now, if you can infer from the name of these sounds, you can probably guess what this program's meant to conjure up the idea of. This cat is meowing happily. [MEOW] DAVID MALAN: Happily, but doesn't quite like to be touched. [ROARS] DAVID MALAN: So now we have a cat who will yell at you. All right, well, one last example with cats here, and let's open version nine of this here. So now, we have the next most annoying sound that I could find, so we have a walrus or sea lion here who's going to do the following. [SEAL BARK] DAVID MALAN: Okay, so this will go on until you figure out how this program works. So this time, this animal has two scripts, and what's interesting here is that these scripts are going to execute in parallel. So because they both start with one green flag clicked, it's like going like this, and both programs start running it once even if they're looping forever. So in the top script, I have some logic. What features does that provide up there? [SEAL BARK] AUDIENCE: [INAUDIBLE] DAVID MALAN: If it's what? [SEAL BARK] AUDIENCE: If muted to zero, it's going to keep playing the sound. [SEAL BARK] DAVID MALAN: Okay, good. So IF muted, whatever this is, this orange thing is zero, THEN play the sea lion sound and think "Oh, hi," for two seconds. Now, I don't know what muted is, but zero conjures up the idea of false or off. So if muted is false, so if not muted, keep playing the sound. All right, well, how do we disable this thing? Well, let's look at the second script down there. The second script says set muted to zero. Notice it's also orange, so what Scratch does is it colors blocks in the same shade if it's sort of logically related. So just as muted up top was orange, so is muted down here mentioned in orange block. But this is a variable assignments, so just like in algebra, you have x and y and z, in programming you have variables, but they're generally-- let's pause for a moment and figure how to stop this barking. How do I do this? [SEAL BARK] DAVID MALAN: Okay. It stopped. Okay. So just as in algebra you have variables x, y, and z, but in programming, having variables like x, y, and z is generally frowned upon because they're not at all expressive. They have no semantic meaning whatsoever, so in most programming languages, variables can have full fledged names or words or phrases, like muted, to say what they do. So this second script also was listening forever, and it said if the key, the keyboard key Space, is pressed, question mark. So there's a condition with a Boolean expression that's going to answer a question either truthfully or false, then I have inside of it IF the space key is pressed AND IF muted is zero, set muted to one, ELSE set muted to zero. So this other fork in the road, and notice how I've nested the two IF conditions, is a way of checking is the Space Bar pressed because if so, I either want to go this way or that way. And how do I invert the value of muted? I have to check is it zero? If so, make it one, else make it zero to therefore toggle its two states. All right, so we have then some of these fundamental constructs. We have Boolean expressions, and realize, too, these are not all that unfamiliar. In fact, here's a quick screenshot of Harvard course's CS50 shopping tool, and any website out there that has checkboxes and drop downs have really, all this time, been using Boolean expressions. In this case here, if you click the checkbox next to course greater than or equal to 4.5, or the same next to faculty, you're specifying a Boolean expression. Show me courses for which that expression is true. Or to the right, doesn't conflict with courses I'm taking, if that is checked, then yes, you want to check that condition, else you want to ignore it. So Boolean expressions are sort of all around, but when we put them in conditions, whether IF conditions, IF ELSEs, or we can even simulate deeper levels, IF ELSE IF ELSE-- so that's sort of a ternary state. You can go this way or this way or this way. We can keep nesting things to go in different directions. So Scratch has these loops, like Forever. It has these features like Repeat 10, some finite number of times. We have the ability now to set variables, so in this case I've declared, for instance, a variable called socks. I've initialized to 0, and that's yet another direction we could have taken up here with Joseph, whereby maybe I just keep track of how many socks I have on and terminate the program when that variable's value is 2. That would be another way of sort of generalizing that problem and doing something again and again. Well, let's go ahead and now introduce a couple new things. So those of you with prior programing experience will know that a lot of languages have arrays, or vectors or lists, and indeed, Scratch has something like this, too. So let's see if we can't take things to the next level here. If I have the ability, now, with these puzzle pieces to add something, like a word or number, to a variable, I can start to accumulate things. And this is actually pretty apropos for things like games, role-playing games where you're kind of walking around some fantasy world collecting things, picking things up, earning points, or the like. You might want to keep track of some kind of inventory, and indeed, that's what one of our former students here did with something called Fruitcraft RPG. So let me go ahead and open up this thing here, and in Fruitcraft, we have this world up at top. So let me go ahead and click the green flag. Notice at top left is some kind of inventory. That's implemented in Scratch as what we'll call an array or a list, and now we have this little animation. So just as we started earlier with this cookie love story, and then we advanced to cats and sea lions, now we can have things that are even more interactive. And this little blue guy, I can start to move around his little home here. So it looks like he's got an exit down here, so I'm using the arrows keys, up, down, left right. And now I'm outside, so let's what I've got here. Looks like an orange, and indeed, as soon as I touch the orange, it gets plopped into my inventory. If I go over here to the cherries, now I have something else in my inventory. And this is all nice and cute, but think about how, now, this is implemented. Well, we have this notion of a list, and that's apparently a puzzle piece that you just say what you want add to it, add orange, add cherries. Now, what is this little blue guy doing? Well, he's a sprite. And presumably, the orange and the cherries-- they themselves were separate sprites. And using conditions in Boolean expressions, the student was probably able to express IF blue guy is touching cherries THEN add the word cherries to his inventory, and then also hide the cherry sprite. So underneath the hood, there probably still is a cherry sprite there. We've just told it to become effectively invisible. Now, if I keep walking over here, we can also do this proximal thing, where I can go and read the sign. So if blue guy touching sign, we can have this Say block just like the cat spoke to us in words, hello, earlier, "Got some fruit? Bring it to the fruit place." All right, so now, apparently, I have my directions. I can go over here to the fruit place, line myself up with the door. Now, I'm in here. I can go up to the man at the counter. He detects that I'm close to him, so it doesn't have to be quite identically touching, and I have won the game. So there we have Fruitcraft RPG. So we can do things even more advanced than this. We can add sounds. We can add pseudo randomness. We can add complexity. Let me go ahead here, and rather than do this myself, let me show you one of the more sophisticated submissions we got last year from a certain someone named Blake. Can we have one volunteer who is comfortable appearing on camera and is up for playing a game? How about right there? Come on up. All right, so the game that you have just unknowingly volunteered to play-- [APPLAUSE] DAVID MALAN: --is something from yesteryear called "Frogger." What is your name? RENDA: Renda. DAVID MALAN: Redna? RENDA: It's like Brenda with a b. DAVID MALAN: Okay, Renda. David. Nice to meet you. So here in "Frogger," and if we could raise the volume just a little bit, you are this little green frog on the bottom. You can use left, right, up and down, and your goal is to cross the street, cross the river, and touch the lily pads at the top. Aw. One more t-- redo, all right? Let's hit stop. No one saw that. [APPLAUSE] [APPLAUSE] DAVID MALAN: Yeah. Very well done. Excellent, thank you. So that there was Frogger. Now that you know what you've gotten yourselves into, one more volunteer for a different game submitted by another student. You want to come on up? What's your name? RICHARD: Richard. DAVID MALAN: Richard. All right, Richard, come on up. [APPLAUSE] DAVID MALAN: You have something that'll sound familiar soon, so here are your instructions. So in a moment, some puzzle pieces are going to scroll up from the screen that look either left or right up or down. You're going to have to hit the arrow keys in such a way that it corresponds to those puzzle pieces lining up with the placeholders at top. So when you see a left arrow, and it lines up with the left arrow, hit the left arrow. You may begin. [MUSIC - "STRONGER" KAYNE WEST] DAVID MALAN: All right, big round of applause for Richard. [APPLAUSE] DAVID MALAN: Very well done. Thank you. [APPLAUSE] DAVID MALAN: So fun and, seemingly, sort of intimidating as it might be to implement something as seemingly sophisticated as this, realize that the student didn't set out and just write this all at once. Rather, you can break down a problem as seemingly complex as this into much smaller pieces, and this, too, is going to be a theme. The worst thing you can do in writing a program in most any language is to sit down, get really excited, write the whole damn thing, and then just hope that it works by the time you're finished writing. Rather, the process of programming should generally be very deliberate, very iterative, whereby you just set very small steps for yourselves, bite-size pieces do you want to bite off, and so that you have these sanity checks, little milestones you can meet. And then you build on top of those to create more sophisticated things still. So for instance, how could we go about implementing a game like this? Well, frankly, I would certainly start by just supporting one key at a time. Let's just implement support for the left arrow. So the student had to somehow create in Photoshop, or in Scratch itself using the little graphical editor, an arrow key that looks like the one at top left there, just the gray placeholder. Then the student had to figure out what x, y coordinate to put it, where to put it in the window. 0, 0 is up here, so you have to figure out the number of pixels, or dots, to offset that arrow from the top of the screen. And then once that's in place, your program doesn't actually do anything yet, so you then need a second sprite, for instance a green arrow that's also pointing left, and you then need to start writing some scripts for it. And you notice, perhaps, that these things started coming at different speeds, and the colors were in different locations, and that's because the student used a bit of pseudo randomness. And by pseudo randomness, I just mean pick a number between something and something because you can start to map things, like if the number is between one and five, well, let's make the thing green. If it's between 6 and 10, let's make the puzzle piece red instead. So long as you have a way of generating some kind of randomness, you can then make decisions based on that randomness. And I keep saying pseudo random because there's a little dirty secret. Computers can't come up with random numbers. They can only do what they're told because they're man-made devices. They can't just guess a number like we humans feel like we can. A computer has to do something mathematical to conjure up the illusion of mathematical number, sometimes using the current day of time as an input to figuring out what number to return, but more on that another time. For now, just know that we can generate pseudo randomness. So once I have the ability for the left arrow to start appearing at different times and at different speeds, then I can go back and add some of these IF conditions. IF this sprite is touching the other one, AND the left arrow key has been pressed-- so three conditions in that case. I can use that AND block perhaps, in that case-- THEN I want to go ahead and increment the score. And at top, we have a score, we have Awesome, Cool, Good, and Boo. So there's apparently five variables that this student used to keep track of these various metrics. So in short, the end result is amazing. It's fun, it's fun to play, it's engaging, but this is not where the student began. He or she started at a much smaller set of steps. So what are some other building blocks that we can weave into these programs? Well, there's this other concept in most languages, Scratch among them, known as threads. So a computer can actually not really do multiple things at a time, at least not usually. Rather, a computer generally has just one CPU, and even though computers are super fast and can, therefore, create the illusion of doing multiple things at once-- checking your mail, getting an instant message, printing a document-- really, a computer is just jumping from printing to IMing to emailing, back and back and back and forth so fast that we slow witted humans just don't realize that it's actually running those programs a little bit at a time. Now, this a bit of a white lie these days because, nowadays, many our computers are what are called multi-core, so you have one CPU but multiple cores, which is kind of like having multiple CPUs. And so sometimes, computers can truly do multiple things at a time, but generally within a program, programs rely on these things called threads. So a thread is sort of like a miniature program that can exist alongside another miniature program and can run in parallel, or at least can run under the illusion that they're running simultaneously. So Scratch supports these things called threads. You can have multiple scripts executing at once, just as we did with the sea lion, and this allows us to actually then have interactions among these sprites. Let me go ahead here and pull up, let's say, threads, and play this as follows. We have two sprites, each of whom we'll see has just one script. And you notice there seems to be some intelligence in the cat in this one because he's getting closer-- [ROARS] DAVID MALAN: --and closer to the little bird. So how is the bird operating? Well, let's take a look at the bird first. The bird script said when the green flag is clicked, go to x equals negative 115 and y equals 150. So I just figured out a random location where I wanted the bird to start, and I just plopped him there by default. Then Forever IF not touching cat, so this is a different kind of looping construct, but same idea, do this again and again and again. So long as you're not touching the cat, move three steps, and if you're on the edge, bounce, where it's sort of a reflection in the billiard sense. So that's how the bird is moving around kind of seemingly randomly, but it's just because it's bouncing off the walls in this case. Now the cat, meanwhile, is kind of cheating. The cat, when the green flag is clicked, yes, starts in some location, a random location-- at least in part as per the pick random green block there-- and then Forever IF touching the bird, play the lion sound, and then stop script. So when I said terminate, or exit before, there's a puzzle piece in Scratch that will just kill the program at that point because it's kind of logically done. But otherwise, here, notice what's going to happen. Point toward the bird and move one step. So this point toward bird is kind of an advantage the cat has in that it's homing in on the moving bird, and we can now make this program all the more interesting. Instead of moving one step at a time per CPU cycle, per strike toll of the bell, so to speak, let me go ahead and move, let's say, five steps at a time as the cat. Click run, and now he really finds him quickly. If we double this further to 10 steps, it kind of goes right for him. Now, we can give the bird, perhaps, a bit of an advantage. Let's go to the bird and say instead of moving three steps, let's move him 30 steps. But he still got caught in the end. So here, we have two threads. It's incarcerated in Scratch with two scripts and two sprites, but the idea in other languages is that you can write, essentially, too many programs like this and have them run truly, or imaginarily, in parallel. Now, there's also this concept in programming known as events, and this is something we won't see in C, the language known as C. We will see it towards semester's end in web programming, when we introduce JavaScript and the notion of building web pages that are dynamic and interact with users. So in this case, we have a very simple example of two sprites, boy and girl, each of whom have their respective threads, but somehow these two are inter-communicating by way of something called events. So let me go ahead here and zoom in on the boy's script, which looks like this. When green flag clicked, forever do the following. If the key Space, or the Space Bar, is pressed, say Marco for two seconds, that's purely aesthetic on the screen, a little speech bubble, but then broadcast. So broadcast is another Scratch piece that's representative of a class of functionality in programming that allows different programs, different threads, to inter-communicate, to somehow send messages, one to another. Passing a piece of paper in class is sort of the low tech equivalent. So broadcast event. I can send this message, and the word event is completely arbitrary. Scratch sometimes has these drop downs, so I just came up with a random word like event because now, what the boy does when I press the key is he broadcasts this event. And if I look now at the girl's script, her script is super simple because all she needs to do is not act when the green flag is clicked. She is designed to action when she receives quote, unquote, "event", and at that point, she's listening therefore for the so-called event again and again. As soon as she receives that event, she's going to shout Polo for two seconds. And so you can perhaps infer from this exactly what the next result is going to be. Let me click the green flag. Nothing happens because I need to do what? AUDIENCE: Space Bar. DAVID MALAN: Space Bar. Boy says Marco, girl says Polo. But that's not hard coded per se. That's inter-communication between scripts, so now we have the ability to make even more complex programs where these two are somehow inter-communicating. So in what directions can we take this? Well, in problem set 0, really, the objective is to have fun with Scratch. For the hacker edition, you'll instead have fun with a more sophisticated version of Scratch called BYOB, Build Your Own Blocks, but the idea is the same. You'll be able-- Yes, that was deliberate. It came from Berkeley. BYOB is the hacker edition version of this, but both demographics, standard edition and hacker edition alike, the goal at hand for the coming week is really just to dive in deep, get your hands dirty with programming, and make something interesting, make something interactive, make something artistic, make something fun to actually demonstrate, so that by week's end, you'll have a project, not only for your first CS50 pset, but you'll have a little something that you can show off in Annenberg to friends or even family by uploading it to MIT's website. And so as I said on Wednesday, we expect 90% of the class, generally, to do the standard editions. Realize that there's also this outlet for those of you who might otherwise find yourself a bit bored with the basics and really want to dive in and craft a vision you already have with prior background in this more friendly environment. So let me pull up one other example that one of our former students here did and tell a little something through song. That similarly, as this plays, think about how you go about implementing this program using precisely these same building blocks, a little bit of pseudo randomness, and a bit of familiar song. If we could raise the volume just a little bit? [MUSIC - "IT'S RAINING MEN" THE WEATHER GIRLS] DAVID MALAN: That's it for CS50. We will see you on Monday. [APPLAUSE]