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

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Introduction to C Programming

Transcript

[MUSIC PLAYING]

DAVID J. MALAN: All right. This is CS50. This is week one, because of course, last week was week zero. And this is the week where we'll actually start programming in a much more traditional way, that programming language we promised called C. Of course, we started with this. And hopefully by now, with problem set 1, you've had a little bit of fun, even if you've played with it before. And the goals of Scratch, beyond making things feel very accessible and user friendly is really to elucidate some of the fundamental concepts that we'll see again today, and really every week subsequently, like functions and conditionals and loops and variables and so much more. And in fact, among the goals of Scratch is, again, to plant these visuals in your mind. So even as today onward feels all the more like a fire hose, especially when it comes to really weird, cryptic textual syntax, the ideas are still going to be the same.

So today, this program, Hello, world, becomes this instead. And in fact, just to color code things temporarily, I dare say that what I've color coded here in orange, which looks probably, to those of you who've never programmed, pretty cryptic is the equivalent of when green flag clicked orange puzzle piece like this. What remains is just one line in purple with a bit of white, which is what ultimately is going to get the screen today to say, Hello, world on the screen. And of course, we had a name for something in purple. In fact, if we rewind to week zero, this block in purple represented what type of functionality? AUDIENCE: [INAUDIBLE]. DAVID J. MALAN: A function itself, an action, a verb that gets the computer to do something. So what looked like this last week is about to look like this. Let's take away the color coding and focus really on what we're going to now start calling source code. So this is what programmers do in the real world.

This is what software developers, software engineers do in the real world. They write code that looks like this. And clearly, it's a little English-like, but it's not English in the way you would compose an essay or an email. Clearly, there's some patterns and some special syntax to it that will highlight ultimately today. The problem is, though, that computers, of course, don't understand source code. They only, per last week, understand zeros and ones. That is it, the so-called binary system. So somehow, we've got to get what already looks cryptic into something that looks at a glance even more cryptic, the zeros and ones that computers do understand. And for today's purposes, just know that built into your Macs, PCs and phones, there is a built in understanding of what these patterns mean. Maybe it means a number, maybe it means a letter. But today, maybe it means an instruction, like print something on the screen, or save something, or load something.

That is to say, computers use patterns of bits not only to represent all the stuff we talked about last week-- numbers, letters, colors, images, sounds, and all of that, they also use patterns of bits to represent fundamental functionality. Print things, play things, much like those same scratch blocks. But no computer scientist really, unless they take out a paper pencil or write a program or use a website to convert this can read this and know what's going on. That's why we humans are actually going to use not machine code, as it is called, the zeros and ones that computers understand, we are going to start writing source code. And last week you already wrote source code, but in the form of dragging and dropping those puzzle pieces. So this too is going to be the paradigm that sort of guides us through the entire semester. Problem solving programming is really about input becoming output.

And we'll focus today then on a certain type of input becoming output. Someone has to get the source code, that's written in a language like C, into the machine code, the zeros and ones that the computer actually understands. So source code today is going to be our input. Machine code is going to be our output. And we're going to give you today a special program called a compiler, whose purpose in life is to translate one to the other. And there's compilers for different languages in the world. We're going to focus on one that supports today's language, known as C. And here, as promised, is the programming environment we are going to use. It's tailored to CS50, which is to say, we've pre-installed certain software that you might find useful during the term. But for all intents and purposes, the tool you will use for CS50 problem sets henceforth is a very popular industry standard tool called Visual Studio Code, or VS Code for short.

We are using a cloud based version of it that lives at literally this URL, cs50.dev. You can sign in to that so long as you have a free GitHub account, for which you signed up presumably already. And that will give you access to not only an industry standard programming environment, but again, an environment that has some CS50 specific things pre-installed. And at the end of the semester, or even in the middle, if you so you're so inclined, you can actually download for free VS Code onto your Mac, PC. You can disconnect from the internet and you can actually program on your own computer. Caveat, though, is that you tend to hit technical support headaches in the very beginning of the term, so we suggest you do that later in the term once you're already comfortable with this cloud based environment here. And here it is. This is what programming shall look like,

whether we're using C now or Python in a few weeks or JavaScript or SQL thereafter. So here is what looks-- what is VS Code configured as follows. At the top right, you'll generally have one or more tabs for code, much like tabs in a browser. And this is where you'll write code that looks a little something like this. And in fact, this is exactly the code that you saw a moment ago. What VS Code does, among other things, is it actually highlights your code for you. It colorizes it in what's generally an illuminating way. So I did not choose to make this red. I did not choose to make this blue and this purple. The computer sort of automatically does that for you, as we'll soon see to draw your attention to different ideas in the program itself that all happens automatically. At the bottom here, you're going to use a more advanced interface today onward, known as a command line interface in the form of a terminal window.

So you can still use your mouse or trackpad and click and drag and do things like that in this environment. But you'll find, and many programmers prefer that it's much more efficient ultimately to use your keyboard more often than the mouse or the trackpad. So we'll introduce you to that text based terminal window there. Up here at top left, you'll have a File Explorer. So what's nice about VS Code is that not only will you have textual commands, with which you'll get comfy, you also have a normal Mac or PC or phone nowadays, like literally files and folders will visually appear to you so you can play with or manipulate them there. And then, lastly, this is sort of like the menu, the so-called activity bar that just has icons for various features, including CS50's duck. So in fact, if you poke around, you'll see ultimately a duck icon when you log in, which is your own CS50 specific chat bot of which you can ask questions throughout the process.

So now that we've got VS Code here, let's go ahead and actually consider what it represents. So this is generally, for jargon sake, a graphical user interface, which means buttons and icons and menus and all of that. We all take that for granted on most any device nowadays. That's abbreviated, just so you know, as GUI, G-U-I. But built into VS Code, again, is what's not only the terminal window by name, but conceptually this is a command line interface. So not a graphical user interface, but a command line interface, whereby there aren't icons to click on or double click on. Rather, if you want to run a program, you use the command line interface, or CLI, to type the name of the program that you want to run. And so this will feel like a step backwards initially today, because we all tap and point and double click on things nowadays. But again, it's going to give us more power, more efficiency ultimately beyond this.

So with that said, let's go ahead and actually use it for just a moment. During class, you're welcome to follow along. But suffice it to say, we'll generally go somewhat quickly. Really, you're going to learn how to program by way of the problem sets each week. I'll introduce and focus on the concepts, the ideas, the sort of primitives that will get you started, but only through actually doing the problem sets is the muscle memory and practice going to come. So not to worry if it doesn't all go down easily the first time around. So here is the code that I claim is equivalent to last week's Hello, world program. Let's actually go ahead and do this in the programming environment. So I'm going to go ahead and switch over to VS Code itself, which is now running on my Mac here. It's not just a screenshot. And I'm going to go ahead and do the following to get started with programming. I'm going to write literally in my terminal window, the word code,

and I might have to give it focus by clicking down in that quadrant of the screen. And then I'm going to give the name of the file that I want to code. And in this case, I'm going to propose that we call it hello.c. In the world of Scratch, when you downloaded it, you might have noticed the files are all called like SB3 or some such file extension. When writing code in C, you literally name the file something dot C by convention. But notice some other details. Especially if I zoom in, everything I've typed thus far is lowercase. There's no spaces. And so this is going to be important. And unfortunately, computers are not forgiving. And odds are one of the first stupid mistakes you'll do is miscapitalize something, misspell something, add too many spaces or the like. Not to worry. In time, that kind of muscle memory will come with practice. So let me zoom out.

Let me now just hit Enter and you'll see at top right the Code tab that I promised. So I'm going to go ahead and type out this program pretty quickly, because I've done it before. Include stdio.h, int main void, and then some curly braces, as they're called, and then printf quote unquote. Hello, comma, world, backslash n, close quote, semicolon. All right. So that's a lot. But that too will come in time with practice. But this is the exact same code that we saw just a moment ago. Indeed, if I zoom in, it's color coded just as in the screenshot, and thus I have written my first program. VS Code will automatically save for you, but you can also hit control or Command S to ensure that it's saved. But notice what's happened at top left. Not only do you see my code over here, you see a visual icon, just like on a Mac or PC that, yes, this file now exists in your account. And that too is what you're getting with VS Code for CS50.

You're getting your own sort of server in the cloud. It's called a container nowadays. So there's some virtual disk space somewhere in the cloud, ala iCloud or Google Drive, that's going to store all of your files. And at the moment, because I refreshed my account before class, I only have one file in my own account. What's this? What's this? Well, this is like my ID number for GitHub. Not really a big deal. That's just randomly generated by GitHub. Urban Adventure is the name of my programming environment today, otherwise known as a code space. This is just a GitHub thing which is, again, one of these cloud companies. Instead of choosing random letters and numbers to uniquely identify all of our programming environments, it's popular in the tech industry nowadays to just put together random English words that sometimes sound kind of cool. But it's just by coincidence, not something I chose. Yours will be different.

All right, so I've written some code. I created hello.c. I typed in all of that code. I confirmed visually at left that it was created. I'm going to hide my File Explorer henceforth, just so that we can focus on the code. How do I actually run this program? Well, on a Mac or a PC, we would be in the habit of like opening the folder and double clicking on it. Or on your phone, you would take it out and tap on an icon. But not here. Here, we're focusing primarily on the command line interface within this whole environment. So I'm actually going to have to introduce a few commands. You saw already the code command, which for our purposes is VS Code specific, that just creates a new file called hello.c in this case. But I need two other commands to actually run this program. The first nicely is called make, and then I specify what program I want to make.

And then a little weirdly, I have to type dot slash hello. But just to take a step back, make hello. If this is about to be my second command that I type, what does that step represent, perhaps? Given what I said just a minute or so ago. AUDIENCE: That's going to translate your source code into ones and zeroes. DAVID J. MALAN: Perfect. So make represents the compiler, so to speak, the program that converts source code to machine code. I have to do that for now manually by running make hello. Now, make is kind of smart, and even though I'm saying make hello, not make hello.c, make it smart, and it's going to say, if you want to make a program called hello, I'm going to assume that there is somewhere in this folder a file called hello.c. So you should not type make hello.c. You just type make hello. And then this third command, even more cryptic, what might it do? If this is step three of three. That's going to run the machine code. It's going to tell the computer in this folder,

the dot implies this current folder, and dot slash just means something in this current folder. Run the program called Hello. So that's it. Like there's three steps to writing a program in C. You create the file, as with the code command. But there are other ways to do that too. And you don't even have to use VS Code. You can use dozens of other alternative programs in the world. You run the compiler, which, in this case, is called make. Little white lie, make's not actually the compiler, but more on that next week. But make is going to trigger compilation of this code. And the last step three is to execute, or run the program called Hello. So let me go back to VS Code here. And you'll see that my code is still at the top. My terminal window is at the bottom. I hid my File Explorer, just because it's not that interesting anymore. And I'm going to do what you proposed, which was M-A-K-E space hello. All lowercase. Enter.

And ironically, thankfully, nothing happened. And that's actually a good thing in this environment. If nothing seems to happen you probably did, good. If anything does seem to happen on the screen, you probably screwed up and you've made some mistake. So seeing nothing is generally a good thing. But what has happened? Well, let me actually go back and open up my File Explorer. And notice, there's not only hello.c, but there's a second file now. Hello, which is the name of the program. So Hello is the program I want to run. I'm going to go back to my terminal here and to run this program, I'm going to do dot slash H-E-L-L-O. I'm going to cross my fingers, as I'll often now do, and voila, my very first program in C. How else can we see this file? Well, down here in my terminal window. Let me zoom in. You keep seeing dollar sign. That has nothing to do with currency. It's just a weird, geeky convention that your prompt at a terminal

window, like where you type commands, generally starts with a dollar sign. Sometimes it's a hash symbol. Sometimes it's an angled bracket. It depends on the system you're on. But dollar sign is very common. It just means type your commands here. Well, I've typed code, I've typed make, and I've typed dot slash hello. But I can type other things too. And more on these later. Like ls, which doesn't actually spell something, but is short for list, L-I-S-T. Programmers tend to just be as succinct as they can, so most commands are not full words. They're often abbreviations. If I hit Enter now, you'll see also two things. You'll see hello.c. And you'll see in green, just to draw attention to it, hello as well. The asterisk here just means in the programming environment, this program is executable. Like you can actually run this by doing dot slash hello. The fact that this is just white here, that just means it's some text file.

It's in fact source code. So in other words, ls lists the file in my current folder. Or you can use your human eyes in the File Explorer at top left and just look at what files exist. These are one and the same. One is a GUI one, is a CLI. Graphical command line. And so forth. And we'll start to take these kinds of paradigms soon for granted. But let me pause here and see thus far, now that we've written our first of many C programs, any questions? Or confusion we can clear up?

It's OK if you don't understand most of the lines of code. That's what today is about. Yeah. AUDIENCE: I don't fully understand the difference between hello and hello.c. DAVID J. MALAN: What's the difference between hello and hello.c? So hello.c is literally my source code. It is a file that exists somewhere in the cloud that contains all of the code I myself wrote. The hello file is the file that the compiler created for me by converting the source code to the machine code. So inside of hello, theoretically, is a whole bunch of zeros and ones. We can't quite see them. But if I do this, let me zoom out. Let me click on hello. And notice that VS Code is going to yell at me. This file-- the file is not displayed in the text editor because it is either binary-- that is zeros and ones-- or uses an unsupported text encoding, whatever that means. If I do open it anyway, but I don't recommend this. Like heed these warnings.

You won't see zeros and ones, but you will see sort of nonsense. And this is because VS Code is trying to interpret those zeros and ones incorrectly, as ASCII text, like English text. But it's not. They're instructions for the computer. So as soon as you see scary red stuff like this, like undo, close whatever tab you open, because odds are you can only break the program you just created. It's not a huge deal. You can recreate it. But that's what's inside of those files. Yeah. AUDIENCE: What if [? you don't ?] [INAUDIBLE]? DAVID J. MALAN: Really good question. What if we don't type dot slash hello we, just type hello. Well, let me do this. Let me hide my File Explorer again because it's not that interesting here on out. I'm going to clear my terminal window by hitting Control L, just to be neat and tidy in class. Or you can literally type clear and it will clear it. But again, that's just to keep things tidy.

Your TFs might do that in section 2. If I just type Hello, enter. I'm going to get this, weirdly. Bash, hello, command not found. So more on bash down the line. But this just means literally the command hello is not found because you need to tell the computer where it is. So dot slash hello means run the hello program that is, in fact, right here. By contrast, you don't run dot slash for code, for make, or other commands that we'll soon see, like ls, because why? Those are installed in the system for everyone, not just in your individual folder. So that's the difference. Any programs we write, it'll be dot slash something. All right, so let's tease apart what is actually going on here and see if we can lean heavily today on Scratch, especially as the syntax gets weird, perhaps a little overwhelming. Still the same idea. So this last time, of course, was our Scratch program that just said Hello, world.

I claim today that this is the nearest equivalent that any programmer can convert Scratch into C. If we color coded it accordingly, indeed, this sort of lines up with when green flag clicked is the orange. And then the purple is just the equivalent of the say block. So the say block, we said earlier, was a function. So let's compare these things side by side because there's actually some rhyme and reason to what MIT did with Scratch, as to why these shapes look like they do and so forth. So in Scratch, there's a function called say. Recall that it takes an input, otherwise known as an argument, or a parameter is another name. And that's always provided in these white ovals, zero or more white ovals. In C, we've already seen, but let's do it a little more pedantically, the equivalent say is essentially the word print. Why did MIT say you say?

Just because it's a little more kid friendly. But print is the idea in our environment. It's actually not print, it's printf, because we're going to be able to format our text in interesting ways. More on that in a moment. But notice, the opening parentheses and closing parentheses here conjure up the idea of that white oval. So that's kind of intentional on MIT's part. What, though, in C goes between these parentheses? Well, literally the input or the argument you want to pass to the function, like Hello, world. But in C, you have to be a little more pedantic because you don't have a nice little graphic like this purple block with the white oval. You have to surround everything in double quotes. Those of you with prior programming experience, in C, you need double quotes, not single quotes in this context. And then there's this arcane detail here, backslash n, which we'll come back to in just a moment.

But that's essentially what's going on, line by line from Scratch to C, there's kind of an equality between those two, even though, of course, look a little bit different. Well, let's see what that backslash n is doing, just to highlight some details here. So let me actually zoom in a little bit here and let me go up to my code. And let me just recklessly delete the backslash n. I'm going to let it auto save. I'll zoom out. In my terminal window now, I'm going to run make hello to recompile the code from source code to machine code, because I changed the source code. Nothing seems to happen. That's good. Now I'm going to type dot slash hello, enter. And there's a subtle bug. Since I made that change. What looks wrong to your eye now? AUDIENCE: The dollar sign [INAUDIBLE]. DAVID J. MALAN: Yeah, the dollar sign, our so-called prompt is at the end of the line instead of on its new line. I mean, this isn't really a deal breaker.

Like the code works, and you can still type a new command. But it just looks a little stupid. Like this was not the intent of the program. It's sort of good practice to move the prompt to the next line, and that's because the backslash n is what we're going to call an escape sequence. So it turns out in programming, you have to tell the computer exactly what you want it to do. So if you want a new line, the equivalent of hitting Enter on the screen, you have to tell the computer to put a new line there. What you do not do is this. If I zoom out and I go into my code here, and I'll zoom in on the code-- if you want to put a new line, you don't do this. Why? It's just confusing for the computer. Like, wait a minute, is that a typo? Did your lines just wrap. Do you want to put a new line there. It just looks stupid. And it makes it less line based, the code itself.

So humans decided years ago, if you want an actual line break, don't just naively hit the Enter key. Literally tell the computer, put a new line here. If you want to move two lines down, just do two of those. If you want three, just do three of those. Well, why the backslash? Again, these are what are called escape sequences. And you don't literally want an n, let alone [? an ?] n n. What you want is a new line, which is represented in code as simply backslash n. Now, for the mathematicians among you, what we're doing now by writing, using functions like printf is just sort of like f of x notation, if you recall that from high school or prior, where f is a function, x is an argument or an input thereto, and we're using parentheses in code, just like mathematicians would, to write functions like these. And the types of functions we're using right now still follow this model. You've got input, you want output.

In this case, the input to printf, for instance, just like the say block, is what's called an argument. The output, though, of the function printf is what we call a side effect. And the easiest way to think about that is a side effect is just something that sort of happens on the screen, visually, [? audibly. ?] It just sort of happens. And there's that effect on the screen. And we'll contrast this with other types of outputs from functions. But for now, we're focusing on just this, which is reminiscent, of course, of what we did last week, which is if you type Hello, world into the white oval, use the say puzzle piece, you get out the side effect of the cat appearing to have said hello, world. Now, as for those escape sequences in C, there's bunches of them, but very few of them will we actually use in practice. Backslash n is a new line. Backslash r is a little more subtle and it's kind of a feature of yesteryear.

It moves the cursor not to the new line, but to the beginning of the line. Kind of like an old timey typewriter, if you've seen how those work. Sometimes, though, you might want to print out an actual double quote. But there's a problem, of course. If this is my code here, and I'm already using double quotes as sort of special symbols to surround the text, I want printf to say it would probably be a little-- like if you wanted to say hello, world, with sort of finger quotes, why might this not be a good idea? If you think about this from the computer's perspective. Why is this probably not the right way to do this? Yeah? AUDIENCE: [INAUDIBLE]. DAVID J. MALAN: Exactly. The computer is indeed going to read your code top to bottom, left to right. And when it sees the first open quote, OK, that's fine. It understands that. But when it gets to the second quote, it's going to assume, oh, wait a minute. Maybe you only want me to say hello comma,

and then it's going to keep reading and be like, wait a minute, why is there the word world here. And then wait a minute, now there's two more quotes. It's just confusing. It's ambiguous. And computers need you to be, again, very precise. So if you want a quotation mark to literally be displayed on the screen, you would escape it, so to speak, which looks a little weird and takes some getting into the habit of. But this just solves that kind of problem. And similarly, might you use single quotes in other contexts? More on that soon. And if you really want to bend your mind, how do you actually print a literal backslash, if you ever care to? It's not that common a character to type, but if you ever want it on the screen, it seems that we're using backslash as a special character that says, hey, give me a new line or give me a carriage return or give me a double quote.

Weirdly, in programming, if you want to type a literal backslash on the screen, you literally do backslash backslash. But that's it for sort of weirdness for now. But this is to say, humans tripped over these same problems years ago. They came up with solutions, and now we indeed have these conventions in code. All right. So let's tease apart some other features of this in every program we're going to write, namely what's at the top of this file. So at the very top of this file, there is this cryptic looking hash include, or pound include standard io.h in angle bracket. So this is a little weird. We'll talk more about this next week, too. But this is what's called a header file. Any file that ends in dot h is not a source-- well, any file that ends in dot h is what we're going to call a header file. And inside of that header file is functionality that maybe came with the system, came with the programming language itself.

So for instance, I'm going to do this. I'm going to go back to my code here and I'm going to make a very common mistake that you yourselves might make in the coming days, where I just forget that line because I don't even understand it in the first place so I certainly didn't think to type it here. Now, if I go back to my terminal window after clearing it and I run make hello, because I want to recompile it because I've changed the source code, I'm going to see a fairly cryptic error. I mean, there's more error on the green than there is code up here, but you'll get the hang of reading it to try to figure out what's going on. And I'm seeing this. Hello.c, line 3, character 5. So that just means line 3, colon, character 5. From left to right, it's sort of a visual cue as to where the problem is. Call to undeclared library function printf with type dot dot dot. And then the rest kind of overwhelms me visually at this point. But that's a hint.

If you do not include that header file at the top of the code you've written, you do not have access to what's generally called a library. A library is a collection of code that someone else wrote for you. Maybe it was MIT, maybe it was the authors of the C language itself years ago. Maybe it was CS50 if we wrote some code for you. A library is a collection of code that someone else wrote for you and you access it, again, by including header files that those same people wrote for you. So if I go back to my code now-- let me clear my terminal window just to be less overwhelmed. Let me undo what I just did and put that file back. Can you perhaps infer, just functionally, what is inside of standard io.h that, again, someone else wrote? What must be inside? Printf. So whoever invented printf decades ago probably put that code in this file. And so by including it, so to speak, in my code, I now have access to printf functionality.

So that's all. And again, C is lower level than scratch. It's obviously text based, which means you have to be a little more pedantic yourself as to what you want the computer to do for you. And if you want to use someone else's code, you indeed have to include it. Scratch didn't bother with this, but we indeed do need to do this in the context of C. As an aside, just to preempt some unnecessary headaches, this word is not studio.h. Every year, a non-zero number of people can't understand why their code is not working because studio.h is not found. It's standard io, stdio.h. That's one of the first frequently made mistakes otherwise. All right, so remember that. Let me undo now the unnecessary quotes I added here. And let me propose that we show you where you can learn more. So all of these libraries generally are documented. People wrote instructions for how to use them.

So you don't just have to listen and pay attention only in class. You don't have to pull up a book. There tends to be online documentation as well. For instance, for the standard I/O header file. And the documentation in the world of programming for C specifically are called manual pages or man pages for short. Unfortunately, they're really written decades ago for the more comfortable among you, those who have an eye already for programming. And so what CS50 has done at this URL, manual.cs50.io, is we essentially have more user friendly versions of the documentation for this header file and others. So for instance, if I pull up manual.cs50.io, you'll see a web page like this. And if I just scroll quickly, you'll see a whole bunch of header files, .h files, and a whole bunch of functions beneath them. And there's only a couple of dozen or so here. And indeed, per this checkbox at the top frequently used in CS50,

we have highlighted the functions that odds are over the next month and a half like you will probably want to use. If I turn off that less comfortable mode, there's actually hundreds of functions that come with C. And like no programmer knows all of these functions. What they do is they read the manual when they want to find some new piece of functionality. So I'm going to simplify this. I'm going to scroll down, though, to stdio.h, for instance here, and you'll see more functions that we'll eventually get to. But if I click on printf, you'll see hopefully some fairly user friendly instructions for how this thing works. For instance, under synopsis, you'll see that we tell you what header file you should include in order to use it. Below that is something called a prototype. More on that later. But below that is a description. And here is where the CS50 staff have written in layperson's terms

explanations of how this function works, how to use it, and so forth. But if you'd rather see what the real world uses, you can turn off that mode and you'll see much more arcanely the original language. So in short, these are sort of training wheels that you can turn on and off at your leisure. But ultimately, this is real world documentation as well. So if we want to see something else, for instance, let me go back to the main menu. And as we'll see today, there are actually functions in a header file called cs50.h that for a few weeks, we're going to lean on heavily. Long story short, it's actually kind of hard. It's annoying in C to get user input, ironically, to get the human to type in a word or a number. You have to jump through some technical hoops to make that happen. And we'll show you how to do it like the real way in a few weeks. But for now, among the first training wheels is a CS50 library code that we wrote that will just make your life easier.

And indeed, we're going to give you access to functions that simplify the process of actually getting input from the user. So case in point, we're going to give you access to functions like get_string, when you want to get a string of text from the user-- a string is just text. So if you want to get one character, one word, one sentence, one paragraph, you can call a function called get_string. We're going to give you another one called get_int. When you want to get an integer from the user, like 1 or 0 or negative 1 or anything else, you can use that function as well. And we'll see today too there's other functions you can use from CS50's library. In a weeks' time, we'll take these away once you don't need them anymore. And you'll see what those library functions have been doing all along for you. But for now, let's focus on this. Perhaps the most useful of them, get_string,

and solve a problem that we did already pretty easily in Scratch. So recall in Scratch, this was a program that used two functions. Three, in fact. Ask, to ask a question of the user. Say, to actually display something on the screen. And join, to combine the default of apple, banana. Or in this case, Hello, and whatever the human's answer was. So this made our Hello program a little more interactive last time. How can we actually translate this into a similar paradigm now? So input and output is the story, as always. In this case, we have arguments going into those functions. But now we're going to introduce not side effects, which is stuff that happens visually. We're going to revisit that blue circle called answer, or the blue oval called answer, that represented last week what we called a return value. And this is what many functions will actually do for us. They're not just going to display something presumptuously on the screen

or play a sound or a video or something like that. They're going to hand you back virtually a value-- text or integers or sounds or images that you can then do with what you see fit. So the paradigm we'll now have is much like in Scratch. If the input is what's your name and the function is ask, and you get back a return value of answer, we want to actually do this now in C. So side by side, what code like this in Scratch is going to look like today onward is this. Instead of using the Ask block, you literally use CS50's function called get_string. It takes input. So we put the parentheses on the left and the right to conjure the idea of this white oval. Inside of that string, you can put a prompt, so to speak, like, what do you want the human to be asked, in this case. And I'm missing something still. Per the placeholders here, what's missing? So quotation marks, so literally quotation marks on the left and the right.

And I'm going to be a little anal here. I'm going to put a space at the end. Because I don't want to-- I could, but I don't want the cursor to go to the next line. Hence, no backslash n. If I want the cursor just to sit there kind of blinking, waiting for the user after the question mark, I'm just going to put a space. So it will stay there for me. But this is just an aesthetic detail using the same idea as before. So that is the analog of this block. But how do I get access to the so-called return value? MIT just plopped it on the screen for us automatically. In C, we have to write a little more code to get access to that return value. And the way we do this is on the left hand side of this line of code, we come up with a name for the return value. You can call it anything you want. But answer is a nice equivalent to what MIT did. You could more generically call it x or y or z.

But that's not really useful. And so computer scientists, unlike mathematicians, will tend to use variables that are a little more verbose, like the word "answer." But in C, it's, again, a little lower level. You have to tell the computer what type of variable this is going to be. So I'm kind of conflating "variable" and "return value," but they're being used in an intertwined way. The get_string function, just like the ask block, returns a value. If you want to do something with it, you need to put it in something called a variable, which is denoted in text here. But again, per last week, the computer doesn't know if it's looking at numbers or characters or images or sounds. You have to tell it, as the programmer, that the zeros and ones that are somehow involved here underneath the computer's hood are, in fact, to be treated as text, a.k.a. string. Now, there's one stupid subtlety still missing from this line of code.

Does anyone know, especially if you've programmed-- OK, all of you have program before. Yes? AUDIENCE: Semicolon. DAVID J. MALAN: Semicolon. So one of the headaches of C and a lot of languages is you actually have to finish your thought explicitly so the computer knows that that line of code is done. And it's not a period, like in English. It's, in fact, a semicolon. Now, you don't use these everywhere. We'll see where you use them. But that, too, is a very common mistake, to overlook something simple. But again, in the coming weeks, even though this might look very cryptic, with muscle memory and practice, you'll start to see these things instantly, even if, for a few days, you sort of bang your head against the screen, so to speak, not seeing what the TFs and I much more readily see. So let's go ahead and do this. Let me go back over to VS Code here. Let me zoom in just a little bit.

And let me go ahead and do this. I'm going to get rid of my single use of printf. And I'm going to say the exact same thing-- string answer equals get string, quote, unquote, "What's your name?" question mark, space, closed quote, semicolon. And now I want to print out that answer. Well, let me do this incorrectly, deliberately, for the moment. Let me just say printf, quote, unquote, "hello, answer," if I want to plug in "answer" and I want to add a new line at the end, semicolon.

So let me try this. But there's multiple mistakes now in my code. Let's trip over them deliberately. Let me go down to my terminal window by clicking at the bottom of the screen. Let me run "make hello" again. Enter. And, oh, my god, there's even more errors now than there were before, but not a problem. Let me click on this little triangle here, which is just going to zoom in on the terminal window. So it takes up my full screen. And just generally, all you have to do is find a few keywords visually that give you a clue as to what's going on. Or, as before, you can always ask the CS50 Duck. So here's the command I ran, "make hello." Somehow that induced all of these errors. Always read them top to bottom, not bottom up. So from top to bottom, there's a problem on line 5, character 5-- use of undeclared identifier string. Did I mean standard in? No, no, no, I didn't there.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent