1. Home
  2. Explore
  3. Computer Science
  4. Introduction to Programming

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Content

Introduction to Programming

Transcript

SPEAKER 1: This is CS50, and this is week 1. And by the end of the day, you will know how to create programs that look like this. So this, of course, is binary. This is the only language that machines ultimately understand. But thankfully, per last week, there's so many abstractions and there are so many humans that have come before us that we don't actually have to write anything at this level. We can abstract way above it like we did with Scratch already and like we will starting today with C. But does anyone nonetheless want to take a guess at what that program, when fed to your Mac or PC, actually does? Anyone recognize? Anyone want to hazard a guess? It's perhaps the simplest program you could write. Indeed, it does, when fed to the brain of your computer, the so-called CPU simply prints that. So how do we actually get to that point? Well, recall where we started this conversation last time talking about computer science more generally

and problem solving-- we proposed could be distilled really is this. You've got some inputs. You want some outputs. And somewhere in the middle, you need to do something with those inputs. And to get to that point, though, we had to represent those inputs and outputs. We just had to decide as humans, how are we going to represent all of the inputs to our problem when it comes time to have a computer actually process them. And at the end of the day, all of the phones and the computers that we're all using only at the end of the day plug into the wall to get their physical resource, electricity, and they might store that temporarily in a battery. But that really is our only input. It's either plugged in or it's not. It's either a 1 or a 0, true or false. So the world really reduces to those two states, so to speak. And so you can think of those states then as just being like a light bulb, on or off.

I pulled up my cell phone last time to turn the flashlight on or off, 1 or 0, true or false. Now of course, if you only have one light bulb, you can only count from 0 to 1. But if you start to have a bunch of them back to back to back to back, you can permute them like I did my finger-- 0, 1, 2, 3, and so forth. And so we started talking about binary more generally. And so here for instance were three sequences of 0's and 1's and each of those represented something, but we don't need to think about the world at that level. We can abstract on top of that. All of us are so much more familiar with decimal of course, and indeed recall that this was just 72, 73, and 33, which if anyone recalls, when you use ASCII-- which is this global standard for mapping numbers to letters-- we got what message? Yeah, it was just high, capital H capital I exclamation point. And so that's an abstraction on top of those otherwise binary numbers.

But we don't have to model just text using numbers. At the end of the day, our only resource is still that electricity, and the only way we think about it digitally is still zeros and ones. But if we take the same value-- 72, 73, 33-- and treat them in the context of Photoshop or a photo program or a graphics program, we can instead interpret them as like some amount of red, some amount of green, some amount of blue, which gave us last time, recall, this yellowish color. So now we had another abstraction on top of binary colors, and this is just one pixel. What can you do once you have more than one pixel? What can you represent next? Yeah right images. So we're continuing the conversation up and up and up, and we could represents something like a graphical emoji on the screen, which has more than just one yellow dot. It's got a whole bunch of yellow dots and other colors as well. And recall that, if we want to animate things,

whether it's through silly things like animojis on a phone or just more proper videos and movies, well, those are just sequences of images flying past your human eyes really quite quickly. So that's where we kind of left off last time starting at the base level and abstracting away so that we could stipulate thereafter we can represent inputs, and we can represent outputs, whatever those happen to be. And here on out, we don't need to think at that level. We can just assume we all know how to do this. And even if it eventually becomes kind of a distant memory, we know that someone can indeed do this. And that's the value of abstraction. But inside of this black box are so-called algorithms, the secret sauce-- this is where the problems are actually solved. And we not only talked about what these algorithms are, but for instance, how efficient they were. So recall that this red line represented a very simple algorithm just turning

the phone book page by page one at a time. And the reason that it's a straight line is because there's a one to one correspondence between how many pages there are in the book and how many page turns there are-- one page, one more page, one more turn, and so forth. If I fly through it at twice the speed-- 2 4 6 8-- I can do better. And so that yellow line now, recall, was lower on the graph. If you just look at any two points, yellow and red, yellow is below red, saying it takes less time. But it was not quite correct. There was one bug when I was looking for Mike two pages at a time. What was that issue? Yeah, I might miss him. He might accidentally get sandwiched in between two pages-- not a huge deal because I could fix it, but I have to fix it. I have to apply that additional logic and double back at least a page if I go too fast. But of course the final algorithm-- and frankly all of our initial intuition probably-- was the dividing and conquer, open it roughly to the middle,

look down, and then go left, and go right, and just repeat that process as the problem gets this big to this big to this big to this big to just one page left. So that was all about efficiency. But to get to that point we needed to express ourselves more precisely. And so we introduced pseudo code. There's no formal definition. It can be English, English like. It's just meant to be succinct and get the point across. And recall that, along the way, we introduced a whole bunch of concepts, many of which you probably experimented with Scratch, like loops and conditions, Boolean expressions, variables, and so forth. And those were building blocks that came out of this kind of demonstration here. But honestly, even in this demonstration, in this pseudo code, there were a whole bunch of assumptions. If you read these instructions one at a time and you're holding the phone book yourself, odds are you can execute this pseudocode, this algorithm.

But what does it really mean to, say, open to the middle of the phone book? All of us have an intuitive understanding of what that means. But honestly, if you were explaining that to a kid or someone who's learning English or whatever language for the first time, open to the middle of the phone book, you should probably sets forth some assumptions. OK, this thing in front of you has 1,000 pages, pieces of paper. Turn to the 500th page, and let's call that the middle. This would very quickly get tedious if all of us humans are talking at that level of detail. And so we abstract away with more sweeping statements like open to the middle of the phone book, but that's an abstraction. And it's not quite as precise as is probably ideal, especially feeding this algorithm to a newbie or to a robot or a computer. But it's useful because we can then make a 12 step program instead of a 20 step program by elaborating too much.

And for instance, throughout here too we had our loops and conditions and so forth, but even call Mike. What does that mean? Well, if you imagine that the human knows how to use the phone, then it goes without saying. But if he or she also needs to be programmed to use the phone, you've got to explain-- pick it up, hit this button, type this sequence of buttons, and so forth. So call Mike is also an abstraction. So these abstractions are useful, but they can sometimes get in the way, especially if you're not precise enough to program the computer correctly. And to paint this picture, I thought we could begin a little heartedly here. I brought some breakfast, if you didn't quite make it next door or beyond. Just need a couple of volunteers if you're comfortable appearing on stage and on the internet here. Let me kind of-- there's a lot of lights here. How about over there on the left and over here in the front? Yeah, right there. I think your hand was up. Come on down.

And Brian, do you mind lending us a hand here, too? Come on down. If you want to take control here, let you go ahead and switch over to another program for you. What's your name? JEAN: Jean. DAVID: Jean, David. Nice to meet you. Have a seat on the far left. And your name? ABBY: Hi, I'm Abby. Nice to meet you as well. On the far right if you could. So Jean and Abby, do you want to say a little something about yourselves quickly? JEAN: I'm Jean. I'm a Massachusetts native, and I'm taking CS for the first. It's my first coding or anything. Or I'm doing and I'm enjoying it. DAVID: Nice, glad to have you with us. And Abby? ABBY: Hi, I'm Abby. I'm taking this as a sophomore, and I know nothing about computers or computer science. So I'm probably taking it stat on stat. DAVID: OK, well, nice to have you as well. So in front of us is a whole bunch of ingredients, and hopefully we can start this semester off gently.

And if we're successful, we'll actually have a quick bite here. But we thought we'd defer to the audience here, and Brian's going to scribe as we go. And all we want to do this morning is just make a peanut butter and jelly sandwich, one instruction at a time. And each of us will just execute what we hear. How does that sound? All right, if someone could volunteer with the first instruction and Brian will type it down. AUDIENCE: Open bread. DAVID: Open bread we heard. Open bread is the first instruction. So each of you would like to execute open bread.

No, don't look at me. All right, so we're kind of on our way. I think Abby did it better certainly, but we did it correctly arguably. So let's move on to step 2 and see if we can't improve. Take out bread. Welcome to the team now. Nice, all right, step three. Yeah. AUDIENCE: Place two pieces of bread on the table. DAVID: Place two pieces of bread on the table.

Never mind the plates. OK, step four. AUDIENCE: Twist cover of jelly till it opens. DAVID: Twist cover of jelly till it opens. Thank you. Step five? Step five? Yeah? AUDIENCE: Place the lid to the side. DAVID: Thank you. Place the lid to the side. I took some liberties myself. AUDIENCE: Take the knife. DAVID: Take the knife.

Peel off the cover of the jelly. No covers on ours. Stick knife into the bottle? From the top. Stick-- step nine. AUDIENCE: Rotate hands so jelly ends up on. DAVID: Rotate hands so jelly ends up on-- OK, step-- quickly-- 10.

Yes, step 10? AUDIENCE: Pull out knife. DAVID: Pull out knife. OK, step 11. Jelly side down on bread. All right, step 12. Step 12, anyone? Yes. Thank you. Step 13. Pour jelly on bread.

JEAN: Pour jelly-- DAVID: Pour jelly, jelly. All of it? OK, now you're just messing with us. Step 14. AUDIENCE: Put jelly down. DAVID: Put jelly down. Thank you. 15? Pick up peanut butter. AUDIENCE: Take the lid off. DAVID: Take lid off. Thank you. Peel off lid. Thank you.

Step 18? Pick up knife by blunt end, scoop. Scoop. Step 20? Put peanut butter on bread? 21? AUDIENCE: Move the knife left to right. DAVID: Move-- move the knife left to right, please. Left to right.

Step 22? AUDIENCE: Put down knife. DAVID: Thank you. 23? AUDIENCE: Put down jar. DAVID: 24. What was that? Eat sandwich. OK, I think we're-- well, why don't each take a bite? And a round of applause, if we could, for our volunteers. Thank you. ABBY: Mind if I take some for the row? DAVID: You can take some for the row if you'd like. Thank you. So-- thank you, Brian. OK, now I need a minute.

Thank you. So suffice it to say, this obviously demonstrated even more so than the phone book example where our certain assumptions are and our abstractions are. And honestly, almost all the time those are useful. And of course, we kind of hammed things up. And I think the instructions were kind of helping with that here. But when it comes time to program with Scratch and certainly with C starting this week, you can't really make as many of those assumptions anymore because, if you don't handle these corner cases and if you don't think about what that instruction means, you're going to get the proverbial spinning beachball or the hourglass that you're familiar with on your Mac or PC. The program is going to crash, something's going to go wrong just because you miss some specificity or precision. Now we're full of peanut butter. So over time, we're going to find that, much like in Scratch, we were able to make our own building blocks.

You might recall the short examples we did with the cough example where I had cough 0 and then cough 1 and cough 2 where I was making my own puzzle piece within Scratch. That was useful because, after that example theoretically, I never again need to think about or worry about how to implement cough. I can just use that abstraction. But someone has to implement them, and sometimes it's going to be other people who have come before us. And sometimes it's going to be us. So this isn't to say that programming ends up being so tedious that you have to point out every little thing, but you or someone does have to do that level of precision at least once. And nicely enough in Scratch, MIT did most of that legwork for you. We all had the building blocks with which to make our own animation or game or artwork or the like. But even then, you probably had to connect several dozen puzzle pieces or even more to get those fundamentals to do

what it is that you wanted it to do. So today we're going to start to transition from Scratch, this graphical programming language, that while targeted at younger students, is typically representative of a lot of the same concepts that are now going to be laced throughout the semester. But we're going to introduce today an older, more traditional language that's just text based. And as such it's a lot more powerful. But at first glance, it's actually going to look a lot more cryptic. In fact, instead of writing zeros and ones starting today, we're instead going to write something like this. Now if you've never programmed before, odds are, at first glance, this does look pretty cryptic, and there's a lot of symbols within it, punctuation from the keyboard. There's probably some familiar English like words. And frankly, even after doing Scratch anyone, even with no prior background, can probably hazard a guess as to what this program written

in this other language called C does when you run it. It just prints hello world. Now granted there's a decent amount of overhead syntactically. There's a bunch of stuff you have to type to make this program do what you want it to do. But at the end of the day, that's all it's going to do. And this is among the simplest of programs we're going to add to our puzzle pieces, so to speak, today and see some of those same concepts that we saw last time as well. So let's do this first though. Let me take a moment to compare Scratch to C because the most important takeaway for today is going to be that, even if the syntax doesn't look so obvious-- and frankly, even if your first minutes or hours with writing your own code in C is frustrating because, oh, dammit, you left off a semi-colon or, oh, I had a parenthesis in the wrong place. There's a lot of these stupid syntactic hangups that make you feel quite often that you really aren't getting it. But that's not the important stuff.

A lot of the syntax is the least important. That's not at all fundamentally intellectually interesting. So try to see past that, and try to take comfort in the fact that it's the principles that are going to be important. And honestly, just muscle memory and practice, all of the other stuff that at first is going to be an occasional frustration, it just starts to go away as you start to see this for what it is and not for the syntax alone that you see on first glance. So this is to say this program on the right in C is equivalent to what we did just a week ago with two puzzle pieces in Scratch. Now there isn't going to be a green flag on my Mac or my PC as we move forward that you can just click. We're going to run these programs in a little different way, but that's all the code on the right is doing. It's equivalent to the code on the left. So let's do this again and again for just a few of those concepts

from last time, and then we'll start writing some of our own programs. So this was an example, this purple block, of what concept in programming? Yeah, a function. So it was a verb. It was an action, and we're going to call those generally functions. They just have functionality built into them. So how do we do this in C? Well, you might remember from just a moment ago, because one of the lines of code was representative of this, it had some of this syntax. So in fact, if I were to translate the block on the left in Scratch to the equivalent code in this other text based language called C, I'm going to start by writing print and then open parenthesis and then close parenthesis. And those parentheses represent the oval, the white oval on the left, that we typed hello world into before. Now in C, it's not quite as literal as that. The function, or the verb, is actually not called print. It's called printf, and the F stands for formatted.

And it just means that in C you can actually format your text in different ways. So we'll see that before long, and it turns out that you don't just write hello world between those parentheses like we did in Scratch. You also actually have to surround them with double quotes in C. Not such a big deal, but something you didn't have to do before. But in C, you're also going to generally want to be super specific to the computer. And when you want the cursor the text on the screen to move down to the next line, you need to tell the computer that by literally typing backslash n. The human is not going to see a backslash and an n. He or she is actually going to see the cursor move to the next line of the screen like in Google Docs or in Microsoft Word or the like. But this just speaks to the precision that you need to have when talking to a computer at this level and not just with the puzzle pieces. And then one last thing-- and I alluded to it earlier

because it's the bane of a lot of programmers early on. Most lines of code in C have to end in a semi-colon. That's the sort of code equivalent of a period in an English or some other languages sentence. So that's it. It took us a little while to build that up. But that's all it is. The idea on the left of saying something is the same in C as printing something with this function called printf. And before I forge ahead with some other comparisons, any questions on just this translation? AUDIENCE: How do you write backslash n? DAVID: How do you write backslash n? Good, so thinking ahead, this would seem to make it hard to literally show the user backslash n. Well, it turns out that this backslash, because it's not a terribly common character, the programming world uses it as what's called an escape character. It's one that you use when you want to escape information and show it in a slightly different way. So the way you would show literally to the human

a actual backslash n is to actually in your code do backslash backslash n because the second backslash is like saying treat the next character special and actually show it to the human. And there's other such examples of that. So how about this one? This orange block was an example of one concept in Scratch? Yeah, so this was a variable, like an x and y in algebra. This was just a placeholder for data, and you could store numbers. It turns out you can store words. You can store other things too in other languages. So in C, we're going to do this. We're going to say, literally, the name of the variable we want-- for instance, counter. But we could call anything we want-- equals zero if we're setting it initially equal to zero. But C is a little more pedantic. You've also got to tell the computer, the type of variable I want is specifically for an integer, otherwise abbreviated int. So you have to tell the computer in advance what type of data

you're going to store on it. And take a guess. You've got to finish the thought ion C. What more do we need to add to the-- yeah, just a semi-colon. And that's it. It looks a little more cryptic, but the idea is fundamentally the same. So what if we wanted to do this in Scratch? Change counter by 1-- this was equivalent to incrementing or adding 1 to counter. Well, let me go ahead and propose that you could literally just do this in C. Set counter equal to whatever counter currently is plus 1. That seems to be the right intuition. And now notice, what's key to note here is that this equal sign isn't saying that counter equals counter plus 1 because that just doesn't seem possible. If you pick any value for counter, like the number 1, well, one definitely does not equal 1 plus 1, which is 2. And 1 does not equal 2, and you can come up with an infinite number of worrisome incorrect comparisons. So the equal sign in C, like a lot of languages we'll see in the class,

actually means assignment. Copy the value on the right into the value on the left. So set counter equal to whatever it is plus 1. What? We've got to finish the thought. So we need a semi-colon. I don't though need to remention int, and why might that be? Yeah, I already told the computer it's an integer. You don't need to repeat yourself by mentioning int again, assuming in this context, even though we're looking at it just on the slide, has actually been created before just like you did with Scratch by saying make a variable. So it turns out you can be a little more succinct in C and a lot of languages. If you find this a little tedious to type-- and it's a little verbose. It's a bunch of keystrokes. You can actually abbreviate it with just this. So plus equals is just syntactic sugar, as a programmer would say. It's just a nice fancy feature that lets you write fewer words or characters but do the same thing. And frankly, we can do a little better.

And if you've taken a PCS, you might have seen this in Java as well. You can also simplify this even more to just counter plus plus semi-colon. So that's it-- all equivalent. This is just a little more efficient. And as you get more comfortable programming, saving keystrokes just saves you time. Now this of course was an example of what in Scratch by contrast? Yeah, we called this a condition. And it had a Boolean expression that we were asking a question of. In this case, we're apparently asking in Scratch is x less than y and, if so, say it on the screen. So how might we translate this to see? Well, it turns out we can quite simply translate this one pretty literally. We've seen almost all of the building blocks thus far, but we do have to introduce a little something new here. Notice that the printf line is almost identical to what I used earlier for just hello world. I've obviously just changed the words in it, but I still have the backslash n.

I still have the quotes, still have the semi-colon. So the rest of that is the same. Now if is new, but this is a one to one translation. Scratch calls it if. C calls it if. And the only additional thing you need in C is parentheses around the Boolean expression. So that's what takes the place of the little green block there. And then assuming x and y are indeed variables that we created earlier, you can just compare them like this and you can use greater than and other symbols for comparison as well. But there is something a little interesting, and most of us don't often have occasion to even use these keys on our keyboard. Curly braces, on a US keyboard they tend to be over on the top right above your Enter key. These are just C's equivalent of this shape. Notice that most of the yellow blocks in Scratch had this embracing or this embracing shape to them.

You can simulate that in C by having what's called an open curly brace and then a closed curly brace. So that's the same exact idea. Now as an aside, you don't technically always need these curly braces. If you just got a one liner like this, you can omit them as you might see online or in textbooks. But we'll just always draw them for consistency so that the C code always looks like this. What if you wanted to express this, though? If x is less than y, then say x is less than y, else say x is not less than y. Well, it turns out this is almost identical. The first four lines, perfectly the same as before. But it turns out in C, you can literally say else after that closing curly brace. And then just print out alternatively whatever it is you want to say. So this is like the fork in the road. If you go one way, say this. If you go the other way, say this other thing. Any questions on these comparisons thus far? Yeah.

AUDIENCE: Should we put the first bracket on the same line as the if? DAVID: Really good question. Can you or do you put the curly brace on the same line is the if? You can, and we're going to talk about this the next couple of weeks, this matter of style. There are different ways I could express this exact same code. Frankly, I could write out all of this code with no spaces whatsoever. In fact, just to make that point, if I go ahead and just open up a simple text editor here-- not to actually program, but to just type something-- I could actually do something like this if x less than y. Then go ahead and print out x is less than y backslash n semi-colon curly brace else print and so forth-- completely unreadable at the end of the day or unmaintainable, especially when the code gets complicated. But whitespace does not tend to matter to the computer, but it does matter to the human. And as you're alluding to in some languages,

it's actually conventional to do this, where you actually keep the curly brace on the same line. And indeed, you might see textbooks do this as well. Some people will even do this. These are all long story short matters of style. In CS50, in the earliest weeks of the class, we're going to insist that everyone follow the same style so that we have some basis for comparison. But eventually, this is the kind of thing that, like in your own English writing or whatever language you tend to write in, you have your own stylistic or linguistic flair to it. Code has that as well. Other questions? Yeah. AUDIENCE: When you establish the counter-variable, do you always have to say what it is equal to, or can you just say int counter section? DAVID: Really good question. When you declare a variable, create a variable, do you have to set it equal to something right away? Short answer, no. And we'll see examples of that before long, where you can actually

say give me a variable called counter, but don't actually set it equal to some value. Come back to that in a bit. So what if we want to add this logic? Frankly, in Scratch it's starting to look a little overwhelming. But this is just a three way fork in the road. If x is less than y, say so, else if x is greater than y, say so, else if x equals y, then go ahead and say they're equal. And in C, we can do this translation pretty directly as well. In fact, now the first eight lines of code

are identical to before except this middle one here where I'm adding a second Boolean expression. Is x greater than y? And then I have this third condition, else if x equals y. But there seems to be a typo perhaps or something anomalous here. So anything jump out? Yeah. I have a double equal sign, which maybe is just a typographical error on my part, but turns out it's not. This is deliberate. But why? This seems like our first example of where Scratch doesn't really map perfectly to C?

AUDIENCE: Well, because the equal sign is like an assignment. And so counting the equal sign actively sets it equal-- DAVID: Exactly. We already a moment ago decided as humans-- or really, years ago-- equals is actually in the context of C going to be assignment-- copy the value from the right to the value on the left. And so we kind of painted ourselves into a corner. We still as humans, as programmers, want to be able to express the notion of equality and comparing. But if we've already used the equal sign for assignment, we need another pattern of symbols to represent equality. And as it turns out, humans just chose two equal signs instead-- so slightly different from Scratch. The reason Scratch does it this way is because you don't really want to have to get into those weeds certainly when the target audience is 8-year-olds just learning to program in the first place. It's not important nor is it really important for us.

But for us there's going to be a logical difference because, if we use the wrong one, the behavior is going to be wrong. If we had just one equal sign, we would literally be changing x to equal y rather than just comparing it. Was there a hand in here? Yeah. AUDIENCE: Just a quick question. So if you wanted to express greater than or equal to, would you write equal and greater than? DAVID: Good question. If you wanted to express greater than or equal to, how might you do that? It turns out there are ways to do that. And if I go ahead and just give myself someplace to draw here for a moment, you can actually indeed do less than or equal or greater than or equal. There's no way on a typical keyboard to put them atop each other like you might recall for math. You just put them next to each other.

Well, it depends. I want the double equal sign here because I want to explicitly check this third case and say x is equal to y. So that was my goal. But logically, this is not necessary. Let's make the program a little better designed. How many possible cases are there when comparing two integers, x and y, for greater than, less than, or equality? Well, I kinda of just answered the question, didn't I? Three. Excellent! There's three scenarios there-- x is either less than or greater than or equal to. And I'm hard pressed to think of a fourth. So do I need this amount of specificity? What could I do to give myself a slight optimization, improve the code just a little bit just to save myself a little bit of time writing it and maybe even the computer a little time running it? Yeah. AUDIENCE: You don't need the last condition. DAVID: Yeah, I don't need the last condition because, if we all agree logically that either x is less than y or greater than y

or maybe equal to y, well, if there's only a third and final case that can just be my so-called else. Just make that be the so-called default case. And in fact, even though this is what most people would call an over optimization, you are saving the computer some time. Because suppose that x does in fact equal y and they're both the value number 1. So is 1 less than 1 when this line of code is executed? Yes or no? No, obviously not. 1 is not less than 1. So this code does not execute. But the Boolean expression is evaluated, so to speak. The question is asked. Is 1 greater than 1? No, and so this code is not executed, but this Boolean expression is. So we just spent another step or second or however fast the computer is. Is 1 equal to 1? Yeah, it is. So this actually prints. But to your point, you don't need to ask that question. And in fact, you just increased by a factor of 50% how many questions you're asking. So you just wasted a little bit of time.

Now as an aside, our Macs and PCs and phones these days, I mean, again, they're operating at like a gigahertz speed, one billion things per second. So in practice, who cares if you're asking that third question? And frankly, if it makes your code more readable or to your teaching fellow or to a colleague or friend who's working on the program for you, then that's great. If it's more clear from the code what's going on, leave it that way. But these are the kinds of design decisions that we'll now make. And arguably this version of the scratch program and this version of the C code is just a little better designed because why write more code than you need to express the exact same idea. So what about this? This was a loop in Scratch. This was an infinite loop because it was just forever saying hello world. Now in C, this gets a little less directly translated. It turns out c uses the key word while.

So there is no forever keyword in C, but there is the word while. And of course, I'm going to use my curly braces-- curly braces, curly brackets to encompass the following lines of code. The line of code I want in there is just another printf. So that's the exact same as before, but it's not sufficient to just say while. It turns out that while wants you to ask it a question every time the loop executes. And it's going to check that question. And if the answer is yes, it's going to run the loop. But if the answer being asked in C is ever no or false, it's going to not execute the code and it's just going to move on to any further lines of code lower down in the file. So in C, you actually need a pair parentheses after the keyword while. And then you need to ask a question. You need to ask a question like, is x less than y or a question like is x greater than y or is x equal to y. But none of those scenarios apply because the whole purpose

of this Scratch block is literally to do something forever. So what's a question we could ask to which the answer is surely true? Does 1 equal 1? We could contrive an arbitrary but very met mathematically correct scenario. We can just say just 1 equal equal 1. But it turns out you can be even more succinct because in C there's a couple of keywords, one of which is true, one of which is false. And the word true is by definition always true, and the word false is by definition always false. So you don't need to contrive some arbitrary but correct idea of does 1 equal equal 1 or does 50 equal equal 50.

You don't need to just come up with some arbitrary solution. You can literally just say true because that key word true never changes value. So even though this is a little weird looking, it's how you induce something to happen forever. You asked the same question again and assume that the question always has the same answer of true. Any questions on that one? Yeah, in the back. AUDIENCE: Do spaces matter? Can you take out the space between y and 0? DAVID: Good question. Do spaces matter? Short answer, no, not in this case. You can in fact delete all of the space here except for the one in the English phrase, and it would still be functionally correct. You can even add spaces anywhere you want. You can make this taller by hitting Enter a bunch of times, tabs, spaces around the word true. All of the examples I"ll show here today and you'll see in the coming weeks are the better way to do things because they're more readable. But again, as you get more comfortable with code

or if you're coming in with some prior experience, you might already have your own opinions. And frankly, this is just a religious debate among programmers, which is the right way to write your code. And that's fine. Once you get comfy, so long as you're consistent is the most important thing. You don't need to adhere to one person's or the other. So how does this code work logically? Well, the first thing the computer, your Mac or PC or your phone or whatever is going to do, it's going to ask the question. Well true. Well, true is always true. So it's going to proceed to execute the line of code. But after it does, because that's the entirety of the code that's in between the curly braces, we could have more lines. These are just short programs. The computer is going to check, OK, is true still true. Yes. So it's going to execute it again. Then it's going to ask the question again. Is true still true?

Yes, so it's going to execute the code again, and this is going to repeat literally forever. But what if you don't want to repeat something forever? What if you only want to repeat it 50 times? Scratch doesn't make you think very hard about this. People just figure out how to keep track of 1, 2, 3, 4, 5, and all the way up to 50 and then stop. That's nice. It makes it easy to use the block. C and a lot of languages aren't quite that user friendly. You will see later in the semester that newer languages are a little closer to what Scratch offers. But in C, we need to be more explicit, but this is a chance to use some of these more primitive building blocks. In C, the equivalent of repeat is going to be the proposition for just because, for now. And then, just as before, if we want to do something again and again within this loop, we're going to use the curly braces, similar to the little orange block there. And then what am I going to do?

I'm going to do this every time, 50 times hopefully, print out hello world. So now I just need to figure out and see how to express the number of times specifically 50. So it turns out in C-- use parentheses again-- this is going to be a pretty common characteristic of a lot of the code we write. And then you need to do three things. The burden is now going to be on us the programmer to keep track of how many times we want to execute this code to how many times we've already executed this code and then constantly make sure that one does not exceed the other. So we stop once we hit 50. So what's the fundamental construct that we use to keep track of anything in a program? A counter, which was an example of a variable. So we just need to use a variable. Now it's actually going to be inside of the parentheses this time. So it's not on its own as it was just a bit ago, but the syntax is the same.

I could call it counter, but the reality is that the convention in programming is just to use shorter variables when you're just doing something mundane. And if all you're doing is looping-- i stands for integer, is sort of many programmers' go-to variable name rather than the more verbose but correct counter or whatever. So this says, hey, computer, give me a variable called i. Let me store integers or ints in it and set the initial value to 0. Why? Well, almost everyone in this room probably starts counting from 1. Computers just tend to start counting from 0. But why? What's the rationale for starting to count from 0 perhaps based on last week?

Why does that kind of makes sense? Yeah, what do you think? AUDIENCE: Well, because it's ones and zeros, and it's binary. DAVID: Yeah, it's just ones and zeros, and what's the smallest number, negative values aside, that you can represent in binary? Well, it's just 0, 0, 0, a bunch of zeros. So why would you waste that representation, that permutation of bits? Let's just start counting at 0 and then add to that. So you can start counting from 1 in C, but the convention in most languages is count from 0. So we'll get off on that foot as well. And you might recall even that in our PBJ, for the peanut butter and jelly-- not for the PDJ code-- for the phone pseudo code, I actually deliberately started numbering the lines from 0 to 1 to 2 for that same intuition. So here's how you then say to the computer check, if you would, whether i is less than 50. Now, initially it's obviously going to be less than 50 because zero is less than 50 but that same condition is

going to be checked again and again and again as this loop executes. And then recall from before, we can just plus plus a variable to add 1 to it. We can do this more verbosely. We could say i equals i plus 1, but it's just more conventional to write i plus plus just to say the same thing more tersely. So what happens next logically? That's the code I've written. What does the computer do with it? Well, it initialises i to 0 and prepare to store integers in it. It checks the condition just in case you initialized it too big of a value. You might not want the loop to execute at all. But obviously 0 is less than 50. So this line of code executes. Take a guess as to what happens next. Yeah, you probably want to do i plus plus because you're done executing all the lines of code in between the curly braces, even though there's just one. So let's go ahead and increment i. So i is now 1. Let's now make sure-- is 1 less than 50? Obviously. Execute the code.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesContent