Free Essay

Cs 50

In:

Submitted By BanananaBa
Words 17436
Pages 70
Week 1.1 (Monday)
ENGLISH ORIGINAL TEXT УКРАЇНСЬКИЙ ПЕРЕКЛАД DAVID J. MALAN: So this is CS50. And this was CS50's own Colton Ogden, for more of who's music you can download at soundcloud.com/cs50. So today we focus all the more on the art of programming. And we take where we left off last week, focusing on Scratch, which was this graphical programming language. And take things down to a lower level, using a more traditional programming language known as C. But along the way, realizing that the same ideas we talked about last Friday will recur not only in this language C, but in most every other that we look at this semester. So we called this thing here what last time? This is representative of a statement. So we called this a statement. And it does something. It's an instruction that a computer or Scratch might execute. And henceforth, let's also start calling something like this a function, for reasons we shall soon see. Meanwhile, we saw things like this. And these are generally known as what construct? AUDIENCE: Loop. DAVID J. MALAN: So a loop. So pretty straightforward. It literally does what it says. And in Scratch, if you want to cram more puzzle pieces in there, the piece will grow to fit it. And we'll see in C that we can do the same thing. Another type of loop, though, in Scratch might be forever, or there's any number of other approaches. But let's take a more generalist look, with a face that's likely quite familiar, at loops more generally. MARK ZUCKERBERG: One thing that computers are really good at is repeating commands. As a person, you'd get really bored if you had to do the same thing lots of times in a row. But a computer can do the same thing millions or even billions of times, and not get bored, and be able to carry that out really well. So for example, if I wanted to wish everyone on Facebook a happy birthday by sending them an email, it might take me more than a century to actually write out all of those emails to everyone. But with just a few lines of code, I can have a system send an email to everyone on Facebook wishing them a happy birthday. So that's what loops are and why they're valuable and something that computers can do very well. DAVID J. MALAN: So if you've been the recipient of some of CS50's and Dropbox's space of late, that's actually precisely what we do, using code quite like that.We essentially have a big spreadsheet into which folks have been inputting their names and email addresses. And we wrote a tiny bit of code that can iterate over those addresses and spit out unique addresses in case anyone submitted multiple times. And thereafter, we send an automated email from CS50's bot, including the coupon code. Now we also looked at this construct last time. And this is a particular example of what? So, yeah, a Boolean expression. And the shape is meant to capture that as well. All such questions of the form true or false in Scratch will look a little something like this. And we call this a Boolean expression. That's indeed true or false, yes or no. It's a way of answering a question. And Meanwhile you can use these Boolean expressions inside of constructs like these, which of course are conditions or branches, proverbial forks in the road. And they can look not only like this, but they can also have elses associated with them. And you can actually have a three way fork in the road or a four way fork in the road, simply by nesting these things, as you'll see in Scratch if you haven't already. And as you can do in C as well. Let's take another generalist look at an alumnist, as well, who might present a different approach to these things called conditions. BILL GATES: People make decisions every day. For example, before you go outside you kind of have an if statement that says, if it's raining then I need to get my jacket. And computers are amazing once you decide those kinds of statements, that they can reliably execute those things at unbelievable speed. And so a computer program really is a little bit of math and some if statements where the decision gets made. DAVID J. MALAN: So as you may know, it was folks like Bill Gates, Paul Allen, and others that truly kicked off the so-called personal computer revolution some years ago. I thought, before we dive into some administrivia, we'd relate a tale from the Albuquerque, New Mexico museum of Natural History and science where some of Bill Gates' and Paul Allen's earliest stories are recounted how we have now today's PCs and Macs and more. For this, though, we need two volunteers who have very good narration voices to read a script aloud. All right, how about in back there. Come on up. And how about in front here. Come on down. Take your places here. As you guys come up, a couple of administrative announcements. sectioning, the process of choosing a section, will start this Wednesday through Friday. More on that this coming Wednesday in lecture. Super sections, meanwhile, are something that we offer next week whereby the entire class is invited to participate in fairly large scale sections, one more comfy, one less comfortable. And we will announce the particulars of that, as well, later this week. Meanwhile sections, themselves, will start in week three of the course, zero index, which means those are a couple of weeks out. So not to worry. You have not yet missed anything along those lines. Meanwhile in the meantime, if you have any questions administratively, email myself and Devon and Gabe and Rob at this address here. Lastly, problem set 0 is, of course, out. You may have noticed it on the course's website. It should provide you with all answers to questions you might have along the way for getting started with the problem set. But if you find yourself in need of a helping hand, by all means attend office hours, Monday, Tuesday, Wednesday, Thursday of this week in the evening in four dining halls. See that URL there for the particulars of where office hours shall be. Now Let's meet our two guests here today. What's your name? JAY PAUL: Jay Paul. DAVID J. MALAN: Jay Paul, nice to meet you. HIKARI: Hikari. DAVID J. MALAN: Hikari? HIKARI: Hikari. DAVID J. MALAN: Hikari. Nice to meet you as well. Jay Paul and Hikari have in front of them on these music stands two scripts that I printed out this morning from the New Mexico museum of Natural History and Science. And what I thought I'd do on the overhead is accompany your recitation of the script and this history with some visual images, no surprises. And what I've done in advance is prehighlight on your script what you should read, and what you should read. And we'll essentially just alternate paragraphs. So it's much like you might have done in English class. That's really compel the audience to believe in your tale here. Shall we? So the story here is, we have a BASIC, and it begins in Cambridge. JAY PAUL: It was winter, 1974, in Cambridge, Massachusetts where winters can be cold. A bearded, long haired college dropout named Paul Allen was trudging across Harvard Square, absorbed in his thoughts. His main preoccupation in those days was how to get his friend, Bill Gates, to quit school and go into business with him. HIKARI: The two had already gone through a number of business ventures together, beginning at Lakeside school in Seattle where they were paid in free computer time to test a PDP-10 computer at a local time sharing company. The most recent plan had been to quit school and form a software company. Allen had left Washington State University. But at the last minute, Gates decided to stick with Harvard. JAY PAUL: That day, crossing Harvard Square, Allen spotted the January, 1975 issue of Popular Electronics with the earth stopping headline, World's First Minicomputer Kit to Rival Commercial Models. Beneath the headline was a picture of a small box adorned with lights and switches. It was called the MITS Altair 8800. And Allen knew this was what he had been looking for. HIKARI: Days of discussion followed. Allen and Gates understood the significance of the Altair. They had talked often about microprocessors and were waiting to see what would be done with them. Now there was a minicomputer kit on the cover of Popular Electronics. It apparently had no software yet. They imagined a nation of programmers descending on MITS. And so they called Ed Roberts, the head of the company, claiming to have a version of the BASIC programming language almost ready for the Altair. They didn't. And Roberts must have known they didn't. He was getting 10 calls a day from people who had a BASIC almost ready. And his stock response was, "The first person who shows up with a working BASIC gets the contract." JAY PAUL: Gates and Allen had never seen an Altair. They had never even seen the Intel 8080 microprocessor at the heart of the Altair. But a couple of years earlier Allen had written a program on a mainframe computer that emulated the operation of a previous Intel microprocessor. And this time around they would do the same thing. HIKARI: With an Intel 8080 manual at his side, Allen sat down at a Harvard PDP-10 computer and wrote the emulator and software tools necessary to do the programming. Meanwhile Gates stopped going to classes and devoted himself to designing the BASIC, using every trick he knew to get the size down below 4 kilobytes. JAY PAUL: Out in Albuquerque, Ed Roberts got a call from Gates asking for details about how the Altair handled specific routines. No one had ever asked that before. And Roberts began to get interested. HIKARI: With the development tools and the design ready, Gates and Allen wrote the code on the PDP-10, enlisting another Harvard student, Monte Davidoff, to write math routines. After a final night of programming, Allen got on a plane to deliver their BASIC to MITS. He spent the plane ride out worrying. And back in Cambridge Gates was worrying. They had tested their BASIC and it had worked on the emulator. But what if the emulator was wrong? JAY PAUL: As the plane approached Albuquerque, Allen realized that their BASIC, now neatly contained on a small roll of punched paper tape, would be useless without a separate program, called a loader, that would tell the Altair how to read the paper tape being fed into the teletype machine. He took out his notebook and quickly scribbled down a loader program in Assembly language, then manually translated that into the 1s and 0s the Altair would understand. HIKARI: Allen was expecting a clean, little, high tech company run by men in business suits. So he was surprised when Roberts met him at the airport looking like a ranch hand. Roberts was also surprised. When he dropped the Harvard programmer at an expensive hotel, Allen had to confess that he couldn't afford the room. JAY PAUL: MITS, itself, was located in a dusty strip mall. Inside on a cluttered workbench was an Altair loaded up with 5 kilobytes of memory and connected by a cable to a teletype machine. Roberts and Chief Engineer, Bill Yates, waited expectantly as Allen toggled his loader program into the Altair. The teletype began chugging as it pulled the paper tape through the tape reader. It took perhaps 15 minutes to load the program. Then the teletype abruptly printed a memory prompt, then a ready prompt, and Allen began typing a few test commands. To everyone's amazement, the software worked. There were bugs, of course. But the main thing was it worked. HIKARI: Later, on their way to a $3.00 lunch at Pancho's, a wasp flew in the window of the pickup truck and stung Allen on the arm. But at that point nothing could spoil the mood. The Altair now had its BASIC, the first commercial software for a home computer, made by Paul Allen and Bill Gates, doing business as Microsoft. DAVID J. MALAN: Many thanks to our two readers. [APPLAUSE] DAVID J. MALAN: Now you have your choice, before you leave, of a sparkly or a glow in the dark-- oh, wait one sec, wait-- sparkly and a glow in the dark elephant from CS50's own Cheng Gong. HIKARI: Aw, thank you. DAVID J. MALAN: All right, thank you so much. [APPLAUSE] DAVID J. MALAN: So true story. This is to say that all of these machines and the ease with which we use them now and take for granted, really started here, just a few paces from this actual theater. And now today, if you've not been, this is Maxwell Dworkin, the computer sciences building, also around the corner. And on the second floor of this building does hang three pages from the original source code that Bill Gates and Paul Allen wrote. In fact, if use you zoom in you can see not only their names in the original type, but also their signatures that they adorned a few years back when they last visited. But what was particularly compelling about this is what they set out to do was to write a program that would enable other people to write their own programs. At the time all there was with this Altair machine made by MITS. And all they needed was some way of making it easy for hobbyists and people like us in this room to actually program that without necessarily understanding Assembly code, or machine code, or God forbid, 0s and 1s. We programmers, like those in this room, we want to be able to express ourselves much more like pseudo code even if it's a bit more nit picky than we talked last week. We don't want to write code like this, which Paul Allen and Bill Gates did. We, instead, want to write code that looks a little more user friendly. Now this is a language known as BASIC. And the line numbers there are what you use to simply number the lines of code that you're writing. We don't even have to do that these days. But you can see here how PRINT "hello, world" would indeed presumably print just that. And so what Bill and Paul did was empower people to write code like this instead of-- if you take a look at the computer science wall-- code like this. In fact, CS50 recently had an opportunity to sit down with Professor Harry Lewis in the Computer Science department, who actually taught Bill Gates some years ago, and is standing here before those three pages of excerpts. Let's take a look. HARRY LEWIS: What you have here is a listing of an early piece of software written by Bill Gates and Paul Allen, the founders of Microsoft. So the code is interesting for two reasons. First of all, it became Microsoft's first product, which was an interpreter for the BASIC programming language. And secondly, this was one of the first attempts to create an interpreter so ordinary people could use personal computers. So Bill Gates was an undergraduate at Harvard. I started teaching at Harvard in 1974. This was done in 1975. So it was early in his career and early in my career. I actually taught Bill in a course around this time. Paul Allen was not a Harvard student, but he had been a high school classmate of Bill Gates. If you come and look at the listing, you'll actually find a third name, Monte Davidoff, who was Gates's classmate here at Harvard. OK, so here's an interesting comment up here. It says "In 4K can delete square root but for loops should still work." OK, so what that means is that there were two ways to compile this program. One was to run on a version of this Altair computer that only had 4K words of memory, 4,096 words of memory. But the big version had 8K. And so what this says is that in the 4K version you had to delete some code to make it fit. And one of the things that would be deleted would be the square root routine. But apparently the for loops should still work even when you're compiling down for just the 4K version of the computer. DAVID J. MALAN: So one of the themes, as we'll see in computer science, is this notion of layering and abstraction, and really standing on the shoulders of folks who have come before us, not unlike some of the Bill Gates and Paul Allen narrative here. And what this means is that today we can take for granted that things are actually easier for us to write code. Indeed code, as we said on Friday, is more technically known as source code. And it's this English like syntax that's more proper and more well defined than something like pseudo code, for which there is no formal definition. And today what we're going to focus on is source code that looks like this, which admittedly at first glance looks completely cryptic. And frankly, it's way more aesthetically complex than the underlying program is. All this program does, recall, is what did we say? It just prints "hello world." And yet look at all of the stuff we need to wrap around that very simple phrase. But before long all of these lines and more will make much better sense to you. And the flow is as follows. What we need at our disposal is to take code, like source code that we just saw. And we need a new program to run it through. We need algorithms that can convert source code, like this, into object code, 0s and 1s. In other words, what we're going to learn today is how to do this, write source code up top, pass it as input to a special program known as a compiler, and we're going to produce object code. Which is just a fancy way of saying we will take something that looks like this, pass it into a program called a compiler, producing object code that looks like this. So these are literally the patterns of 0s and 1s that are understood by an Intel computer these days, that if interpreted by the CPU, the brains inside of a computer, will literally print out, quite simply, "hello world." Now there's way more 0s and 1s than you would hope might be necessary for that. But that's because we're building on a good deal of complexity that we can henceforth take for granted. In other words, a lot of smart people have given us a lot of cool tools and powerful software with which we can now make projects of our own. So let's get started. Whereas last Friday, and for Problem Set 0 this week, you'll be playing in a world that looks like this. Starting today and for Problem Set 1 next week, the code is going to look a little more cryptic, but functionally is going to be the same. So notice, top is Scratch, bottom is C. Frankly Scratch is a lot more user friendly and accessible. But if you now compare visually top to bottom, there's kind of a one to one correspondence between the puzzle pieces and the language we're about to play with. In particular, say, the blue puzzle piece up top, is apparently equivalent to what keyword or special phrase in this language called C? AUDIENCE: Printf. DAVID J. MALAN: Printf. That means formatted printing. And that's just a fancy way of saying printf in C is going to be a statement or a function that prints something to the screen. What does it print to the screen? Whatever you tell it to inside of quotes, inside of parentheses. So again, admittedly, there's a lot of stuff that you have to keep in mind, parentheses, quotes, semicolons, and all of this. But all of that is sort of beside the point. The interesting takeaway for now is that the say block in Scratch is pretty much equivalent to the printf statement in C. Meanwhile, the yellow puzzle piece up top, when green flag clicked, is probably equivalent to what keyword here? AUDIENCE: Main. DAVID J. MALAN: So main. Maybe int, maybe void. But main kind of sounds like it's important, and indeed it is. So when green flag clicked is, again, the puzzle piece that kicks off an entire Scratch program. But we are going to now start calling that main, this function known as main. Now meanwhile we'll generalize this as follows. We might call say a function. And it might look specifically like this. Well, what about loops? If we want to start converting or translating more in Scratch to C, this thing here apparently just says "hello world" forever. So if you associate these scripts with a cat in Scratch, it's just going to keep saying in some kind of cartoon bubble, "hello world, hello world, hello world," ad nauseum, forever. If we want to do something similar in C, it's going to look a little cryptic. But we can achieve the same results, as we'll eventually find out, with syntax like this. I'm going to use printf again, because at the end of the day I want to print "hello world." And I'm apparently using a keyword that isn't forever. It's instead the word while. But just semantically in English, while kind of suggests some kind of loop or cycle. So that happens to be the keyword that C uses. And while true, why does while true effectively mean forever? Well, while, as we'll soon appreciate all the more, has this parenthetical next to it where you can put a Boolean expression. And so long as that expression is true, this code, as denoted between these two curly braces as we'll call them, will just keep running again and again. So true is true. So while true means just do this forever. It's almost a stupid construct to express yourself. But there was no forever keyword in C. There was while. And there was a very simple Boolean expression like true. And so this, we'll see, achieves the same result. How else might you implement a loop? Well, in Scratch you might hard code a specific number of iterations in the loop here. And so that's exactly what we might do in this version of C, whereby we have a so-called for loop. And the for loop here is going to iterate, somewhat cryptically, from the value 0 on up to but less than 10. Now variables in Scratch. You might not have had occasion to use these. But what's the point, in general, of a variable did we say last week? What's that? AUDIENCE: Points. DAVID J. MALAN: To point? Oh, points. OK, keeping track of points, for instance, in a game. Or more generally doing what with the variable? What's the utility of them? AUDIENCE: Memory. DAVID J. MALAN: Yeah, so memory. It's for storing something. And the sort of silly visual I used last time was like this glass bowl. And if we wanted to store something inside of a variable, for instance right now the value is six because there are six ping pong balls in here. It's just some kind of storage container that underneath the hood is implemented with bits, 0s and 1s, however a computer happens to do that. So in Scratch, if we want to have a variable, we can use an orange block like this. We'll call that counter in this particular case. I initialized it to 0. And what it I then do? Forever, say counter, which if you play with that in Scratch, you'll just see Scratch. The cat or whatever costume you put on him will speak the number in question. Change counter by 1 is like incrementing by 1. And so this is going to count from what so what? From 0 til infinity, or until Scratch breaks, or until you sort of lose interest in watching how high he can actually count. So how might we convert this to C? It's going to look a little cryptic. But again, if you look at each of these lines individually they kind of lineup generally. So apparently int is going to have some special meaning in C. We'll see that again. As an aside it means integer. So it just means number. So that's the type of glass bowl I want, one that can store numbers, not ping pong balls. And I'm going to use the equal sign there to assign it a value of 0. So that's quite like set counter to 0, but in C. Meanwhile, while true, that was equivalent, of course, to forever, even though it's a little cryptic, and then inside of the curly braces. And you can think of these curly braces, which you can type on your keyboard, as really being like the curvature in these yellow loop blocks in Scratch. It embraces multiple lines of code. Printf is getting a little scary now because I see not only quotes in parentheses. But what else is new syntactically in this example? There's a percent d. And then backslash n is there. We did see that before, even though I didn't mention it. Then there's a comma. And then there's a counter. But we'll see in just a moment that this is just a standard way of saying print a "decimal number," quote, unquote, some decimal number. But I'm going to tell you later what that decimal number is. So the fact that there's a comma in this line saying printf, means go ahead and print some decimal number. Oh, and by the way, the number is whatever the value of this variable is. And so to make this more clear, we'll see an example before long involving exactly printf in the context of real C programs. Now just to wrap up some of these constructs. Boolean expressions, you might not have occasion to use these in your program but you might very well, especially if using conditions. And so these two examples from Scratch mean if x is less than y, or if x is less than y and y is less than z, how might we translate that? Well, in C it's just going to look like this. A little cryptic, more parentheses, some weird ampersands, but fundamentally the ideas are as simple as they are in the puzzle piece world. We're simply checking if something is less than something else. How about conditions? In a nutshell in English, what does this chunk of Scratch code do would you say? AUDIENCE: Compares two numbers. DAVID J. MALAN: Compares two numbers, and if x is less than y it says as much. If x is greater than y it says as much, else if x is equal to y it says as much. Now where did x and y come from? Who knows. This chunk of Scratch code is out of context. But what we want to do now is translate this for just a moment to C. So as you get comfortable this week in Problem Set 0 playing in this world on the left, realize that the ideas aren't changing this week or next or beyond. We're simply going to start writing things in a different way with our keyboard instead of our mouse. So if x is less than y, and there's some parentheses there, then there's some curly braces again to kind of encapsulate it just like the yellow puzzle pieces do. And I'm going to printf x is less than y and so forth. What is nice about C, as you can see here, is that you don't get this nesting, nesting, nesting that's necessarily going to push your code to the right. You can instead have everything lineup neatly like this. But that's just an aesthetic detail we'll see again before long. All right. So that brings us back to this cryptic looking program. Let's actually write some code. Now how do you go about writing code? All these years that you've owned a Mac or PC, desktop or laptop, you've actually had the capability to start writing programming code. But you're probably missing a special type of program. You can certainly write code. But you can't necessarily, out of the box, convert that source code into object code, 0s and 1s without what on your computer? AUDIENCE: Compiler. DAVID J. MALAN: So a compiler, right. Now most of you probably don't own a compiler, have never downloaded a compiler. But you'll see you can download it like most any other piece of software. In the world of Mac OS, you might download or have downloaded already something called Xcode or GCC or Clang. If you come from the Windows world you might have downloaded Visual Studio, Visual Basic, environments like that. There's dozens of compilers these days that you might use. But the short of it here is that it would be a pain and, frankly, a technological nightmare for hundreds of people with different computer configurations to all configure their machines in exactly the same way so that we can all be on the same page. So what we, instead, do in CS50 is we give you a standard environment, a Linux environment that's going to look a little something like this. You'll see more of this in the Problem Set 1 specification which will go online this Friday night. And what this means is that you henceforth are going to be able to download and install a program called the CS50 Appliance. And you're going to download and install another program called a hypervisor, which is just a fancy way of achieving this. Whether you own a Mac or PC or a Linux computer or a Solaris computer, or whatever crazy operating system you're running, you're going to download a program called the hypervisor that's going to run the CS50 Appliance on your computer no matter what your operating system is. A hypervisor in other words converts our stuff to whatever language, whatever instructions your own computer understands. So this is a layering. And again, this is kind of thematic in computer science, the building on top of things. You might have Windows. You might have Mac OS. But starting next week you're going to have downloaded a free piece of software called the hypervisor. You're going to have downloaded a piece of software called the CS50 Appliance. That's going to run in the hypervisor, which is going to run on your computer. And the end result is that all of us will have a simple window like this on your Mac or PC that gives us the illusion of all running the same operating system, without any other impact on your computer. And you can full screen it and essentially behave as though you are running an operating system called Linux, which is what the CS50 Appliance is based on. So let's actually use this now to write a program. You can write a program using Microsoft Word. You can write a program using TextEdit, or Notepad, or WordPad, or pretty much any word processing program you've ever used. But the reality is you shouldn't use really any of those programs. You certainly shouldn't use something like Microsoft Word, which has bold facing and italics, and bigger fonts and smaller fonts, because the computer doesn't care about any of that. All the computer is going to care about is English like instructions written in C. So what we'll do inside of the CS50 Appliance is use a program freely available, and it's pre-installed in this appliance, called Gedit. And Gedit is just a super simple text editor like Mac OS's TextEdit, like Windows Notepad that's going to look a little something like this. So let's actually not look at slides of this. But let's actually go into the environment itself. I'm going to go ahead and log in, in this other window, to my CS50 Appliance, which I've pre-installed on my laptop here. Notice that, like Windows and Mac OS, it's got some menus. Like Windows it puts it down there instead of Mac OS, which puts it down there. But the reality is it's all kind of the same. And in here is a whole bunch of software. There's Dropbox. There's a whole bunch of accessories, graphical programs that we'll use later in the term for problem sets. There's a web browser built in so that this is a full fledged computer inside of a computer. But I'm going to click this leftmost white icon here, which is the icon for Gedit. And it's going to open a window that has three panels to it, a left one, a top one, and a bottom one. Now it's in this top right one that I'm going to actually write some code. So let's do this,. I'm going to go to File, Save. And you might not ever have seen this particular window before. But this is like Mac OS or Windows. It's just a window with all of the folders that I have inside of this computer. And I'm going to save the file as hello.c. And I'm going to go ahead and click Save. And now notice I have a tab at top left called hello.c. So probably pretty familiar even if you've not used this particular program before. And now I'm going to type in those fairly cryptic sequence of commands that we saw a moment ago. Include, standard I/O.h. More on that soon. Int main void, open curly brace, closed curly brace. And then inside of there I think is where we had "hello world," semicolon. And now save. So this is a program written in C, written, therefore, in source code. But I can't just run this program. I kind of want to double click on an icon somewhere, but no icon exists other than the source code file. What, again, is the process now that I need to run this file through? AUDIENCE: Compiler. DAVID J. MALAN: So a compiler. So in different computers you do this in different ways. But what we've done here in the CS50 Appliance that's representative of how you might do this on many different systems, is I'm simply going to run a command called make. And make is literally going to do that. Make me a program. So make is going to run a compiler for me. And the name of the program I want to make is hello. Now make is a program. And make is smart enough to realize that if I say make hello, it's going to look automatically for a file called hello.c just because that's the way it's configured. So when I now hit Enter here, this crazy cryptic line just got executed. And trust me, before long, within just days, you'll understand what all of that nonsense means. But for now, just know that make triggered execution of a compiler. In other words, it found a compiler on my computer that's pre-installed on the CS50 Appliance that we'll hand to you in Problem Set 1. And it then took hello.c as input, and produced apparently 0s and 1s as output. And by default what it does is it saves those 0s and 1s in a file called hello. And though this syntax too might be new to you, simply by saying dot slash hello is going to be the means by which I run this program. For now and for at least a couple of weeks, almost all of the programs we write are going to be in black and white text windows. No mice, no clicking, no windows, no icons. We're going to keep it simple and focus on the underlying ideas initially before we get to something higher level, for instance, like the break out game that we talked about in the first lecture last week. So when I hit Enter here, it's equivalent in a text only environment to double clicking an icon called hello. What do you expect will happen when I hit Enter then? AUDIENCE: It'll print "hello world." DAVID J. MALAN: Hopefully it will print "hello world." And indeed it did. Now there's been some cryptic syntax here. Let's rewind for just a moment and see if we can't start inferring just by tinkering, trying and failing, as to what's going on here. What if I get rid of the backslash n? Now some of you who've programmed before probably know instantly what that means. But for those of you who've never programmed before, at least think to yourself what is going to change when I rerun this program? So I'm going to go back down to my little black and white window, which is the window in which I can compile this. I'm going to recompile hello. We're going to see the same cryptic sequence of commands. And I'm going to do dot slash hello. And now someone, if you would, who's never programmed before, what might be different this time? Yeah. AUDIENCE: It won't stop printing "hello world." DAVID J. MALAN: It's going to-- sorry? AUDIENCE: It won't stop printing it? DAVID J. MALAN: It won't stop printing "hello world." So not a bad idea. Other ideas? Yeah. AUDIENCE: Error message? DAVID J. MALAN: Error message, OK, could be. What else? AUDIENCE: It might print the bracket with the semicolon as well? DAVID J. MALAN: Might print the bracket with the semicolon as well. So maybe that backslash then is some kind of terminous that's important. Any other thoughts? So all good ideas. And in fact, it's going to be an error message. That's probably most likely to be the answer in general for the next few weeks as we learn to code here. But for now remember that computers only do what you tell them to do. Much like the ridiculous peanut butter and jelly example. Our human computers were only supposed to do what you told them to do. So in this case, if you don't tell the computer to move that blinking cursor to the next line, it's not going to do it. So when I run this program now, notice the difference. Looks like a bug. It's an aesthetic bug, perhaps. But what is different about this output versus the last one obviously? Yeah. AUDIENCE: It didn't do a new line. DAVID J. MALAN: It didn't do a new line. Now those of you who have maybe made web pages before, you might know of the BR tag or the paragraph tag, very similar in spirit. A web browser will ignore you until you tell it exactly what to do. Similarly, is a language like C only going to do what you tell it to do. So the reason that all of these examples, thus far, have kind of casually had this backslash in there, that's the means by which you express yourself as a new line character, so to speak. And you can kind of appreciate, perhaps, that this would look kind of stupid if nothing else. If I wanted a new line, just hitting Enter and then kind of butchering the code like that shouldn't really rub you the right way. And even if you don't really care at this point, you will realize that this is not a particularly good looking piece of code. And so what the world decided years ago is that when you want to put the cursor onto a new line explicitly, you must explicitly say new line, backslash n. And there's some other symbols like that. But for now we'll just focus on backslash n. Now let's make the program a little more interesting. I'm going to go ahead and this time open up a new file. I'm going to save this as hello-1.c. And just for kicks, I'm going to go put it into my Dropbox folder. As you'll see in the CS50 documentation for the appliance, later this week for Problem Set 1, we'll encourage you to use Dropbox or some equivalent service, because then all of your code's going to be backed up automatically. And so that's why I've gone into this folder here. And now I'm going to write a slightly different program. Include, standard I/O.h, int main void. And then in here printf, hello world, which is exactly the same as before. But now I want to print something that's a little different. I want to print out, say, "Hello, David." All right, so obviously, it should hopefully be the case that if I recompile this program, rerun it, it's going to say "hello, David." But what if I want to introduce this sort of variable, the notion of a container that's going to store D-a-v-i-d and not hard code it into my program. Well what if I start doing something like this? String s, so this is a variable. If you want a string, a.k.a. a word or a phrase. A sequence of characters is what we in programming call a string. We're just going to generically call it s, because it's a nice simple name. But I could call it anything. I'm going to say string s equals quote unquote, "David," semicolon. And now I want to insert D-a-v-i-d into what I'm printing. And before we saw a teaser on the screen of some special syntax that allowed us to substitute in a value. What was the special symbol a few slides ago? So percent. At the time it was percent d for decimal number. That doesn't really seem relevant here. Turns out there's another percent symbol, which is percent s, which stands for a placeholder for a string. So now, very simply, I'm going to go make hello-1, because this file's called hello-1.c, and hit Enter. And I screwed up. What's going on? Well, here's where we have to begin to appreciate that we're in this command line environment, this text only environment. There's no clicking on icons like folders right now. And think back a moment ago. In what folder did I say I was saving my code? So the Dropbox folder. Could have been called anything. But it happens to be called Dropbox. So I somehow need to double click on that Dropbox folder in order to get into it and get at my code called hello-1.c. In fact, let me go ahead and minimize this window for just a moment. Just like Windows and Mac OS, there are folders in Linux. There are folders in the CS50 Appliance. It's just right now we're confining ourselves to this text environment. But if I double click on Dropbox, notice there is the file that I want to compile. But I need this black and white terminal window, so to speak. But I need, therefore, to move into that folder or directory. So slightly arcane, but you'll get used to this too. In the world of Linux, which again is the operating system we're running inside of the CS50 Appliance, there's a command called CD. Which means I can do CD, space, Dropbox. CD, change directory. Right. Back in the day when people were inventing computers and operating systems like this, they wanted to type the fewest keystrokes possible. So the easiest way to say change directory was CD. So if I hit CD, space Dropbox, notice what has changed here. Inside of parentheses the appliance is kind of humoring me and reminding me where I am. So the open folder is Dropbox. If I now type ls for list, again succinct, because people didn't want to type back in the day l-i-s-t. So they instead made it ls. Enter. Notice I see two things, hello-1.c, and then this cryptic thing, source 1m. That's just my way of saying source code for week 1 Monday. That's a folder I downloaded from CS50's website that I made earlier today and just put it into the appliance in advance. But for now the only thing we care about is making this program. So when I type make hello-1, Enter. Damn it. Something went wrong. So let's tease this apart. And unfortunately this is where things get a little stressful at first, at least if you've never programmed before. My god. I wrote a two line program and I have four lines of errors. So what's going on here. First and foremost always scroll back up and find the first error message, because oftentimes compilers just get confused by what you and I do. Compilers are pretty dumb. They'll only do what you tell them to do. And if you confuse them, they're just going to kind of throw up their hands and maybe throw more error messages than are actually relevant. So let's look at the first. Super cryptic at first. But notice, here's the name of the file in which I screwed up apparently. Colon 5, colon 5 just means on line 5 at the fifth character. So fifth column of characters, if you will, error. Use of undeclared identifier string. Did you mean standard n? No, I meant string. And then it's kind of copying and pasting what I typed to really draw my attention to where I screwed up. So for some reason C, or at least the compiler does not understand the word string. And that's because we made it up. So string does not exist in C. What CS50 does, for the first few weeks only of the class, is we provide some training wheels, so to speak. And we put these training wheels inside of a special file called CS50.h. So this is the second of two file names that apparently end in dot h. Let's rewind. Printf is a statement or function that apparently prints something to the screen. But you didn't see me implement printf, right. Someone years ago implemented printf. In what file would you wager he or she put the implementation for printf, the code for printf? In a file called standard I/O.h. In fact, it's probably in two files, standard I/O.h, which stands for header file, and standard I/O.c, which stands for C source code. So he or she some years ago plopped the code that they wrote into that file so that people like us years later can include it, so to speak, in our own programs. And indeed, that's what the pound sign followed by the word include does. It looks on the local hard drive, finds the file called standard I/O.h, and then effectively copies and pastes it inside of my own file. So now my program knows how to print to the screen. So by that logic, where is string defined? AUDIENCE: CS50.h. DAVID J. MALAN: CS50.h. And indeed, that's what we, the core staff, have done. We've invented a few data types, so to speak, like a string, in addition to ones you get for free, like an int. And we'll see others like a char for a character and a few more. Inside of CS50.h apparently is at least some mention of string. So now let me go ahead and rerun make hello-1. I'll zoom in again and cross my fingers. Now by having made one change I fixed most things. But damn it. More percents than data arguments. What did I do wrong this time? So it's still pretty cryptic. But this error is on line 7 and character 21. So let's go look up here. It's a little subtle. But if you think about what the fundamental ideas here are, perhaps we can tease this apart. So printf is the name of the function. Parentheses, thus far, is just like what we put around the stuff we're passing as inputs to a function. All right, just an arbitrary human convention. Use parentheses. Inside of those parentheses we've been putting double quotes, and then a string like "hello world." But in that earlier example very briefly did we look at with Scratch. And we had the percent d, what else was inside of those parentheses that I called out verbally? Yeah. AUDIENCE: So it's what you're taking [INAUDIBLE] from within [INAUDIBLE] what these [INAUDIBLE]? DAVID J. MALAN: Exactly. So we had the percent d. But then we had close quote, comma, counter. Right. We specified what we want to do as the placeholder. So what I'm going to do here is comma, what do you want me to put? AUDIENCE: S. DAVID J. MALAN: S, because s in this case is the name of the storage container. It's the name of that glass bowl. Whereas before it was counter in that simple Scratch example we looked at. So now having made two changes, let me zoom in and try once more to compile this program. Now I see that cryptic line. But that's actually the name of the compiler. Clang is the name of the compiler. Make is just saving me the headache of ever typing that long crazy command out. So now if I do dot slash hello-1, I should see "hello, David." Pretty underwhelming, though, right? We could have done this a lot more simply without talking about variables and CS50.h and all of that. So let's make it a little more interesting. In addition to CS50.h, having things like string declared, the CS50 library also has a few functions. So just like years ago, someone wrote printf and put it in standard I/O.h and some other file. We, the CS50 staff, wrote a function called GetChar, GetDouble, GetFloat, GetInt, GetLongLong, GetString, and we put those inside a file called CS50.h and CS50.c. And we put them inside of the CS50 Appliance. And people can also download them online if they want to put them on their own computers as well. Which is to say that we have created functions that get input from the user. I don't know what all of these data types are. GetInt is kind of straightforward, like get an integer somehow from the user. And GetString is probably like get a word or a sentence from the user. So let's focus on that. And I'm going to go back into the appliance and I'm going to go ahead and save this file as, let's call it hello-2.c as my second version. And let's make a couple of changes. This time instead of hard coding David, which makes an incredibly consistent but underwhelming program, what if I instead do GetString? Now notice GetString has an open parenthesis, closed parenthesis, because it doesn't need any input. It's just going to go get a string from the user. And now a word on other syntax. Semicolons just end a line of code. You don't need them everywhere. But that just means I'm done with this line of code. Let me move onto another statement or function. String declares a variable. String is like saying give me a bowl, please. And let me put a string in it. And now the equal sign. What is the equal sign essentially equivalent to? AUDIENCE: Assign. DAVID J. MALAN: Yeah, assigning a value. So if I, for instance, call this function GetString, and we'll see in a moment that's going to prompt the user for a string. This is like letting me then write D-a-v-i-d on a piece of paper. And when I say string s equals GetString, equal doesn't really mean equal in C programming. It means assign from the right hand side to the left hand side. So I've gotten a string. And the equal sign means put it in the storage container called s. And Then pass this off to printf to actually do its thing. So the end result then is going to look a little different. Let's do make hello-2. Either could work. You're following along. Make hello-2 worked. Dot slash hello-2, Enter. I seem to have an infinite loop or something. Nothing's happening. Why? AUDIENCE: It's making an infinite loop. DAVID J. MALAN: It is an infinite loop. It's kind of waiting for me to actually provide it with some input. So let me go ahead and type in David, and hit Enter. And now it says "hello, David." If I run it again. Let's type in Rob, "hello, Rob." Now this is the worst user interface ever. The user's apparently supposed to know what to do. But no matter. Using these same building blocks just like in Scratch, we can solve that problem and say something like your name please, colon, space, closed quote, close parenthesis, semicolon. So a lot of again silliness with the syntax. But notice I've just added a puzzle piece above this one and above this one. So now if I rerun this, hello-2, Enter. Wait a minute. What's wrong? It's not behaving any differently. Yeah. AUDIENCE: You didn't run make again. DAVID J. MALAN: I didn't run make again, right. So I've changed my source code. But again, there's that flow. Source code through the compiler gives you new object code, or 0s and 1s. So I need to actually rerun make hello-2 Enter. OK, something seems to have happened. Dot slash hello-2. Your name please. And to be clear now, why is the cursor on the same line? Exactly. I didn't put the backslash n up here in my code. So now I can write something like Daven, Enter. I can run it again and type something like Gabe, Enter, and we get a different program again and again and again. Now ultimately we're going to need to use a few different capabilities. We need to introduce ultimately some conditions to do things conditionally. Maybe loops so we can do things again and again. Maybe it would be nice if we could implement our own functions, like we could implement our own printf or our own version of GetString and GetFlow, because ultimately even using this command line environment can we do even the most visually interesting of things. Indeed in conclusion let me do this. I'm going to go ahead and close these windows and open this icon here, which is just a bigger version of that embedded terminal window. So Gedit has not only the place for my code, but also a built in terminal window, the black and white window where I can run commands. I just happened to open a bigger version of this. And now I'm going to go into the folder that I've already put in advance on the course's website. And I'm going to go ahead and open a file called thadgavin.c, which was written by someone else. And if we look at this, this is not the kind of code we'll be writing since the goal of this code was to write the prettiest looking code that he or she could, irrespective of whether or not another human being could ever understand this code. Indeed, every year there's what's called an obfuscated C contest, which is for real geeks who write code that no one else can read, but that does something either really simple or really amazing. And we thought we'd conclude with this look at something that's pretty amazing you might have seen once before. But we'll end on this note, dot slash, thadgavin. This then is what awaits. That's it for CS50. We will see you on Wednesday. [MUSIC PLAYING] | ДЕВІД МАЛАН: Отже, це курс CS50. І це був наш Колтон Огден, музику якого ви можете завантажити з soundcloud.com/cs50.Тож, сьогодні максимальну увагу ми приділимо мистецтву програмування і почнемо з того моменту, де ми зупинилися минулого тижня, розбираючи Скретч - мову графічного програмування. І опустимося до нижчого рівня, використовуючи більш традиційну мову програмування, відому як Сі (компільована статично типізована мова програмування). Та в процесі її вивчення ми зрозуміємо, що ті ж самі поняття, про які ми говорили останньої п'ятниці, будуть зустрічатися не лише у мові Cі, але в більшості інших мов, які ми вивчатимемо у цьому семестрі.Тож, як ми називали таку штуку минулого разу? Це – зразок оператора. Ми називали це оператором, що є інструкцією, яку має виконати комп'ютер чи Скретч. І надалі з причин, які ми скоро з'ясуємо, давайте також називати функцією щось на зразок цього.Ми також бачили такі штуки. І як називаються такі конструкції?АУДИТОРІЯ: Цикли.ДЕВІД МАЛАН: ЦиклИ. Досить легко. Його назва буквально відображає те, що він робить. В Сретчі, якщо ви хочете втиснути в нього якомога більше пазлів, цикл буде розростатись, аби все умістити. Ми незабаром побачимо, що в Сі ми можемо робити те ж саме.Інший вид циклу в Скретчі – назавжди, хоча є багато різних підходів. Але давайте подивимося на цикли більш загально, послухавши достатньо знайому з ними особу.МАРК ЦУКЕРБЕРГ: Єдина річ, яку комп'ютери справді роблять добре – це повторення команд. Як людина, ви б занудьгували, роблячи одне й те саме багато разів підряд. Але комп'ютер може робити те ж саме мільйони чи навіть мільярди разів і виконувати це справді добре, при цьому йому це не набридає. Наприклад, якби я хотів привітати кожного користувача Фейсбуку з днем народження, відправивши листа електронною поштою, мені б знадобилося понад століття для того, щоб написати всі ці листи. Але написавши кілька рядків коду, я можу змусити систему відправити електронного листа всім користувачам Фейсбуку, привітавши їх із днем народження. Це те, чим насправді є цикли, у чому їхня цінність і це те, що комп'ютери можуть робити дуже добре.ДЕВІД МАЛАН: Отже, якщо вам останнім часом надходили повідомлення з CS50 і Dropbox, це насправді саме те, чим ми займаємось, використовуючи код таким чином. По суті, у нас є велика електронна таблиця, в яку люди вводили свої імена та адреси електронних скриньок. Ми написали невеликий фрагмент коду, який може дублюватись для цих адрес і видаляти однакові адреси, якщо хтось підписався кілька разів. Після цього ми відправляємо автоматизований лист (у тому числі код купона) від програми-робота CS50.Минулого разу ми також розбирали дану конструкцію. Приклад чого зображено на екрані? Так, логічного виразу. Його форма призначена для того, щоб показати це. Всі питання, сформовані як «істина» чи «хибність» у Скретчі будуть мати такий вигляд. І ми називаємо їх логічними виразами. Насправді це є способом відповіді на запитання «істина чи хибність», «так чи ні».В той же час ви можете використовувати логічні вирази в таких конструкціях, які є умовами або розгалуженнями, тобто славнозвісними «дорожніми розвилками». Вони можуть мати не лише такий вигляд, вони також можуть мати зв'язані з ними опції «або/чи». Насправді у и можете зробитии шлях, що розходиться на три або чотири сторони, просто нашаровуючи дані структури, як ви побачите у Скретчі, якщо ви досі цього не побачили. З однаковим успіхом те саме ви можете робити й у Сі.Давайте розглянемо інший погляд нашого випускника, який може представити інший підхід до речей, які ми називаємо умовами.БІЛ ГЕЙТС: Люди приймають рішення щодня. Наприклад, перш ніж вийти на вулицю ви маєте оператора «якщо», в якому йдеться: «якщо піде дощ, мені буде потрібна моя куртка». І комп'ютери дивовижні. Щойно ви оберете ті види операторів, які вони можуть надійно виконувати, вони будуть робити це на неймовірній швидкості. Таким чином, комп'ютерна програма насправді є поєднанням невеликої кількості математики і певними операторами «якщо», де приймаються рішення.ДЕВІД МАЛАН: Отже, як ви, напевно, знаєте, Білл Гейтс, Пол Аллен та дехто інший декілька років тому почали так звану революцію персональних комп'ютерів. Я подумав, що перш ніж ми заглибимося у вивчення, ми послухаємо казку з міста Альбукерке, Нью-Мексиканського музею природної історії і науки, де розповідаються оповідання про ранні роки Біла Гейтса та Пола Аллена та про те, як виникли сучасні ПК, Маки і так далі. Для цього нам потрібні два добровольці, з гарними ораторськими голосами аби читати текст вголос.Гаразд, як щодо задніх рядів - підходь сюди. І з передніх рядів - також підходь. Займіть тут ваші місця. І поки ви підходите, пара організаційних оголошень. Секціонування, процес вибору групи, почнеться в цю середу і триватиме по п'ятницю. Докладніше про це йтиметься в середу на лекції.Супергрупи - це те, що ми запропонуємо на наступному тижні, куди запрошується увесь курс, і що означає великі, масштабні групи, одна більш, інша - менш просунута. Деталі ми оголосимо також в кінці цього тижня.Тим часом заняття в групах почнуться на третьому тижні курсу, нульовий індекс, за пару тижнів. Так що не турбуйтеся. Ви ще нічого не пропустили. В той же час, якщо у вас є будь-які організаційні питання, надсилайте їх електронною поштою мені, Девону, Гейб і Роб за цією адресою.Наостанок, Практичне завдання 0, звичайно, завершене. Можливо, ви помітили це на сайті курсу. Там є відповіді на всі питання, які у вас, можливо, виникали під час роботи . Але якщо вам раптом знадобиться допомога, будь-що відвідуйте консультації ввечері у понеділок, вівторок, середу, та четвер на цьому тижні в чотирьох столових. Шукайте за цим URL інформацію з приводу того, де мають бути консультації.А зараз давайте привітаємося з нашими сьогоднішніми гостями. Як вас звати?ДЖЕЙ ПОЛ: Джей Пол.ДЕВІД МАЛАН: Джей Пол, дуже приємно.ХІКАРІ: Хікарі.ДЕВІД МАЛАН: Хікарі?ХІКАРІ: Хікарі.ДЕВІД МАЛАН: Хікарі, також дуже приємно. На цих пюпітрах перед ДжеЙ Полом і Хікарі стоять два тексти, які я сьогодні вранці роздрукував з сайту Нью-Мексиканського музею природної історії та науки. І що я подумав зробити: на екрані зверху ваша розповідь буде супроводжуватись візуальними зображеннями.Я заздалегідь виділив текст, який маєш читати ти, а який – ти. По суті, ви читатимете абзаци по черзі. Дуже схоже на те, що ви робили на уроках англійської. Це змусить аудиторію насправді повірити у вашу розповідь. Справимося? Тож, починаємо розповідь: у нас є Бейсик, і все починається в Кембріджі.ДЖЕЙ ПОЛ: Це відбувалося взимку 1974 року у Кембріджі, штат Масачусетс, де зими бувають холодними. Бородатий довговолосий Пол Аллен, якого виключили з коледжу, плентався Гарвардською площею, поглинений у свої думки. Його головною турботою у той час було змусити свого друга Біла Гейтса кинути школу і почати свою справу.ХІКАРІ: Ця парочка вже мала кілька підприємницьких авантюр, починаючи зі шкільних років у «Лейксайді», Сіетл. Тоді одна компанія платила безкоштовним часом користування комп’ютерами за тестування машини PDP-10. Їхнім останнім планом було покинути школу і заснувати компанію з розробки програмного забезпечення. Аллен покинув Вашингтонський університет, проте в останній момент Гейтс вирішив залишитися в Гарварді.ДЖЕЙ ПОЛ: Того дня, перетинаючи Гарвардську площу, Аллен помітив січневе видання 1975 року журналу «Popular Electronics» з гучним заголовком: «Перший у світі мінікомп’ютер кидає виклик іншим комерційним моделям». Під заголовком красувалася маленька коробка, прикрашена лампочками і перемикачами. Вона називалася «MITS Altair 8800». І Аллен усвідомив, що це було саме те, що він шукав.ХІКАРІ: За дискусіями минали дні. Аллен і Гейтс усвідомлювали значення «Altair». Вони часто говорили про мікропроцесори і чекали можливості побачити, на що вони спроможні. Тепер на обкладинці «Popular Electronics» було зображено перший мінікомп’ютер. Очевидно, на ньому ще не було встановлено жодного програмного забезпечення. Вони уявляли, що армії програмістів накинулися на «MITS», і зв’язалися з Едом Робертсом, керівником компанії, заявивши, що мають майже готовий інтерпретатор мови програмування Бейсик, пристосований до «Altair». Та в них його не було. І Робертс, напевно, знав, це. Йому по 10 разів на день дзвонили люди з «майже готовим» інтерпретатором Бейсик. Його черговою відповіддю були слова: «Перший, хто покаже працюючий Бейсик, отримає контракт».ДЖЕЙ ПОЛ: Гейтс і Аллен ніколи не бачили «Altair». Вони навіть ніколи не бачили мікропроцесор «Intel 8080», вбудований у «Altair». Але пару років тому Аллен написав програму на універсальну ЕОМ, яка емулювала операції попередньої версії мікропроцесора Intel. Цього разу вони робитимуть те ж саме. ХІКАРІ: З інструкцією до «Intel 8080» у руках Аллен сів за гарвардський комп’ютер моделі PDP-10 і написав емулятор і необхідні програмні інструменти. Тим часом Гейтс припинив ходити на заняття і присвятив себе розробці Бейсику, будь яким чином намагаючись зменшити розмір до 4 кілобайтів.ДЖЕЙ ПОЛ: А в Альбукерці Ед Робертс почув дзвінок від Гейтса, який цікавився деталями про те, як «Altair» обробляв окремі програми. Ніхто ніколи не питав про це раніше, і Робертс зацікавився.ХІКАРІ: З готовими інструментальними засобами і планом розробки Гейтс і Аллен написали код на PDP-10, залучивши іншого студента Гарварду – Монте Давідоффа – до написання математичної бібліотеки. Після заключної ночі програмування Аллен сів у літак, щоб показати свою версію Бейсику у «MITS». Під час перельоту Пол занепокоївся, а в Кембріджі почав хвилюватися й Біл. Вони протестували свою Бейсик на емуляторі і вона працювала. Але якщо раптом помилка є в самому емуляторі?ДЖЕЙ ПОЛ: Коли літак наблизився до Альбукерку, Аллен зрозумів, що їх Бейсик, зараз акуратно записаний на невеликому рулоні перфострічки, ні на що не буде придатний без окремої програми – завантажувача, який вкаже «Altair», яким чином читати паперову стрічку, подану в телетайп. Він дістав свій блокнот і швидко накидав програму-завантажувач в асемблері, потім вручну перевівши її у «1» та «0» так, щоб це зрозумів «Altair».ХІКАРІ: Аллен сподівався потрапити у невелику чисту високотехнологічну компанію, якою керують чоловіки у ділових костюмах. Тож він був дещо здивований, коли побачив у аеропорту Робертса, що виглядав як фермер. Робертс також був здивований. Коли він підкинув гарвардського програміста до дорогого готелю, Аллен мусив зізнатися, що не зможе заплатити за номер.ДЖЕЙ ПОЛ: Сама «MITS» розташовувалася у запиленому торгівельному центрі. Всередині на захламленому верстаті стояв «Altair» з п’ятьма кілобайтами пам’яті, кабелем приєднаний до телетайпу. Робертс і головний інженер Білл Йетс нетерпляче чекали, поки Аллен запускав завантажувач, клацаючи тумблером. Телетайп загудів, протягнувши паперову стрічку через зчитувач. Завантаження програми зайняло близько 15 хвилин. Потім телетайп раптово надрукував запит пам’яті й запит готовності і Аллен набрав декілька тестових команд. На загальне здивування, програмне забезпечення працювало. Звичайно, у ньому були помилки, але головним було те, що воно все-ж таки працювало.ХІКАРІ: Пізніше, по дорозі у «Pancho» на трьохдоларовий обід, оса залетіла у вікно пікапа і вжалила Аллена за руку. Але на той момент ніщо не могло зіпсувати його настрій. «Altair» мав тепер свій власний Бейсик, перше комерційне програмне забезпечення для домашнього комп'ютера, розроблене Полом Алленом і Біллом Гейтсом, які цього разу почали справу як компанія «Microsoft».ДЕВІД МАЛАН: Дуже дякуємо нашим читцям.[АПЛОДИСМЕНТИ]ДЕВІД МАЛАН: А зараз, перед тим як ви займете свої місця, виберіть слоника – ой, зачекайте секунду – слоника, що блистить або що світиться у темряві, які зробив для CS50 Чен Гонг.ХІКАРІ: О, дякую.ДЕВІД МАЛАН: Дуже дякую вам.[АПЛОДИСМЕНТИ]ДЕВІД МАЛАН: Правдива історія. Вона розповідає про те, що всі ці машини і та легкість, з якою ми використовуємо їх зараз і приймаємо як належне, дійсно взяли свій початок тут, за кілька кроків від цього залу. І ось зараз, якщо ви там ще не були, це Максвел Дворкін, будинок інформатики, розташований за рогом. І на другому поверсі цього будинку висять три сторінки першого вихідного коду, написаного Біллом Гейтсом і Полом Алленом. Якщо збільшити зображення, можна навіть побачити їхні імена і підписи, які ці двоє поставили під час свого останнього візиту до Гарварду кілька років тому. Але особливо цікавим було те, що вони мали намір написати програму, яка дозволила б іншим людям писати свої власні програми. У той час все це було пов’язане з комп’ютером «Altair» компаніїі «MITS». Їм потрібно було якимось чином полегшити любителям і людям, схожим на нас із вами, писати програми для нього, при цьому не обов'язково розуміючи код асемблера, машинний код, чи, не дай боже, нулі та одиниці. Ми, програмісти, такі як присутні у цьому залі, хочемо мати змогу виражатися за допомогою псевдокоду навіть якщо він вимогливіший за той, про який ми говорили минулого тижня. Нам не хочеться писати такий код, як це робили Білл Гейтс і Пол Аллен. Натомість нам хочеться писати код, який виглядає трохи привітніше до користувача.Тепер ця мова відома під назвою Бейсик. І номери рядків ви використовуєте для того, щоб просто нумерувати рядки коду, який ви пишете. Сьогодні нам навіть цього не потрібно робити. Але тут ви можете побачити, як напис "hello, world" ( «привіт, світ») насправді буде надрукований таким чином. І що насправді зробили Білл і Пол - вони дали людям можливість писати код таким чином замість того щоб -якщо ви подивитеся на екран – писати код таким способом.Нещодавно ми мали можливість поспілкуватися з професором факультету інформатики Гаррі Льюїсом, який навчав Біла Гейтса декілька років тому і який тепер стоїть біля цих трьох сторінок коду. Давайте подивимося.ГАРРІ ЛЬЮЇС: Перед вами частина ранньої версії програмного забезпечення, написаного Біллом Гейтсом і Полом Аленом, засновниками Microsoft. Відтак, код цікавий з двох причин. Перш за все, він став першим продуктом «Microsoft», який був інтерпретатором мови програмування Бейсик. А по-друге, це була одна із перших спроб створити інтерпретатор для того, щоб звичайні люди могли використовувати персональні комп'ютери.Тож, Білл Гейтс був студентом Гарварду. Я почав викладати у Гарварді у 1974 році. Це було написане 1975 року. Тож, це було на початку його та моєї кар’єр. Десь у цей час я насправді вчив Білла. Пол Аллен не був студентом Гарварду, але він був однокласником Білла Гейтса у старшій школі. Якщо ви підійдете ближче і поглянете на список, ви знайдете третє ім'я, Монте Давідоффа, який був однокурсником Гейтса вже в Гарварді.Отже, ось тут є цікавий коментар. У ньому написано: «У 4К можна видалити корінь квадратний, але цикли з параметрами мають працювати.» Це означає, що існує два способи компіляції цієї програми. Один з них був працювати на версії комп'ютера «Altair», який мав лише 4K слів пам'яті (4096 слів пам'яті). Але розширена версія мала 8K. І це говорить про те, що у версії 4K потрібно було видалити частину коду, щоб він підійшов. І однією з речей для видалення був алгоритм квадратного кореня. Але, ймовірно, цикли з параметрами мають працювати навіть коли ви компілюєте програму до 4-кілобайтової версії комп’ютера.ДЕВІД МАЛАН: Таким чином, однією з тем, як ми побачимо в інформатиці, це поняття нашарувань і відокремлень, яке стоїть на плечах людей, що прийшли перед нами, схожих на Білла Гейтса і Пола Аллена, про яких тут розповідалося. І це означає, що сьогодні ми можемо приймати як належне, що сьогодні нам значно легше написати код, ніж це було тоді. В дійсності код, як ми вже говорили в п'ятницю, в більш технічному плані відомий як вихідний код. І він схожий на синтаксис в англійській мові. Він є більш правильним і більш чітко визначеним, на відміну від, скажімо, псевдокоду, для якого не існує формального визначення.Сьогодні ми сфокусуємося на вихідному коді, який виглядає так, і на перший погляд здається повною таємницею. І, чесно кажучи, це естетично більш складний спосіб, ніж програма, що лежить в його основі. Все, що робить програма, нагадайте, про що ми говорили? Вона просто друкує "hello, world". І все ж подивіться на всі ці символи, які ми маємо написати навколо цієї дуже простої фрази. Але незабаром всі ці лінії будуть мати для вас набагато більше сенсу.А потік полягає в наступному. В нашому розпорядженні має бути код на кшталт того вихідного коду, який ми щойно бачили. Також нам потрібна нова програма, щоб його запустити. Нам потрібні алгоритми, які можуть перетворити вихідний код, такий як цей, в об'єктний код – «0» і «1». Іншими словами, сьогодні ми збираємося дізнатися, як це зробити: написати вихідний код (зверху), ввести його в спеціальну програму, відому як компілятор, і створити об'єктний код. Іншими словами, ми візьмемо щось на зразок цього і проженемо через програму, що називається компілятор, створивши об’єктний код, що виглядає ось так.Тож, в буквальному сенсі це комбінації з «0» і «1» (нулів і одиниць), які розуміють сучасні комп'ютери Intel, і які розшифровуються процесором - мозком всередині комп'ютера – у простий напис "hello, world". Для цього потрібно більше нулів і одиниць, ніж ви могли сподіватися. Та це тому, що ми покладаємося на велику кількість складних механізмів, які відтепер можемо приймати як належне. Інакше кажучи, багато розумних людей подарували нам багато класних інструментів і потужне програмне забезпечення, якими ми можемо тепер користуватися для створення власних проектів.Тож, давайте починати. В той час як минулої п'ятниці і для вирішення Практичного завдання 0 на цьому тижні ви будете гратися у світі, який виглядає так, починаючи з сьогоднішнього дня і для вирішення Практичного завдання 1 на наступному тижні код для вас виглядатиме трохи загадковіше, але функціонально залишиться таким самим. Тож зверніть увагу: зверху Скретч, знизу Сі. Чесно кажучи, Скретч набагато зручніший і доступніший для користувача. Але якщо ви зараз візуально порівняєте верхній та нижній елементи, то помітите однозначну відповідність між пазлами та мовою, з якою ми збираємося гратись. Зокрема, «say(сей)», синій пазл зверху, якому ключовому слову чи спеціальній фразі мови Сі він відповідає?АУДИТОРІЯ: Printf (прінтеф)ДЕВІД МАЛАН: Printf, що означає, відформатований напис. Інакше кажучи, printf у Cі буде оператором або функцію, яка друкує щось на екрані. Що він надрукує на екрані? Будь що, що ви йому скажете всередині лапок, всередині дужок. І знову, звичайно, є багато речей, які ви маєте пам'ятати: дужки, лапки, крапки з комою тощо. Але зараз це поки що недоречно. Зараз нас цікавить те, що блок say у Скретчі майже рівнозначний оператору printf у Cі. В той самий час, якому ключовому слову відповідає жовтий пазл згори when green flag clicked (коли буде натиснуто на зелений прапорець)?АУДИТОРІЯ: Main (мейн).ДЕВІД МАЛАН: Main. Можливо int, можливо void. Але main (англ.-основний) звучить так, ніби воно є важливим і це дійсно так. Тому, коли на зелений прапорець буде натиснуто, пазл запустить повну програму Скретч. З теперішнього моменту ми будемо називати цю функцію main, вона відома як main.Тим часом, ми узагальнимо це все наступним чином. Ми могли б назвати say функцією.Зокрема, вона могла б виглядати саме так. А як щодо циклів? Якщо ми хочемо почати далі перетворювати або перекладати Скретч у Сі, мабуть, цей елемент просто завжди говорить "hello, world". Так що, якщо ви пов'яжете ці сценарії з котом у Скретчі, він буде продовжувати говорити в певному анімаційному пузирі, "hello world, hello world, hello world," до нудоти, завжди. Якщо ми хочемо зробити щось подібне в Cі, це буде виглядати трохи таємничішим. Але ми можемо досягти того ж результату, як ми в кінці кінців дізнаємося, з такою синтаксичною структурою. Я знову використаю printf, тому що в результаті хочу надрукувати "hello, world". І очевидно я замість ключового слова forever (назавжди) використаю while (поки). В англійській мові while (поки) семантично передбачає певний цикл або круговий процес.І таким чином стало ключовим словом, яке використовується у Сі. І while true (поки істино), чому while true фактично означає назавжди? Після while, як ми скоро зрозуміємо, йдуть дужки, де ви можете розмістити логічний вираз. І оскільки той вираз істинний, цей код, як позначено у цих двох фігурних дужках, як ми їх звемо, буде повторюватись знову і знову.Тож істина є істиною. Таким чином, while true (поки істино) буде робити це завжди. Це досить дивна конструкція для вираження. Але у Сі не було ключового слова forever (назавжди). Натомість був while (поки). І був такий дуже простий логічний вираз, як true (правда). І таким чином досягається такий самий результат.Як ще ви могли б виконати цикл? В Скретчі ви могли б зашити в код певне число повторень у циклі. І так само ми могли б це зробити в даній версії Cі, в результаті чого ми отримаємо так званий цикл з параметром. Цикл з параметром тут буде коливатись між значеннями від 0 до менш ніж 10.Тепер змінні у Скретчі. Можливо, у вас ще не було нагоди використовувати їх. Але в загальному, в чому сенс змінної, про яку ми говорили минулого тижня? Що це?АУДИТОРІЯ: ВказівникиДЕВІД МАЛАН: Вказувати? А, вказівники. Ок, стежити за вказівками, наприклад, у грі. Або в більш загальному сенсі, що робити зі змінною? Яка з них користь?АУДИТОРІЯ: Пам’ять.ДЕВІД МАЛАН: Так, пам’ять. Вона потрібна для зберігання чого-небудь. Останнього разу я використовував простий візуальний приклад із цією скляною чашою. Якщо ми би захотіли зберігати щось всередині змінної, наприклад значення шість, бо тут є шість куль для пінг-понгу. Це просто певний вид контейнеру для зберігання, всередині заповнений бітами- нулями і одиницями, проте виявляється, комп'ютер може це робити.У Скретчі, якщо ми хочемо мати змінну, ми можемо використовувати такий помаранчевий блок. В даному конкретному випадку ми називаємо його лічильником. Я встановив його на нулі. І що я далі робитиму? Forever (завжди), лічильник say, і якщо ви з ними гратиметеся у Скретчі, побачите лише Скретч. Кіт чи будь-який інший спрайт буде говорити задане число разів.Змінити лічильник на 1 все одно що збільшити на 1. З чого до чого він буде рахувати? З нуля до нескінченності чи поки не перерветься Скретч, чи поки ви не втратите інтерес до спостереження, як довго він насправді може рахувати.Тож як ми могли б конвертувати це у Сі? Це буде виглядати трохи замислувато. Але, знову ж, якщо ви подивитеся на кожну з цих ліній, вони начебто формують ряд. Очевидно, що int матиме якийсь особливий сенс у Сі. Ми знову в цьому пересвідчимося. До речі, int розшифровується як integer (ціле число). Так це просто означає число. Я хочу таку скляну чашу, яка зможе зберігати число, а не кульки для пінг понгу. І я збираюсь поставити там знак рівності і присвоїти йому значення 0. Це дуже схоже на встановлення лічильника на нулі, але у Сі.Тим часом, while true (поки істино), що, звичайно, буде рівнозначним до forever (назавжди), навіть якщо це трохи незрозуміло, а потім все, що всередині фігурних дужок. Ви можете вважати, що ці фігурні дужки, які ви можете надрукувати на клавіатурі, насправді схожі на вигини цих жовтих блоків циклу у Скретчі. Вони оточують кілька рядків коду.Printf тепер виглядає трохи моторошно, оскільки я бачу не лише лапки в круглих дужках. Але що ще є синтаксично нового в цьому прикладі? Тут є відсоток d і потім зворотний слеш n. Ми бачили це раніше, хоча я не згадував цього. Далі там ще є кома. А потім - лічильник (counter).За хвилину ми побачимо, що це лише стандартний спосіб сказати: надрукуй "десяткове число", відкриваємо, закриваємо лапки, певне десяткове число. Але я розповім вам пізніше, що це за десяткове число. А те, що в цій лінії є кома, означає: «Йди далі і надрукуй певне десяткове число.» О, і до речі, числом є будь-яке значення цієї змінної. Для того, щоб зробити це зрозумілішим, ми незабаром розглянемо приклад, що включає printf в рамках реальних програм на мові Сі.Тепер дещо для завершення розгляду усіх цих конструкцій. Логічні вирази. Можливо, вам ще не доводилося використовувати їх у своїй програмі, але ви могли б зробити це дуже добре, особливо використовуючи умови. І тому скажіть мені, як ми могли б перевести ці два приклади зі Скретчу: якщо х менше за у, або якщо х менше за у і у менше за z?В Cі це виглядатиме наступним чином. Трохи таємниче, більше дужок, деякі трохи дивні амперсанди (знаки &), але в основному ідея так само проста, як і у світі пазлів. Ми просто перевіряємо, чи що-небудь менше за щось інше.Як щодо умов? У двох словах англійською мовою, що робить цей шматок коду Скретч? АУДИТОРІЯ: Порівнює два числа.ДЕВІД МАЛАН: Порівнює два числа. Порівнює два числа, і якщо х менше за у він говорить, у скільки разів. Якщо х більше за у, він скаже, у скільки разів, і ще, якщо х дорівнюе у, він каже, у скільки разів. А де ж взялися х і у? Хтозна. Цей шматок коду Скретча відрізаний від контексту. Але зараз ми на хвилинку хочемо перевести його у код Сі.Отже, коли на цьому тижні ви звикнете до світу ліворуч, виконуючи Практичне завдання 0, зрозумійте також, що основні поняття не зміняться ні на цьому тижні, ні на наступному, ні надалі. Насправді ми просто почнемо писати деякі речі іншим шляхом, використовуючи клавіатуру замість миші.Тож, якщо х менше у, і там є певні круглі дужки, далі будуть певні фігурні дужки, які неначе заключають в оболонку, як це роблять жовті пазли. І я збираюся надрукувати через printf "х менше за у" і так далі.Що приємного у мові Сі, як ви можете тут бачити, так це те, що немає цих вкладень, вкладень, вкладень, які обов'язково будуть зсувати ваш код праворуч. Замість цього всі рядки у вас будуть акуратно розміщені таким чином. Але це тільки естетична деталь, яку ми незабаром знову побачимо.Добре. Це повертає нас до цієї загадкової програми. Давайте справді напишемо якийсь код. Як ви візметеся за його написання? Всі роки, відколи у вас з'явився Мак, ПК чи ноутбук, фактично ви мали можливість почати писати програмний код. Але напевно у вас відсутня спеціальна програма. Безсумнівно, ви можете написати код. Але без якої установленої програми ви не зможете конвертувати вихідний код в об'єктний тобто «0» та «1»?АУДИТОРІЯ: Без компілятора.ДЕВІД МАЛАН: Правильно, без компілятора. На даний момент більшість з вас, ймовірно, не мають компілятора, і ніколи його не завантажували. Але ви дізнаєтеся, що можете завантажити його, як і більшість будь-яких інших програм. В операційній системі Mac, ви могли завантажити або вже завантажували щось під назвою Xcode або GCC або Clang. Якщо ви прийшли зі світу Windows, ви, могли завантажити такі середовища, як Visual Studio та Visual Basiс. Сьогодні існує безліч компіляторів, які ви можете використовувати. Але справа в тому, що для сотень людей з різними комп'ютерними конфігураціями було б головним болем і, чесно кажучи, технологічним кошмаром однаково налаштувати свої машини для того, щоб ми могли бути на одній і тій самій сторінці.Натомість у CS50 ми надаємо вам стандартне середовище, середовище Linux, яке буде мати приблизно такий вигляд. Детальніше ви це побачите в інструкції до Практичного завдання 1, яке з’явиться в мережі цієї п’ятниці ввечері.І це означає, що надалі у вас буде можливість завантажити і встановити програму під назвою CS50 Appliance. Також ви завантажите і встановите іншу програму під назвою гіпервізор, що є іншим шляхом досягнення цього. Неважливо, який у вас комп'ютер, чи то Maк, чи то ПК, Linux або Solaris,чи будь яка інша операційна система, з якою ви працюєте, ви завантажите програму під назвою гіпервізор, який запустить CS50 Appliance незалежно від вашої ОС. Іншими словами, гіпервізор перетворює наш матеріал у будь-яку мову, будь-які інструкції, які розуміє ваш комп'ютер.Тож, це є нашаруванням. І знову ж таки, це нібито основа інформатики, будівля в основі піраміди. У вас може стояти Windows. У вас може стояти Mac OS. Але з наступного тижня ви скачаєте безкоштовну програму під назвою гіпервізор. Ви завантажите програму під назвою CS50 Appliance.Вона запуститься в гіпервізорі, який запуститься на вашому комп'ютері. Кінцевим результатом буде те, що у всіх нас на Маці чи ПК буде таке просте вікно, яке дасть нам ілюзію, що ми працюємо в одній операційній системі, без будь-якого іншого впливу на ваш комп'ютер. І ви можете розширити його на повний екран і, по суті, поводитись так, ніби ви працюєте в операційній системі Linux, на якій базується CS50 Appliance.Отже, давайте насправді зараз використаємо його, щоб написати програму. Ви можете написати програму, використовуючи Microsoft Word, TextEdit, Notepad, чи WordPad або будь-який текстовий редактор, який ви коли-небудь використовували. В реальності ви не повинні використовувати будь-яку з цих програм. Ви не маєте використовувати такі програми, як Microsoft Word, в якому є жирний шрифт та курсив, великі й дрібні шрифти, бо комп'ютеру плювати на все це. Все, що комп'ютеру портібно, це англійська мова у вигляді інструкцій, написаних на Cі.Так що у CS50 Appliance ми будемо використовувати доступну програму під назвою Gedit, яка вже попередньо там встановлена. Gedit усього лише надзвичайно простий текстовий редактор на зразок TextEdit у Маці чи Windows Notepad, який буде мати схожий на це вигляд.Тож, давайте не будемо дивитися на слайди, а насправді зайдемо в саме середовище. Я піду далі і в іншому вікні увійду в мій CS50 Appliance, який я попередньо встановив на своєму ноутбуці.Зверніть увагу, що, як і у Windows та Mac OS, тут є кілька пунктів меню. Як і у Windows вони розміщені знизу отут, а не там, як у Mac OS. Але насправді вони нібито однакові. І тут є ціла купа програм. Тут є Dropbox. Тут є ціла купа аксесуарів, графічних програм, які ми будемо використовувати пізніше виконуючи практичні завдання. Тут є вбудований веб-браузер, тож CS50 Appliance є повноцінним комп'ютером всередині комп'ютера.Але я натисну цю крайню ліву білу іконку тут, що є іконкою Gedit. І зараз відкриється вікно, в якому є три панелі: ліва, верхня і нижня.Тепер справа угорі я насправді збираюся написати код. Тож давайте зробимо це. Я збираюся відкрити - файл -зберегти. Можливо, раніше ви не бачили цього особливого вікна. Але тут усе так само, як у Mac OS або Windows. Це усього лишень вікно з усіма папками, які є у мене в цьому комп'ютері.І я збережу файл як hello.c. І я піду далі і натисну Зберегти. А тепер зверніть увагу, зліва вгорі у мене є вкладка, що називається hello.c. Ймовірно, вам це досить знайомо, навіть якщо ви не використовували цю програму раніше.А зараз я введу ту досить загадкову послідовность команд, яку ми бачили хвилину тому. #include <stdio.h>. Докладніше про це незабаром. int main (void). Відкрию й закрию фігурні дужки, а потім, думаю, всередині там був напис "hello world,", двокрапка.{printf(“hello, world\n”);}І тепер Зберегти.Тож,це програма, написана на Cі, отже, написана на вихідному коді. Але я не можу просто запустити цю програму. Як би я не хотів клацнути двічі на якусь іконку, ніякої іконки не існує, крім файлу з початковим кодом. Знову, який процес мені потрібен, щоб запустити цей файл?АУДИТОРІЯ: Компіляція.ДЕВІД МАЛАН: Компіляція. На різних комп'ютерах ви робите це по-різному. Але в CS50 Appliance, ми зробили зразок того, як можна це робити у багатьох різних системах. Я просто запущу команду під назвою make (зробити). І make буквально це зробить. Зробить мені програму.Тож make запустить компілятор для мене. І назва програми, яку я хочу зробити - привіт(hello) . Тепер make - це програма. І make досить розумна, щоб зрозуміти, що якщо я скажу make hello, вона буде автоматично шукати файл з ім'ям hello.c просто тому, що вона так налаштована.Тому, коли я зараз натискаю тут на Enter, цей загадковий незрозумілий рядок виконується. І повірте мені, незабаром, лише за кілька днів ви зрозумієте, що означає вся ця нісенітниця. Але зараз, просто знайте, що make запустив виконання компілятора. Іншими словами, він знайшов на моєму комп'ютері компілятор, попередньо встановлений у CS50 Appliance, який ми вам вручимо у Практичному завданні 1. І потім взяв hello.c в якості вхідних даних і виробив «0» і «1» на виході.І він автоматично зберігає ці «0» і «1» у файлі під назвою hello. І хоча цей синтаксис, можливо, також новий для вас, зрозумійте, що просто вказавши ./hello я запущу цю програму.Зараз і принаймні найближчі пару тижнів, майже всі програми, які ми напишемо, будуть в чорно-білих текстових вікнах. Ніяких мишок, ніякого клацання, вікон та іконок. Ми не будемо поки що ускладнювати і спочатку зосередимося на основних поняттях, перш ніж перейти до якогось вищого рівня, наприклад, гри «Breakout», про яку ми говорили в першій лекції минулого тижня.Так що, коли я натискаю Enter тут, в лише текстовому середовищі це рівнозначно подвійному клацанню на іконку з назвою привіт (hello) . Як ви думаєте, що трапиться після того, як я натисну на Enter?АУДИТОРІЯ: Він надрукує «привіт, світ» ("hello world.")ДЕВІД МАЛАН: Сподіваюся, він надрукує «привіт, світ».І справді надрукував. Тепер тут були деякі загадкові синтаксичні конструкції. Давайте перемотаємо на хвилинку і подивимося, чи не можемо ми дізнатись про їхню роль, халтурячи - пробуючи і промазуючи . Що, якщо я позбавлюся від зворотного слешу n? Зараз ті з вас, хто вже раніше займався програмуванням, напевно відразу дізнаються, що це означатиме. Але ті, хто ніколи не займався програмуванням принаймні подумайте самі, що буде, коли я перезапущу цю програму. Тож я повернуся до свого маленького чорно-білого вікна, в якому я можу це скомпілювати. Я збираюся перекомпілювати hello (привіт). Ми побачимо таку ж загадкову послідовність команд. І я наберу ./hello. А тепер хто-небудь, хто ніколи не займався програмуванням, скажіть, що може бути іншим цього разу? Так.АУДИТОРІЯ: Він не перестане друкувати "hello world." ДЕВІД МАЛАН: Він, пробачте, що…?АУДИТОРІЯ: Він не перестане друкувати це?ДЕВІД МАЛАН: Він не перестане друкувати "hello world.". Непогана ідея. Інші думки? Так.АУДИТОРІЯ: Повідомлення про помилку.ДЕВІД МАЛАН: Повідомлення про помилку, можливо. Що ще?АУДИТОРІЯ: Він так само може надрукувати дужки і крапку з комою?ДЕВІД МАЛАН: Так само може надрукувати дужки і крапку з комою. Можливо, той зворотний бекслеш є свого роду кінцевою точкою, це важливо. Які-небудь інші думки?Тож, всі думки слушні. І справді, там буде повідомлення про помилку. Вірогідно, це найімовірніша відповідь на найближчі кілька тижнів, поки ми тут вчимося кодуванню .Але на даний момент запам'ятайте, що комп'ютери роблять тільки те, що ви їм кажите робити. Дуже нагадує смішний приклад з арахісовим маслом і желе. Передбачалося, що наші людські комп'ютери повинні робити те, що ви сказали їм робити. Отож, в цьому випадку, якщо ви не скажете комп'ютеру перемістити цей миготливий курсор на наступний рядок, він не зробить цього. Тож зверніть увагу на відмінності, коли я запущу цю програму.Схоже на помилку. Певно, це естетичне помилка. Але яка очевидна відмінність цих вихідних даних від попередніх? Так.АУДИТОРІЯ: Не з'явився новий рядок.ДЕВІД МАЛАН: Не з'явився новий рядок. Можливо, той з вас, хто раніше робив верстку веб-сторінок знає, що тег <br>, тобто тег переносу рядка, по суті дуже схожий. Веб-браузер буде ігнорувати вас, поки ви конкретно не скажете йому, що робити. Так само мова Сі робитиме лише те, що ви їй скажете робити.Тож, причина того, що всі ці приклади досі мали цей зворотний слеш, у тому, що ви використовуєте його як символ нового рядка, так би мовити. І ви можете зрозуміти, що це виглядало б принаймні трохи дурнувато. Якби я cтворював новий рядок, просто натискаючи Enter і потім неначе обрубуючи код таким чином, я б вам не дуже догодив. І навіть якщо в цьомц сенсі ви не переймаєтеся, ви зрозумієте, що цей фрагмент коду виглядає не особливо добре.Так що багато років тому світ вирішив, що, якщо ви явно хочете помістити курсор на новий рядок, ви повинні чітко сказати: новий рядок, \n( зворотній бекслеш ен). Є ще деякі символи, схожі на цей. Але зараз ми зосередимося на \n.Тепер давайте зробимо програму трохи цікавішою. Я піду далі й цього разу відкрию новий файл. Я збережу його як hello-1.c і лише для забави поміщу його у мою папку Dropbox.Як ви побачите в кінці тижня в документації CS50 до Apppliance під час виконання Практичного завдання 1, ми рекомендуємо вам використовувати Dropbox чи інші рівноцінні сервіси, тому що тоді всі ваші коди будуть автоматично збережені. І ось чому я зайшов у цю папку.А зараз я напишу трохи іншу програму. #include <stdio.h>, int main (void). А далі printf(“hello, world\n”); точно так само, як і раніше.Але зараз я хочу надрукувати дещо інше. Я хочу надрукувати: "скажи "Hello, David.". Гаразд, будемо сподіватися, що якщо я перекомпілюю цю програму, перезапущу її, вона скаже "Hello, David."Але якщо я захочу, щоб ввести цей вид змінної, поняття контейнера, що буде зберігати D-a-v-i-d і не зашивати його у код моєї програми. Що, якщо я почну робити щось на зразок цього?string s, тож це - змінна. Якщо вам потрібен рядок (англ. string - рядок) відомий також як слово або фраза. В програмуванні ми називаємо послідовність символів рядком. Ми назвемо його s, бо це гарна проста назва. Але я міг би назвати його будь-як.Я скажу: string s ="David"; (рядок ес дорівнює Девід в лапках, крапка з комою). А тепер я хочу вставити "D-a-v-i-d" в те, що я друкую. І перед тим як ми побачимо на екрані ребус із особливих синтаксичних одиниць, який дозволив нам зробити заміну у значенні. Що за особливий символ був кілька слайдів тому?Тож, відсоток. Тоді це був відсоток d для десяткового числа. Що здається недоречним тут. Виявляється, є ще один відсотковий символ, відсоток ес (%s), що означає "заповнювач" для рядка.А зараз, дуже просто, я наберу hello-1, тому що цей файл називається hello-1.c, і натисну Enter. І я облажався. Що відбувається? Тут ми маємо почати розуміти, що ми у цьому середовищі командного інтерпретатора, у цьому лише текстовому середовищі. Тут зараз немає натискань на іконки папок. І поверніться на хвилину назад. У якій папці я казав, що зберіг свій код? Тож папка Dropbox. Вона могла б називатися будь-як. Але так трапилося, що зветься Dropbox. Тож якимось чином мені потрібно двічі клацнути на папку Dropbox для того, щоб зайти в неї й дістатися мого коду під назвою hello-1.c. Дайте мені піти далі й на хвилинку зменшити це вікно. Так як і у Windows та Mac OS, в Linux є папки. Папки є у CS50 Appliance. А просто зараз ми обмежені цим текстовим середовищем.Але якщо я двічі клацну на Dropbox, зверніть увагу, що тут є файл, який я хочу компілювати. Але мені потрібне це чорно-біле вікно терміналу, так сказати. Але мені потрібно перейти в цю папку або каталог. Трохи загадково, але ви теж звикнете до цього.У світі Linux, яка є операційною системою, запущеною всередині CS50 Appliance, є команда під назвою cd. Це означає, що я можу ввести cd, пробіл, Dropbox (cd Dropbox). cd - змінити каталог (change directory). Саме в той день, коли люди винаходили такі як у нас із вами комп'ютери й операційні системи, вони хотіли так мало натискати на клавіші, наскільки це було можливо. Тож найпростішим способом сказати "змінити каталог" була команда cd.Тож якщо я введу cd, пробіл, Dropbox, зверніть увагу на те, що тут змінилося. В дужках Appliance ніби сміється мене і нагадує мені, де я. Тож відкрита папка - Dropbox. Якщо я тепер наберу ls, щоб зробити список (знову скорочено, тому що тоді люди не хотіли повністю писати l-i-s-t (англ.-список) і замість цього вони замінили його на ls).Enter. Зверніть увагу, що я бачу дві речі, hello-1.c, а потім цю загадкову штуку , src1m (source 1m). Таким способом я позначив "вихідний код для тижня 1, понеділок". Цю папку я сьогодні вранці завантажив з сайту CS50, і заздалегідь вклав її у Appliance.Але на цей момент єдине, що нас цікавить - це створення цієї програми. Тож коли я набираю make hello-1, Enter. Блін. Щось пішло не так. Отже, давайте розберемо це окремо. І на жаль, це місце, де стає трохи важкувато, принаймні якщо ви ніколи не програмували раніше.О, господи. Я написав два рядки програми і маю чотири рядки помилок. Тож, що тут відбувається. У першу чергу завжди прокрутіть назад і знайдіть перше повідомлення про помилку, тому що часто компілятори просто плутаються у тому, що ви і я робимо. Компілятори досить мовчазні. Вони робитимуть тільки те, що ви скажете їм робити. І якщо ви заплутаєте їх, вони просто ніби піднімуть руки до неба і, можливо, покажуть більше повідомлень про помилку, ніж це насправді доречно.Отже, давайте подивимось на першу помилку. На перший погляд надзвичайно загадково . Але зауважте, ось ім'я файлу, в якому я очевидно напартачив. Двокрапка 5, двокрапка 5 означає: у рядку 5 на п'ятому символі. Тож, у п'ятому стовпчику символів, з вашого дозволу, помилка. Використання неописаного ідентифікатора рядка. Ви мали на увазі standard n?Ні, я мав на увазі рядок. А далі йде начебто копіювання і вставка того, що я набрав, щоб фактично привернути мою увагу, до того місця, де я напортачив. Таким чином, з якихось причин Cі, або, принаймні, компілятор не розуміє слова "рядок (string)". І це тому, що ми зробили це. Тож команди string в Cі не існує . Що робить курс CS50, протягом перших кількох тижнів курсу ми надаємо вам додаткові навчальні коліщатка, так би мовити. І ми ставимо ці навчальні коліщатка у спеціальний файл під назвою CS50.h.Так що це другий із двох файлів, назва яких очевидно закінчується на h. Давайте повторимо. printf - це оператор або функція, що друкує щось на екрані. Але ви не бачили, як я приводив у виконання printf, правильно. Кілька років тому хтось привів у виконання printf. На який файл ви поставите, в якому файлі він або вона заклали виконання printf, коду printf?У файлі під назвою stdio.h. Насправді, це, ймовірно, два файли: stdio.h, який символізує файл заголовка, і stdio.с, який символізує вихідний код Cі. Таким чином, він чи вона кілька років тому кинули код, який вони написали, в цей файл, щоб через багато років такі як ми люди могли, так би мовити, включити його у свої власні програми.І насправді, це те, що означає знак "решітки", після якого стоїть слово include. Він шукає його на локальному жорсткому диску, знаходить файл з ім'ям stdio.h, а потім копіює його в мій власний файл. Тож тепер моя програма уміє друкувати на екрані. Отже, за цією логікою, де визначається рядок?АУДИТОРІЯ: CS50.h.ДЕВІД МАЛАН: CS50.h. І це насправді те, що ми, основний персонал, зробили. Ми придумали кілька типів даних, таких як string, на додаток до тих, які ви отримуєте безкоштовно, на кшталт int. І ми побачимо, деякі інші, такі як char для character та декілька інших. Усередині CS50.h принаймні, є хоча б приблизне поняття string.А зараз дозвольте мені піти далі і перезапустити make hello-1. Я знову збільшу масштаб і схрещу пальці. Тепер, зробивши лише одну заміну, я виправив більшість помилок. Але, чорт його би побрав. Більше відсотків, ніж аргументів даних. Що я зробив не так цього разу?Тож все ще досить загадково. Але ця помилка в рядку 7 і символі 21. Отже, давайте дивитися тут. Майже непомітно. Але якщо ви подумаєте, про те, у чому полягають основні ідеї, можливо, ми зможемо розібрати це.Тож, printf - це назва функції. В дужках ми зазначаємо те, що вносимо як вхідні дані у функцію. Довільний людський звичай - використовувати дужки. В дужках ми поставимо подвійні лапки, а потім рядок, наприклад, "hello world."Але в тому прикладі зі Скретчем, який ми дуже коротко розглядали раніше. І у нас був відсоток d, що ще було в тих дужках, що я буквально прокричав? Так.АУДИТОРІЯ: Це те, що ви приймаєте [нерозбірливо] з [нерозбірливо], що ці [нерозбірливо]?ДЕВІД МАЛАН: Точно. Таким чином, у нас був відсоток d. Але після того у нас були лапки, кома, лічильник. Правильно. Те, що ми хочемо зробити, ми визначили як заповнювач. Тож я збираюся поставити тут кому, що ви хочете, щоб я написав?АУДИТОРІЯ: S.ДЕВІД МАЛАН: S, тому що в цьому випадку s означає назву контейнеру для зберігання. Це назва тієї скляної чаші. Тоді як раніше це був лічильник в тому простому прикладі зі Скретчем, який ми розглядали. А зараз, після двох замін, дозвольте мені збільшити масштаб і спробувати ще раз компілювати цю програму.Зараз я бачу, цей загадковий рядок. Але фактично це назва компілятора. Clang є назвою компілятора. make рятує мене від головного болю набирати ту довгу божевільну команду. Так що тепер, коли я введу ./hello-1, я повинен побачити "hello, David."Не викликає захвату, чи не так? Ми могли б зробити це набагато простіше, не розмовляючи про змінні і CS50.h і все це. Так давайте зробимо це трохи цікавіше.На додаток до CS50.h, у якому описані такі речі, як string, бібліотека CS50 також має декілька функцій. Тож, так само як багато років тому хтось написав printf і вклав її у stdio.h та у деякий інший файл.Ми, співробітники CS50, написали функції під назвами GetChar, GetDouble, GetFloat, GetInt, GetLongLong, GetString, і ми вклали їх у файли під назвою CS50.h і CS50.c. І ми вклали їх у CS50 Appliance. І інші люди також можуть завантажити їх з Інтернету, якщо вони захочуть мати їх у себе на комп'ютерах. Іншими словами, ми створили функції, які отримують вхідні дані від користувача. Я не знаю, якими є усі ці різновиди даних. GetInt начебто проста, як отримати ціле число від користувача. І, ймовірно, GetString нібито отримує слово або фразу від користувача.Тож давайте зосередимося на цьому. І я повернуся в appliance , і я піду далі і збережу цей файл як, давайте назвемо його hello-2.c як мою другу версію. І давайте зробимо кілька замін.Що, якщо я на цей раз, замість того, щоб прописати в коді David, що є неймовірно послідовною, але не викликаючою захвату програмою, пропишу GetString? Зараз зверніть увагу, що GetString має дужки, тому що вона не вимагає введення жодних даних. Вона лише отримає рядок від користувача.А тепер кілька слів про інші синтаксичні знаки. Крапка з комою тільки закінчує рядок коду. Вам не потрібно ставити її скрізь. Але це просто означає, що я покінчив із цим рядком коду, дозволь мені перейти до іншого оператора або функції. string(рядок) описує змінну. string нібито каже: "дай мені чашу, будь ласка. І дозволь мені покласти в неї рядок коду.А зараз знак рівності. Чому, по суті, еквівалентний знак рівності?АУДИТОРІЯ: Присвоєнню.ДЕВІД МАЛАН: Так, присвоєнню значення. Отже, якщо я, наприклад, назву цю функцію GetString, і ми миттєво побачимо, що вона запитає рядок у користувача . Це нагадує дозвіл мені написати Д-е-в-і-д на аркуші паперу. І коли я кажу: string s дорівнює GetString, дорівнює насправді не означає дорівнює у програмуванні мовою Cі. Це означає присвоення лівій частині виразу значення правої.Тож, у мене є рядок. І знак рівності означає: «помісти його в контейнер для зберігання під назвою s. А потім передай це функції printf, щоб вона зробила свою справу.»Відтак, кінцевий результат виглядатиме трохи по-іншому. Давайте введемо make hello-2. Одне з двох має працювати. А ви слідкуйте. make hello-2 спрацював. ./hello-2, Enter.Здається, в мене тут безкінечний цикл чи щось таке. Нічого не відбувається. Чому?АУДИТОРІЯ: Він робить безкінечний цикл. ДЕВІД МАЛАН: Це – безкінечний цикл. Він нібито чекає, коли я надам йому якусь вхідну інформацію. Отже, дозвольте мені піти далі, ввести "Девід" і натиснути Enter. А тепер він каже "привіт, Девід". Якщо я знову запущу його. Давайте введемо Роб. "привіт, Роб."Зараз це найгірший користувальницький інтерфейс, який коли-небудь існував. Очевидно, користувач повинен знати, що робити. Але все одно. Використовуючи ці ж блоки, як і в Скретчі, ми можемо вирішити цю проблему і сказати щось на зразок: "Ваше ім'я, будь ласка", двокрапка, пробіл, ставлю ліпки, закриваю дужку, крапка з комою. Знову багато дурниць із синтаксисом.Але зверніть увагу, я просто додав пазл над цим і над цим. Тож тепер, якщо я перезапущу це, hello-2, Enter. Почекайте хвилинку. Що не так? Він поводиться так само. Так.АУДИТОРІЯ: Ви знову не запустили «make».ДЕВІД МАЛАН: Я не запустив «make»знову , правильно. Тож, я змінив свій вихідний код. Але, знову ж, тут є той потік. Вихідний код через компілятор дає новий об'єктний код, або «0» і «1». Тому мені потрібно перезапустити make hello-2, Enter. Ок, здається, щось сталося. Крапка слеш hello-2. Ваше ім'я, будь ласка. І щоб було ясно, чому курсор на тому ж рядку? Точно. Я не поставив зворотний слеш n у своєму коді. Тож тепер я можу написати щось на зразок "Дейвен", Enter. Я можу запустити його знову і ввести щось на зразок "Гейб", Enter, і ми отримуємо іншу програму знову, і знову, і знову.Зараз, наостанок нам потрібно буде використати кілька інших можливостей. В кінці кінців ми маємо ввести певніі умови, щоб зробити речі умовними. Можливо, цикли, щоб ми могли робити це знову і знову.Можливо, було б непогано, якби ми могли приводити до виконання наші власні функції, наприклад, якби ми могли виконувати нашу власну printf або свою версію GetString і GetFlow, тому що, в кінцевому рахунку, навіть за допомогою цього середовища командного рядка ми можемо зробити найбільш візуально цікаві штуки.Дійсно, на завершення дозвольте мені зробити це. Я збираюся піти далі, закрити ці вікна і відкрити цей ярлик тут, що є лише більшою версією того вбудованого вікна терміналу. Тож Gedit має не лише місце для мого коду, але і вбудоване вікно терміналу, чорно-біле вікно, де я можу запускати команди.Я просто відкрив його більшу версію. А тепер піду в папку, яку вже заздалегідь розмістив на сайті курсу. І я відкрию файл з ім'ям thadgavin.c, написаний кимось іншим.І якщо ми подивимося на нього, це не той код, який ми будемо писати, оскільки метою його автора було написати якомога привабливіший код, який він чи вона могли написати, незалежно від того, чи могла б коли-небудь його зрозуміти інша людина.Насправді, кожного року проводиться подія під назвою «Оbfuscated C contest», подія для справжніх гіків, що пишуть коди, які ніхто не може прочитати, але які роблять щось дійсно просте або дивовижне. І подумали, що могли б завершити цю лекцію, подивившись на щось дійсно захоплююче, що ви могли б бачити лише раз. Але ми закінчуємо на цій ноті, точка слеш, thadgavin. Це і є те, що на вас чекає.На сьогодні це все стосовно курсу CS50. Побачимося в середу.[ГРАЄ МУЗИКА] |

Similar Documents

Free Essay

Every

...Thinking Styles Test - 'Word' document Read each set of words and tick the two in each group that best describe you. 1. A. I am imaginative. B. I like finding things out. C. I am realistic about things. D. I like puzzles. 2. A. I am organised. B. I am happy when things change. C. I like to ask questions about things. D. I like finding things out. 3. A. I like discussing and arguing. B. I like to get to the point. C. I like making things and thinking in new ways. D. I like seeing how things fit together. 4. A. I get on well with people. B. I like to do things with my hands. C. I like school work. D. I am adventurous 5. A. I am precise. B. I am flexible. C. I like things to be organised. D. I am inventive. 6. A. I like to share things and ideas. B. I like everything to be in order. C. I am sensible. D. I like to be independent. 7. A. I like to do better than other people. B. I like things I do to be perfect. C. I like working with other people. D. I think in a logical way. 8. A. I like thinking and talking about things B. I care about peoples' feelings. C. I am hard-working. D. I like to take risks. 9. A. I like reading. B. I like people. C. I like solving problems. D. I am good at planning and organising. 10. A. I am good at memory work. B. I am good at joining up ideas. C. I am good at sorting-out problems. D. I am good at coming up with new ideas. 11. A. I like to change things. B. I am good at making decisions. C. I am good at thinking on my...

Words: 814 - Pages: 4

Free Essay

Is This Rap's Logical Conclusion

...the poverty and violence, which people experience on the street, and many rappers are striving to achieve respect, money and fame through a rap music career. In the article “Is this rap’s logical conclusion” from 2003, the journalist presents the life story of 50 cent, a rapper who’s achieved all three elements: respect, money and fame. In the article, we are confronted with his horrible circumstances as a child, in which he was forced to live the life of a drug dealer. We hear the stories of his being shot, of selling drugs before he was a teenager, and of how he wrote a platinum hit-song in just under an hour. Throughout the article, the journalist is present in the text as he provides subjective observations. He conveys his own personal view of 50 cent’s life, and tells us how “he can flip the switch between being a though guy to a soft-spoken choirboy” (p. 3 l. 34-35). This is interesting for the reader because it sounds like the journalist is sitting in the presence of 50 cent, while making observations. The journalist is therefor bringing the readers into the conversation. In the article, the journalist chooses to show the readers how 50 cent has had a rough childhood. He speaks about how 50 cent’s mother was killed, how he used to sell drugs and earn 5000 dollars a day when...

Words: 984 - Pages: 4

Free Essay

Ad Analysis

...Dwayne Curry English 101 Dr. Rita Kumar 11 November 2009 AD Analysis of Reebok Advertisements The articles I chose come from the same exact magazine just different publish dates. They are targeting the exact same youth but in very different ways. My goal is to break the their interpretations and show what the ads are trying to represent in the companies eye. Reaching the target audience is the key for sales and with marketing departments being the the crucial part of business you know they are always coming up with ways to find them. My first Reebok article is cut in half. On one side of the photograph is superstar rap artists Jay-Z. The other side of the photograph is a picture of the projects he grew up in. You are able to catch a glimpse of a drug dealer's arm which has abut six rubber bands around it. In Jay-Z's part of the photograph he's in the penthouse suite overlooking downtown New York City. He's in a professional suit and is sitting in an expensive brown lunge chair. The other side of the photograph is black and white unlike Jay-Z's portion. Your able to really see the details of the photograph of an image portraying a younger Shawn Carter “aka” Jay-Z. This little article has an amazing amount of subtle messages. At first glance it's hard to figure out what exactly is the advertisement trying to sell. You see a strategically place Reebok symbol place in the lower right hand corner of the photo. It makes the reader have to search and by doing that that get...

Words: 1169 - Pages: 5

Free Essay

50 Cent and His Life

...of the back and came up on 50's left with a gun cocked. "Sneaky motherfucker, man," 50 says. "He did it right. He just didn't finish." The man hit him with nine shots at close range. 50 took bullets in the hand ("shell hit my thumb and came out my pinky"), the hip ("that one hurt-hurt"), the calf and the chest, and one to the face went through his left cheek and into his mouth. "You don't actually feel each one hit you," he says. "The adrenaline is pumping. You movin' and tryin' to get out of the way. I was bouncing around the back seat. We pulled off. We got a block or so. We had to pull over to get rid of the tote [gun]. Threw it in the sewer, then we got to the hospital. But I was up and still talking the whole time." A few weeks later, the gunman was murdered. 50 denies responsibility. He spent 13 days in hospital, then staggered out on a walking frame. Six weeks later, he began walking on his own. Now life was more precious to him. He began working on his body with endless push-ups, pull-ups and sit-ups. But, more importantly, there was now a large, squarish hole through the left side of his lower jaw and a piece of bullet in his tongue. He'd lost a bottom tooth and a U-shaped chunk of his gums, but his lazy tongue and the hole in his jaw gave him a slur like no one in hip-hop. "There's a different sound now when I talk, cos of the air around the tooth," 50 says. "Gettin' shot just totally fixed my instrument." The story of the shooting of 50 Cent spread throughout hip-hop...

Words: 523 - Pages: 3

Free Essay

Christmas

...can be set into one of five classifications. On Christmas morning, the first blessing you snatch is a customary box molded blessing wrapped in modest wrapping paper. The mark says that its from your cousin; nonetheless, its unmistakably evident that your two year old cousin did not compose his name in immaculate cursive substantially less select the blessing. You open your Aunt's blessing and discover a XXXL T-shirt, which she clearly acquired from the deal receptacle for $1.50. "Uh...thanks," you mumble as you look at your 220 pound outline. What a pointless blessing! Then again, your Uncle is certain to get you a cool and special blessing. There is one and only issue. Your mother never supports of the combat knife, Super Nintendo, or 50 cent show tickets. Goodness go ahead mother! In the event that your sibling even considers you amid the occasions, you ought to think about that as a blessing in itself. In any case, if your sibling happens to have some extra money and choose to use it on you, it appears that the blessing he picks is more to his preferring than yours. Your sibling may get you that feature amusement that he's been peering toward, however that you never truly tended to. Goodness well. It is not a complete misfortune. Assuredly the amusement will keep your sibling occupied and out of your hair! Your grandparents' blessing to you is dependably an endowment of need. Grandparents appreciate giving socks and blessing endorsements from Barnes and Noble. You know...

Words: 385 - Pages: 2

Free Essay

Change Is Always Good

...better version of yourself.” B. In today’s society, people now have to make changes in their life like Michael Vick, Domestic Diva, and 50 cent. C. C. I believe that most people have to experience something bad in their life to realize change is really good in for the better. For example like spending time in jail. II. Body A. First I’m gone to talk about when Michael Vick went to jail for running an illegal interstate dog fighting ring. B. Michael was sentenced to three years prison time in jail. Team members and football fan had no clue if he would be returning to the game again. C. So Michael decided to plead guilty to felony charges and will serve one year and eight months in prison. III. Next I will be talking about 50 Cent who is known for rapping and real name which is Curtis Jackson III who spends time in jail for drug-related charges. A. So the judge decides to sentence him 3 to 9 year’s prison time in 1994. 50 cent was still an aspiring rapper who was very determined to do something positive with his life once he was released from jail. B. 50 cent did his time and also earned six month boot camp instead of prison so he considered as an early release. C. While he was in boot camp he earned his GED. Right after 50 cent was release from jail, 50 Cent continue to rap and his popularity blew up with the release of his first album in the year of 2000. IV. Last I will talk about a woman...

Words: 543 - Pages: 3

Free Essay

Get Rich or Die Tryin

...Yea, ha ha, yea, yea If I can't do well, homey, it can't be done Now I'ma let the champagne bottle pop I'ma take it to the top Fo sho I'ma make it hot, baby (baby) I apply pressure to pussies that stuntin I pop Stand alone squeezin my pistol I'm sure that I gotta Now Peter Piper picked peppers and dont rock rhymes I'm 50 Cent, I write a lil bit but I pop nines Tell niggaz, "Get they money right," cuz I got mine And I'm around quit playin nigga you can't shine You gon be that next chump to end up in the trunk After bein hit by the pump, is that whut you want? Be easy nigga, I'll lay your ass out Believe me nigga, thats whut I'm about, gangsta You could find a nigga sittin on chrome Hit the clutch, hit the gear, hit the gas & I'm gone (Yea!) If I can't do well, homey, it can't be done Now I'ma let the champagne bottle pop I'ma take it to the top Fo sho I'ma make it hot, baby (baby) I'm down for the action, he smart with his mouth so smack em You holdin a strap, he might come back so clap em React like a gangsta, die like a gangsta for actin Cuz you'll get hit & homicide'll be askin, "Whut happened?" OH NO look who clapped em with the FO'FO' 20 inch rims sittin CHRO-CHROME Eastside, Westside niggaz OH NO, NO GO Even my mama said, "Something really wrong with my brain" Niggaz don't rob me they know I'm down to die for my chain G-UNIT! We get it poppin in the hood G-UNIT! Muthafucka whuts good? I'm waitin on niggaz to act like they dont know...

Words: 609 - Pages: 3

Free Essay

Philosophy of Hiphop

...Philosophy of hip hop Student’s Name University Affiliation Report on Film ‘From Mambo to Hip Hop’ ‘From Mambo to Hip-Hop: A South Bronx Tale’ is an hour long documentary that narrates a story about the inventive life of the South Bronx, starting with the Puerto Rican immigration and the acceptance of Cuban rhythms to form the New York salsa resonance; enduring with the fires that damaged the neighborhood, but not the innovative spirit of its inhabitants; accounting the ascending of hip-hop from the ruins; and finishing with reflections on the influence of the neighborhood’s songs to make sure that the endurance of a number of generations of its people, and, in the course, take the world’s pop customs by storm. ‘From Mambo to Hip-Hop’ dances all the way through the account of a region that took care of two musical movements: the mambo that developed into salsa and the hip-hop that cropped up from the most distressed days of the South Bronx. Created by Steve Zeitlin and Elena Martinez , who are principals in the New York ‘folklore group City Lore’, and directed by Henry Chalfant, who is a longtime speaker of the South Bronx who worked together on a documentary from the early 1980’s “Style Wars,” “From Mambo” dashes by, driven by tempo that varies through the decades. Mambo and hip-hop are the type of dissolving pot experience that New York stirs and heats. Their ancestry is African, refracted through the Caribbean and the town. In their early stages...

Words: 947 - Pages: 4

Free Essay

Hi My Name

... Curtis “50 Cent” Jackson is continuing to pursue his acting career and is starring in, as well as producing the new film “Freelancers”, which was written by L. Philippe Casseus. Jackson will be playing the son of a deceiving NYPD officer who becomes affiliated with the corrupted force that his father helped build. “Freelancers” begins filming on March 28 in Grand Rapids, Michigan. Jackson has also been acknowledged for his prior films “Righteous Kill” and “Get Rich or Die Tryin’.” In my opinion, “Freelancers” will just be another poor written script and will probably serve as another embarrassment for 50 Cent. “Freelancers” sounds like another one of 50 cents’ stereotypical films that contains an extraordinary amount of violence, along with an excess of unnecessary profanity. For example, 50 Cent’s previous movie “Get Rich or Die Tryin’ is an autobiographical film of his own life. The film portrays 50 Cent’s disturbing life that consists of drugs, sex, violence, robbery, and most importantly, rap music. I believe that since 50 Cent wants to be represented as a convict, he should have no business in trying to continue his success as an actor or producer. If 50 Cent was such a great actor and producer, I’m sure he would of had many films out by now, but it seems to me that he is just in need of something that can boost his declining career. Additionally, 50 Cent should be ashamed of his lyrics in his rap songs. Therefore, why would anyone want to hire 50 cent. I do...

Words: 323 - Pages: 2

Premium Essay

Infulence of Media

...shows like Jersey Shore, Keeping up with the Kardashians, America got talent, So you think you can dance, American Idol, and the list goes on. These shows have “made” commoners into stars.. That goal has had people seek other applications on the internet rise up to cash in on the benefits. The Years of Fast and the Furious had people deck out cars with the dream of being king of the road. Street racing, however dangerous, had become a lasting fad since the days of “chicken" in the 50’s and 60’s. Product placement on shows and commercials has helped Coca-Cola stay in the refreshment top spot since 1886. Other companies have found their way in to the American Culture like sport teams memorabilia, sponsors, and events for advertisement. Michael Jordan has a net worth of 650 million (90 million coming from his career with the Bulls) just for his name thanks impart to Nike and the shoes that keep on selling out. Rappers have taken names of known criminals to emphasis the “bad boy” concept in American Culture. 50 cent, Rick Ross, Frank White (Notorious Big other name), Escobar (Nas other name), Capone& Noriega all rap about a lifestyle on the criminal side and those emulate the rappers and want to be them take the words for truth. This type of media has encouraged both spectrums of bad and good. Artist like TuPac has done some raps to praise women...

Words: 509 - Pages: 3

Premium Essay

Style Wars

...Destiny Aguilera January 13, 2011 Style Wars 1. Describe Style Wars as if you were explaining it to a person who has not viewed the film. The documentary, Style Wars, is basically about the three things that made up the Hip Hop culture in the 1970’s to early 1980’s. The first was graffiti and how the teenagers of the time would use this type of art to express themselves. They would spray paint their names on the sides of buildings and subway trains in New York City. Another way of Hip Hop culture was expressed by a type of dancing called break dancing, and the kids would compete in competitions to see who the best was. Finally, the last form of expression was rap, where the kids would express themselves in the form of words. This documentary shows how teenagers used these three things to express the way they felt, and it also shows how the adults were completely against it. 2. Write about two facts or issues presented in the film that you had not been aware of before. One thing I did not know was how much the graffiti meant to the artists. I thought the teenagers did it just to, I guess, ‘stick it to the man’, or show that they were above the law. I didn’t know that they saw it as art and took long hours of practicing to get it right. Another thing I didn’t know was that all of the different moves in break dancing had names. 3. Does this film have merit to show to college students? Explain why or why not. I do not believe it does, unless the film...

Words: 319 - Pages: 2

Free Essay

Concept Chart

...Popular song “ I like It I Love It * Country singer * Net Worth: 60 million Country Music: Tim McGraw * Popular song “ I like It I Love It * Country singer * Net Worth: 60 million Soul/R&B: Mariah Carey * Successful female singer * Very popular throughout the 90’s and early 2000’s * First movie as an actress, “Glitter” was a bust. * Net Worth 510 million Soul/R&B: Mariah Carey * Successful female singer * Very popular throughout the 90’s and early 2000’s * First movie as an actress, “Glitter” was a bust. * Net Worth 510 million Hip Hop/Rap: Curtis Jackson a.k.a 50 Cent * Highly successful * Single “In Da Club” peaked nine weeks at #1 on the billboard charts. * Was shot nine times and lived * Net Worth 140 milllion/Forbes.com Hip Hop/Rap: Curtis Jackson a.k.a 50 Cent * Highly successful * Single “In Da Club” peaked nine weeks at #1 on the billboard charts. * Was shot nine times and lived * Net Worth 140...

Words: 290 - Pages: 2

Free Essay

B-29 Superfortress

...What is your position on our current global situation? My position in our environment is very high because as a teen I don’t know the changes that are happening in the world unless I am told that what us teens are doing to our planet is killing it slowly. In my essay I will include Economic, Political, and Environmental changes that us humans are doing to our planet. I view earth as a home because without earth where would we live and where would breath, being on earth is good but it’s also bad because we are not taking care of our planet like we’re supposed to and if we don’t take care of the planet it will die and there would be no life living anymore. My role locally is important because I can make a huge difference if I just speak up, but my role globally well there is a tremendous difference there because I will not be able to the word out quickly enough because I’m just another teen living on this earth. An increase in population makes excessive demands on natural resources and increases the demand on agriculture and livestock, using chemical fertilizers, insecticides, and herbicides to increase production is actually polluting the air, soil, and water with toxic chemicals. Human population is growing like never before, the list of problems this is causing, or at least complicating is a long one. It includes shortages of all our resources, war and social conflict, limit, personal freedom overcoming health and survival for other...

Words: 258 - Pages: 2

Premium Essay

Movie Paper

...50 First Dates is a movie about a guy and a girl falling in love, but have struggles because the girl Lucy Whitmore played by Drew Barrymore is suffering from Anterograde Amnesia. Henry Roth who is played by Adam Sandler is a veterinarian at Sea Life Park in Oahu Hawaii who is known as a womanizer who is afraid of a comment. Barrymore character is known as a sweet teacher who loves life and her family. In the movie Lucy is suffering from anterograde amnesia, and Roth is trying to win her heart over. Threw out the movie it shows the struggles Lucy’s family and friends have trying to keep that she has amnesia. Roth tries to win over Lucy’s heart but after finding out that she has anterograde amnesia he realizes this is not going to be an easy task. Roth is eventually successful in gain the trust from Lucy’s family and friends, and with that they help Roth win over Lucy’s heart. The movie ends with Lucy’s breaking up with Roth because she feels like she doesn’t wan to stop him from living his life. Roth leaves for an excursion he has been planning to see walruses in the wild, but couldn’t end up leaving without taking his Lucy with him. (Peter Segal) The character played by Barrymore, Lucy Whitmore is suffering from anterograde amnesia. On TheHumanMemory.net Luke Mastin states “This is the loss of the ability to create new memories, leading to a partial or complete inability to recall the recent past, even though long-term memories from before the event which caused the...

Words: 1108 - Pages: 5

Free Essay

Film Analysis

...Maydeli Medrano Dr. Price Psychology 2301-83421 2 February 2013 50 First Dates Film Review The film I decided to watch was 50 First Dates (2004) starring Adam Sandler as Henry Roth, Drew Barrymore as Lucy Whitmore, Rob Schneider as Ula, Sean Astin as Doug Whitmore, Blake Clark as Marlin Whitmore, and Amy Hill as Sue (IMDb). I decided to choose this film because as I read what it was about in some websites I saw that it was both a romance and comedy film, and romance movies . I also noticed that Adam Sandler was in this film, and since I have seen a couple of his movies, I know they are hilarious. I actually ended up liking this movie a lot. The film is about Henry Roth, a veterinarian in a water park located in Hawaii. He dates many tourist girls for one night only because he is afraid that if he gets involved in a serious relationship with a local girl, this might stop him from going to Alaska to study walruses (something he dreams about doing). One day as he sails on his ship, “The Sea Serpent”, it broke down and went to a nearby café located of the coast and a woman caught his eye. He did not go up to her because he assumed it was a local woman. The next day, he went to the café again and saw her there again, but this time he decides to go up to the woman. The woman’s name is Lucy. They get along very well and there is an instant connection between them. They agree to meet at the café the next day for breakfast. Henry goes to the café as they agreed and after Lucy...

Words: 1568 - Pages: 7