CS50x 2024 - Lecture 1 - C
Key Takeaways
Introduces C programming language using Visual Studio Code and CS50 Library
Full Transcript
[Music] [Music] [Music] all right so this is cs50 and this is week one zero index so to speak and it's not every day that you can say that you've learned a new language but today is that day today we explore a more traditional an older language called see and rest assured that even if what you're about to see no pun intended looks very cryptic very unusual particular if you're among those less comfortable cling to the ideas from last week week zero where in we talked about some of those fundamentals of functions and loops and conditionals all of which are coming back today indeed whereas last week and with problem set zero we focused on learning how to program with scratch which again you might have uh played with uh as a younger student uh days back um today we focus on C instead but along the way we're going to focus as always frankly on learning how to solve problems but among the goals for today and really on an entire class like this is just to give you week after week all the more tools for your toolkit so to speak via which to do exactly that so for instance today we'll learn how to solve problems all the more so with functions as per last week we'll do the same with variables we'll do the same with conditionals with loops and with more but we'll also learn at the end of today's class really how not to solve problems it turns out as powerful as Macs PCS cell phones are nowadays there's actually certain things that they can't do very well and they information they can't represent very well and that actually leads to a lot of real real world problems both past and surely future so more on what we're not going to be able to do uh with programming before long but beyond that let's come back to this picture here so this was the very first program that I wrote that you wrote presumably in some form and all it does is say hello world but as promised today this puzzle piece or these puzzle pieces together are going to very quickly start to look more like this and I've deliberately colorcoded in a way so that the text on the screen now kind of resembles the puzzle piece so if I go back notice that we had this when green flag clicked puzzle piece mostly in yellow with the green flag that sort of kicks off the whole process once you actually click the button at top right of scratch's user interface and then there's the purple block which actually is the verb the action the function that does something so if I bring this back over to what we're about to see today there's going to be some boiler plate so to speak some orange text here on the screen that for now you just kind of type and take for granted like you need to write your code like that but more interesting is going to be the purple and we're going to see today that the function previously called say in scratch is now called print F in this language called C but in white here you'll see similar text to our white oval last week whereby that's where user input like your input as the programmer can actually go so there's a lot of distraction and honestly it's these kinds of things that tend to distract and get frustrating early on when learning to code for the first time but the ideas most importantly are going to be the same so how are we going to go about using this well it turns out like last week you're going to start writing something called source code so code as we know it quote quote is more technically called source code that's what you and I as humans actually write and indeed it might look a little something like we just saw but unfortunately computers only speak this binary zeros and ones more properly known as machine code in other words those same patterns of zeros and ones last week uh someone guessed print out hello world on the screen because some one of those patterns is an H another pattern is an e an L an l and an O and so forth and then other patterns of those zeros and ones are commands or instructions to the computer that literally say show h l comma World on the screen but machine code would not be nearly as much fun to write uh if it were indeed in zeros and ones entirely for us ideally you and I are going to write source code which conceptually is sort of up here high level but we're going to need a program to convert it to the lower level machine code so that we don't spend our lives actually having to read and write zeros and ones which back in the day kind of in yesterday year you kind of sort of did with things called Punch Cards and holes on physical sheets of paper we're beyond that because after years and years of innovation folks have given us higher level languages instead so here's what we're going to need to do today if at the end of the day you and I are writing source code but we want machine code AS output we need something in the middle that's going to convert that source code to machine code you and I are not going to have to learn or talk about really anymore zeros and ones and the type of program we're going to start using today and introduce you to is called a compil so a compiler is a program that translates one language to another and it can be any two languages but today and often we'll talk about it in the context of source code to machine code so this is Apple or Google or Microsoft or folks from other uh companies or even volunteers who have written software that do this conversion you and I are essentially going to download a free compiler and use it to actually get our computer to understand the source code that you and I write in these higher level languages so where are we going to do that that well we could actually give you instructions and you could download the appropriate free open-source software onto your own Mac or PC the reality is that creates so many technical support headaches because we all have slightly different computers we all have slightly different versions of Windows or Mac OS or Linux or other operating systems and that too tends to be a distraction at the beginning of any course like this or learning programming so we're going to use the cloud instead we're going to use a URL of the form https cs50. deev and what this will do for you is put inside of your browser window absolutely everything you need for the course but it's going to use software software called Visual Studio code otherwise known as vs code that's actually free itself it's very popular in industry it's what real programmers use every day but it's a cloud-based version thereof and so everything will just work for you out of the box but toward the end of cs50 the goal is going to be to get you off of cs50's infrastructure to get you to download this free uh freely available software onto your own Mac or PC if you so choose so that those training wheels so to speak can come off and then even if you never take another class again you don't need any classes infrastructure moving forward you'll have everything you want and need on your own Mac or PC but for now it'll save us a bit of time so in just a bit I'm going to go to that URL myself on my computer and I and you will see an user interface that looks a little something like this the colors might be different based on your settings fonts might be different and so forth but in general it consists of a few different regions so over here at the top is where we we are going to start writing code today so it's a tabbed interface like any number of programs nowadays and this is that same C code we saw a moment ago so this is where in a moment I'm going to start to type it over here at the bottom is what we're going to call a terminal window or a console and the terminal window is where we're going to type commands for compiling our code for running our code and we'll see today a contrast between a graphical user interface or guy which has menus and icons and things you click and are very familiar with vers is a command line interface or CLI and so we're using both of these together and command line interface just means down here you only use your keyboard you can click click click if you want with your mouse it's not going to generally do much because a command line interface takes commands at the keyboard so in a weird sense it's going to feel like taking a step backwards from the Macs the PCS the iPhones and Android phones we all have which are very graphical but it turns out once you become a computer person or a programmer you can be a lot more productive a lot more efficient I dare say by learning to harness a command line interface and using both types of interfaces for what each is good at so more on that in just a bit over here at left you're going to see soon a folder interface like Mac OS or Windows where any of the files or folders we create in cs50 are going to end up as well so it gives you sort of The Best of Both Worlds you can point and click on the left or you can type commands at the bottom as we'll soon see and then along here is the so-called activity bar where there's just VSS code specific features but also cs50 specific features and if you're in your own version of cs50. you click through in the dot dot dot menu or zoom out so you can see everything you'll see cs50's own rubber duck virtually speaking that will be there throughout the course to answer any and all of your questions as well so more on that soon too so here's the code that I propos that we write first just like we wrote our very first scratch program to say hello world so let's go ahead and do exactly this I'm going to switch over to this screen here where I've already logged into cs50. deev on my computer and just to keep the focus on the code I've hidden the activity bar I've hidden the file explorer so to speak so you're seeing here the area where all of my tabs are about to go and the terminal window where all of my commands are going to go but I've just simplified the UI to keep our focus on the interesting parts for now so how do I go about actually uh writing and compiling and running some code well the teaser is going to be these three steps one of these is a command called apply code and code is just going to let me to open or create a new file like a file called hello.c make is going to be for now my compiler that allows me to make the program that is convert source code into machine code so from C to zeros and ones and then weirdly but we'll soon see why do /hello is going to be the command to run my actual code so the textual equivalent of like double clicking on a Mac or a PC icon or tapping an icon on your phone so that's it these three commands are going to allow me to write to compile and to run code ultimately so let's go ahead and do that I'm back in my vs code interface I'm going to go ahead and run code uh hello.c and notice a couple of details here so one there's this weird dollar sign which has nothing to do with currency but it's just a common convention in the programming world to represent your prompt so if a TF if I ever say go to your prompt we really mean go to your terminal window go to the dollar sign and the dollar sign is where you type the command sometimes it's a different symbol but a dollar sign is conventional now that I've typed code space hello.c I'm going to go ahead and hit enter and maybe not surprisingly this gives me a brand new tab a new file if you will called hello.c and just like Word documents have their own file extension like Doc docx and Excel files have xlsx and PDFs have PDF and gifs have dogf and so forth so do c files have a file extension by convention that is C now a couple of minor points notice that by convention I'm almost always going to name my files in lowercase by convention I'm never going to use spaces in my file names and my file extension two is going to be lowercase long story short accidentally hitting the space bar or using file names with spaces just tends to make life harder when you're in a command line environment so just beware silly stupid things like that so all lowercase no spaces for now so my cursor is literally blinking because the program wants me to write some code I'm going to do this for memory it'll take you presumably some time to acquire the same instincts but I'm going to go ahead and type this first line here pronounced include standard io. more on that soon in main void with some parentheses thrown in notice what's about to happen here is a little interesting in the code I want to type I want what we'll call Curly braces the sort of squiggles that you don't use often in English at least but are there on your keyboard somewhere but notice what VSS code does and a lot of programming environments is it finishes part of my thought so I'm only going to type a left curly brace but notice I actually get two of them and if I hit enter notice that not only does it scooch one down a bit it also indents my cursor because just like with pseudo code last week whenever you're doing something logically that should only happen if the thing above it happens similarly is indentation going to be a thing when we actually write code so vs code and programs like it just try to save us keystrokes so I don't have to waste time like hitting the space bar or hitting tab or sort of wasting my human time like that all right so with that said I'm going to go ahead and type the last of these lines print F where the f is going to mean formatted and then a parenthesis and notice it gave me two it gave me the second one for free sometimes it will get confused and you can certainly override this delete it and start over and now unlike scratch in C it turns out I'm going to need to use double quotes anytime I'm using an English word or phrase or any human language for that matter hello comma world and then at the very end of my line much like English uses periods I'm going to use a semicolon in C so that's a lot of talking but it's not much coding it's technically six lines of code but honestly the only interesting one intellectually as we'll soon see is really line five like that is the equivalent of that say block now here's where I'll cross my fingers hoping that I didn't make any typographical errors it's going to automatically save for me and I'm going to go back to my terminal window where now I'm going to do that second command make space hello common mistake you do not say make hello. C CU you already made that file you say make hello which is the name of the program that in this case I do want to create and make a smart it's going to look in my folder and if it sees a file called hello.c it's going to convert that source code to machine code and save the results in a simpler shorter named file just called hello like an icon on your desktop now hopefully nothing will happen and that is a good thing quite paradoxically if you do anything wrong when programming odds are you're going to see one or many more lines of error sort of yelling at you that you made a mistake seeing nothing happen is actually a good sign so the last command to run my code recall our three steps here we co we're in code to create the file make to compile the file from source code to machine code so lastly is/ hello so this now is the equivalent of my like double clicking on a Mac or PC or single tapping on a phone enter ah so close all right it's pretty good I got the h e l l o comma space world but there's something a little stupid about my output what might rub some of you aesthetically the wrong way yeah the dollar yeah so the dollar sign looks like I was like Hello World dollar sign in my output but no that's just kind of a a remnant of my prompt starting with a dollar sign and this is a little nitpicky but this just doesn't feel right doesn't look right it's not quite correct so how can I go about fixing this well here's where at least initially it's going to take some introduction to like just new syntax and see to fix this like the simplest Instinct might be to do this well let me just hit enter like that but this should soon if not already rub you the wrong way because in general we're going to see that programming in c and in Python and other languages tends to be line based like you should really start and finish your thought on one line so if you're in the habit of hitting enter like this and sort of finishing your thought on the next line generally programming languages don't like that so this is in fact not going to do what we expect and just to show you as much I'm going to do this let me go back to my terminal window here I'm going to rerun make hello after making that change enter and there we have it like the first of our erroneous outputs and it's yelling at me it's missing a terminating character and there's some red in here some green drawing my attention to it sometimes these error messages will be straightforward sometimes you're going to like rack your brain a bit to figure them out but for now I've kind of spoiled that obviously enter is not the right solution so let me clear my terminal window just to hide that error let me delete this and let me propose now that I add this incantation here so back slash in it turns out is going to be the sort of magical way of ensuring that you actually get a new line at the end of your output so let me go ahead now and rerun make hello because I've changed my code I need to now reconvert recompile the source code to new machine code /hello and now there is the canonic hello world program that I hop to write in the first place so for now don't worry about the include don't worry about the standard iio don't worry about int or main or void or the curly braces Focus primarily on line five here and over the course of today and next week we'll start to tease apart the other characters that for now you should take at face value questions though on any of the steps we've just done [Music] yeah sure why is the back slash in in uh inside of the the quotation marks if you will so sort of answer is like that's just the the where it needs to be because inside of the quotes is the input that you want print F to Output to the screen so if you want print F this function to Output a new line it must be included in the quoted uh text that you give it exactly back sln is a special pattern that print F no means okay I should move the cursor to the next line good question other questions on any of these steps yeah a good question so what if you actually want to print back sln things get a little tricky there let me go ahead and propose that we do this so it turns out and this is often the case in programming when you want a literal character to appear you actually put another backslash in front of it but this is not going to be something we do often but there is in fact a solution to that but let me propose that beond on that now we sort of compare it against what we've actually done so here is the first scratch program we wrote with the green flag there here recall is the mental model that I proposed we have for almost everything we do whereby functions are just an implementation say in code of algorithms step-by-step instructions for solving problems the inputs to functions recall from last week are called arguments or in some context parameters and sometimes functions can have side effects like last time with scratch there was the speech bubble that magically appeared next to the cat's mouth is a sort of side effect of using the say block so just like this then we had the white oval as input the say block was the function last week and then we had this here side effect well what how do we compare these things left to right well here's the say block at left let's compare now to the C code at right notice a couple of things to sort of adapt from scratch to C print is almost the name of the function it is technically print f for reasons we'll eventually see notice the parentheses in C are kind of evocative of the oval in scratch and that's probably why MIT chose an oval because a lot of languages use parentheses in this way you still write hello world just as we did last week in scratch but per our demo thus far you do need the double quotes and double quotes not single quotes double quotes on the left and right and in order to get that new line you need the backslash end and one more thing is missing yeah the semicolon to finish your thought so all of these sort of stupid things now that honestly you will forget initially if you've never programmed before but you'll soon within days within weeks develop the muscle memory where all of that stuff just jumps off jumps off the page right at you all right so these escapes uh this backs slash in is generally known just so you know as an escape sequence and so backs slash in allows us to specify a character that might otherwise be hard to type but let's tease apart some of the other things at top that function already so include standard i.h it turns out that in C A lot of the functionality that comes with the language is tucked away in separate files so if you want to use certain functions you have to tell the compiler hey I want to do some standard input and output like I want to print some things on the screen and that's because for now you can think of printf as living in this file standard i.h that's a bit of a white lie for now but in standard i.h is essentially a declaration for printf that will teach the compiler how to print things to the screen so hash include here simply tells the compiler before it does anything else essentially go ahead and find on the local hard drive a file called standard i.h and kind of copy paste it there so I know now about print F so this thing thish file is what we'll technically call a header file and if you've ever heard this word especially if you have programmed before it represents essentially what we'll start calling a library so a library in the world of programming is just code that someone else wrote that you can use it's usually free and open source which means you can literally see the code that someone else wrote or sometimes you pay for it sometimes it's closed source which maybe Microsoft wrote it they won't show you the code but they will let you use the zeros and ones so libraries are super useful because honestly you know even I don't really know how print F works I've taken for granted for 25 years that if I use print F stuff prints on the screen but someone smarter than me had to actually write the code in C that figures out how to get the H the E the l l o and so forth onto the Mac screen the PC screen the phone screen or somewhere else so libraries allow us to sort of stand on each other's shoulders and so that someone else can do the hard work and we can now solve problems that are more interesting to us not the basic commodity stuff that everyone might want in their code so again library is code that someone else wrote a header file in C is just a file ending inh that gives you access to the same and so for instance if you want to learn more about these there are what are are called in the world of programming manual pages and these are uh uh textual files like um documentation of sorts via which you can just learn how a function works or and how you can use its inputs or arguments the reality is they're written for folks who aren't in cs50 they're written for folks who aren't just learning how to program they're written for and by folks who have been programming for years and so frankly they're a little hard to understand and so cs50 has its own version thereof at this URL manual. cs50. where you'll see not only the official documentation for C the language but also staff written simplifications in Lay persons terms what all of the various popular functions are what their inputs and what their outputs are so for instance under uh standard i.h you can actually go to that website you can go to a URL like this where standard i.h is in there and you can actually see the documentation there so let me go ahead and do this I'm going to go ahead in my browser here I'm going to go to to uh manual. cs50. and let me go ahead here and select those functions that are frequently used in cs50 and under standard i.h you'll see a bunch of functions only one of which we've even discussed called printf I'm going to click on printf there and you'll see an interface that at first glance might be a little overwhelming but it's going to start to look more and more familiar so first of all you'll see that if you want to use print def under synopsis you need to include this header file like you literally copy and paste that line into your own codee you'll also see this which for now is a bit uh Arcane but this is kind of a hint as to what the function is going to look like but more on that soon but more importantly you can read a description about it and because these descriptions when you're in less comfortable mode are written by me in the coures teaching fellows teaching assistants and course assistants they'll you'll find them to be much more in Lay persons terms and so long story short rely on this site once you want to learn how to use some function and also what other functions exist in fact if I go back back to the main page here you'll see that there all of these functions like are frequently used in cs50 and there's hundreds more that come with C but learning a programming language is not about learning all of those but rather just getting a sense of where you find answers to questions when you do want to try something new but what is important to know for cs50 today is that we have our own header file called cs50.h which has functions that we have written just to make life easier in the first few weeks of the class these are training wheels that will'll eventually take off but it turns out in C especially if you've programmed before it's actually really hard and annoying just to get input from users to get them to type a a word or a number or something else like C does not make this easy in part because it's one of the earliest languages that wasn't zeros and ones so you have to do a lot of the heavy lifting yourself but we'll put on these training wheels today and for a few weeks so that we can focus really on the intellectually interesting uh ideas of c and programming without getting bogged down in certain weeds that we will come back to before long so for instance cs50's own documentation is there at that URL but within the library are these functions a function called get string to get a string of text string is a synonym for just text in a programming language so get string will prompt the human for a string of text get int is shorthand for get integer if you want to get a number from the user uh get float is a little more Arcane get a floating Point number like a real number with a decimal point in it and dot dot dot there are others as well so this is to say within cs50 we've got some userfriendly functions via which we can actually get some input and let's go ahead and use one of these for instance get string because recall that last week our second program in scratch was this one here where we didn't just say hello world we said hello David or hello Carter hello ulia whoever it was typing their name in but to do that we needed this ask block int scratch and then we use the say block and then we use the join block to kind of make all of this work so let's translate this program now into C because it's a little more interesting and representative of the kind of code we'll start to write but we need a slightly different mental model still have a function here which is the implementation in code of an algorithm we still have some inputs called arguments but previously I said that the say block and in turn printf have side effects which is just something visually typically that happens on the screen other functions actually have what we called last week return values and this is kind of analogous to a function maybe uh doing something for you writing down the answer on a slip of paper and then handing you the programmer the slip of paper to do whatever you want with it without just broadcasting it to the world with like a speech bubble on the screen so a return value is Germain for a program like this because recall when we used the ask block and I typed in my name where did my name end up initially it didn't go on the screen yet where did it end up in an answer puzzle piece and that special o um oval puzzle piece I claimed at the time represents a return value so the sort of metaphorical piece of paper that the answer is written down on so that I can then use it later so that's what we want to get to now and see a return value that I can then do anything I want whether it's print it to the screen change it in some way save it in a database or anything else so here for instance is what we did witht scratch the input to the say block or the ask block was what's your name quote unquote the function of course is the ask function and the return value was answer if we now consider how we might translate this to c it's going to look a little weird at first but it's going to follow a pattern today next week the week after anytime we do code like this so get string I claim is going to be the most analogous function in C to the ask block and to be clear this is a cs50 specific thing training wheels of source but we'll show you in a few weeks what this function is doing and how you cannot use it moving forward once you're comfortable with the language itself notice I've put parentheses left and right as sort of a placeholder for user input and that user input is going to be what's your name but I can't just put what's your name in parentheses what do I minimally need to add in there too yeah so the double quotes left and right so let me go ahead and add those in uh I left a space here not for a new line I could move the cursor to the next line but I minimally at least want to move the cursor at least one space over just so it looks pretty so that when I'm prompted for my name there's a space between the question and my answer but it could also be back sln that's just an aesthetic choice on my part but what do I do with the answer that comes back from get string this is where the text is going to look different today in C you start to use an equal sign from left to right respectively and on the left you put the name of the variable in which you want to store that return value so a return value is kind of a conceptual thing you can do with it what you want and if I want to store it longer term in a variable like X or Y or Z in math class I can just give it a name here x or y or Z or more more reasonably answer or any other English word no spaces generally lowercase same same heris as before but this means now ask the user what's their name whatever they type in go ahead and store it from right to left in this variable called answer but C's not done with us yet if you've learned python or certain other languages you'd kind of be done writing code at this point in C though you additionally have to tell the compiler what type of variable you want to use so if it's a string of text you say string if it's an integer a number you say int as we might have seen before so it's a little more pedantic it's more annoying frankly the more onus on you and me the programmers but this just helps the compiler know how to store it in the computer's memory and I'm so close to being done with this line of code but what's missing so semicolon and mark my words if you've never programmed before sometime this week this semester you will forget a semicolon you will like raise your hand you'll get frustrated because you can't understand why your code's not working you will run into stupid issues like that but do take Faith it they are stupid issues it doesn't mean it's not clicking for you or you're not a programmer it just takes time to see these things if it's a new language to you so there now is my semicolon all right let's go ahead then and do something with that return value using the second of the big puzzle pieces in scratch so when I wanted to say hello comma David or whatever the human's name is I kind of stacked my puzzle pieces like this this is actually similar to Python and maybe some other languages some of you have learned but C is a little bit different and the closest analog to this scratch solution is going to look like this I still use print F because print f is the equivalent of say inside of my parentheses I'm going to go ahead and say weirdly hello comma percent s so there's no real analog and see of join instead there's a way to specially format text using printf hence the F in print F and what you do in print f is you type whatever English word or human words that you want you then use percent S as a placeholder if you want a string of text to be added to your own text you literally write percent s and let me anticipate a question from the crowd how do you print out percent s there's a solution to that too if you literally ever want to print out percent s but it's Del deliberately a weird choice of characters that so that the probability that we ever need to type this ourselves is just low that no one really worries too much about it all right but that's not quite enough in addition to saying hello comma space placeholder percent s and just for vocabulary sake that's a format code again format being the F in print F I still need my double quotes around the whole whole thing this case to match my previous program I am going to go ahead and add the back sln to move the cursor to the next line and now I've left a crazy amount of room here but that's deliberate does anyone have an instinct for what I'm probably going to want to add after the quotes but still inside of the parentheses so answer itself I need to somehow tell print f with a second input otherwise known as an argument what I want to substitute for that percent s and so I put a comma and then the name of the variable that I want printf to figure out how to plug in here so honestly it's a little Annoying and this is kind of a dated approach like newer more modern languages like we'll see later in the course Python and JavaScript actually have much more userfriendly ways of doing it but once you wrap your mind around the heuristics the rules here it's just formatting a string by plugging in whatever you want into this format string so to speak and the again the comma here is important this signifies that it takes one input at left and a second input at right but notice this comma there's technically two commas but I'm not claiming that this function takes three inputs why this this comma I'm pointing out doesn't mean the same it's because that comma is part of the quotation marks and it's then part of like the string exactly this comma that I'm pointing to is part of the quotation marks and therefore part of my string of English text so this is just English grammar this is sort of C syntax and again these are the sort of annoying little details that we're using different the same symbol for different things but context matters so just stare at your code look carefully left to write and generally the answer will pop out nope pun intended okay questions now on this syntax before we actually write it and run it yeah back after answer why is the back slash n not after the answer so the way functions work including printf is that you pass to them one argument inside of the parentheses es and then if you have a second argument you put it after this comma here but the way print F works is that its first argument is always a string that you want to be formatted for you so anything you want printed on the screen has to go in those quotes and you can perhaps extrapolate from this if I actually wanted to say multiple things in this sentence so hello maybe first name last name I could actually do hello comma percent s space percent s if I had two variables one called first name one called last name but then I would need another comma for a third input to the function and so it's very general purpose in that sense questions yeah okay so can you abstract away the the the the format string itself hello comma answer short answer yes but not nearly as easily and see as you can in other languages so that's why we're keeping it simple for now but you're going to love something like python or JavaScript where a lot of this complexity goes away but you'll see also in Python and JavaScript and other languages they still in uh are inspired by syntax like this so just understanding it now will be useful for multiple languages down the line all right so let's actually do something with this code rather than just talk about what it might be doing for us let me go over to for instance VSS code again and I'm going to go ahead now and remove this middle line of printf I'm still in my same file called hello. C I'm going to clear my terminal window just to eliminate distraction and to do that I can literally type clear but this is just for aesthetic sake that's not functionally that useful or you can hit contrl L to achieve the same on your keyboard but I'm going to go back to line five here where I previously just said hello comma world and I'm going to do this instead I'm going to De I'm going to give myself a variable called string uh sorry I'm going to give myself a variable called answer the type of which is string I'm going to set it equal to whatever the return value is of get string asking an English question what's your name question mark with just a single space just to move the cursor over followed by a semicolon then I'm going to go ahead and say print F quote unquote uh hello comma placeholder back sln close quote comma and then what goes here again this is where answer goes and then I just need to semicolon on the right of that but I think now that I'm done but let me point out a couple of details this got very colorful very pretty quickly and it's not like the black and white code I had on the screen a moment ago this is because what programs like vs code do for us is it uh pretty prints or rather it um syntax highlights our code for us so syntax highlighting means just add some colors to the code so that different ideas pop out so you'll notice for instance that printf here get string here are in purple because they represent functions just like the say block um here what's your name quote unquote in vs code is a light blue instead of white but it's still going to be consistent if I use strings of text elsewhere as well so I didn't type anything special this isn't like Microsoft Word or Google Docs where I'm highlighting and changing colors of things this is all happening automatically but it's just Unicode text it's just being interpreted automatically and having these colors applied so that things pop out more usefully visually now I've unfortunately made a mistake but I'm going to deliberately induce this one cuz you to will probably make this mistake I'm going to go ahead and run make hello again because I've changed my code so I have to regenerate the machine code from the new source code but unfortunately when I hit enter now my God that my the errors don't even fit on the screen so let me make this bigger I'm going to click the little carrot symbol here just to make my terminal bigger for just a moment and you'll see that there's like more lines of Errors than there are of code that I actually wrote often which is written pretty arcely again for programmers who've been writing code for 10 20 years but there are some details that pop out so notice the problem is definitely with hello. C so great it is my fault this syntax here means that line five is the problem and this next five means character five so you can literally like triangulate your bug your mistake by going to line five and then over five and it's somewhere in that area specifically the area is use of Undeclared identifier string did you mean standard in I I don't think I did like I do want string and then there's some other complexity here but what's important here is not the specifics of this error but really the implication that it doesn't recognize the word string or get string now why might this be [Music] yeah exactly because we are using get string which I claimed as a cs50 thing that we'll use for a few weeks C does not know about it out of the box so to speak I have to teach the compiler that get string exists just like I taught the compiler that print F exists by including the appropriate header file and in this case quite simply it's called include cs50.h that now teaches the compiler oh someone else wrote this function already get string and with it this type of variable called string so now if I go back to my terminal window and rerun the exact same command make Hello Maybe crossing my fingers now nothing in fact goes wrong because the compiler's been brought up to speed with all of the functionality it needs and now if I do/ hello and there it is what's my name and notice the cursor's one space over just cuz I thought that'd looked prettier than having the cursor right next to the question mark DVID as my input and enter and hello comma David all right questions on any of this code thus far questions any of the code no all right so let's introduce some other functionality into the mix it turns out that there are other types of data other types of variables in the world not just strings but indeed per before we have things called integers int for short floating Point values float for short and a few others as well so rather than only focus on string let's get a little more interesting with numbers here and see what we can do with something like integers again int for short by taking a look at not get string as before but now how about get int and for this I'm going to give us a few other tools in our toolkit those format codes to which I alluded earlier like percent s fortunately are pretty straightforward and here is a list of most of the popular format codes that you might ever care about with printf in particular we saw percent s for string and you can perhaps guess which one we're going to use for integers yeah so percent I is what we're going to use for integers and this is the kind of thing that you can consult in the manual pages or a slide like this there's only a few of them that you might frequently use but let's go ahead and use integers in a more interesting context not just using functions but let's revisit this idea of conditionals and conditionals in scratch were like these proverbial Forks in the road like do you want to do this thing or this thing or this other thing it's a way of making decisions in a program which is going to be super useful and pretty much omnipresent in any problems that we try to solve so let me give you a few more building blocks in C by doing the side by-side comparison again so here in scratch is how we might say if two variables X and Y are one is less than the other then go ahead and say quote unquote X is less than y so kind of a stupid program but just to show you the basic Syntax for Scratch this is how you would ask the question If X is less than y then say this so say is the function if is the conditional and the green thing here we called what what do we call it yeah a Boolean or a Boolean expression which is just a fancy way of saying a question whose answer is true or false yes or no one or zero however you want to think about it in C the code's going to look like this so it'll take a little bit of habit a little bit of muscle memory to develop but you're going to say if then in parentheses you're going to say x less than y assuming X and Y are variables you're then going to use these curly braces and then if you want to say quote unquote X is less than y in C what function should we use here presumably so print F so print F quote unquote X is less than y so it's a bit of a mouthful but again notice the pattern name of the function is print F in the parentheses left and right is the argument to print F which is quote unquote X is less than y and again just for Aesthetics to move the cursor to the next line which you don't have to worry about in scratch because everything's in speech bubbles we're adding a back slash n as well so notice that these curly braces as they're called much like the orange puzzle piece here are kind of like hugging the code like this and I'll note that technically speaking in C if you only have one line of code inside of your conditional you can actually omit the curly braces all together and the code will still work if you have one single line of code why just saves people some keystrokes if you have two lines three lines or more in there you need the curly braces but I'll always draw it with the curly braces in class so it resembles scratch as closely as possible as an aside to some of you who have programmed before you might be cringing now CU like you really like your curly brace to be over here instead of here like that to is a stylistic choice and we'll talk too about this in the class aesthetically stylist basally there's certain decisions we can make but generally in a class in a company you as an student or an employee would simply standardize on uh one set of rules so to speak so we'll use these rules for formatting our code in class consistently all right any questions on this snippet of C code all right a couple of others then so here is how in scratch we might have a two-way fork in the road if x is less than y say x is less than y else say X is not less than y in C it's going to look pretty much the same but notice I'm adding an Els keyword here with another set of curly braces I'm going to have a couple of more printfs but in see even though it's clearly keyboard based it's just text no more puzzle pieces it's kind of the same shape so to speak and it's definitely the same idea so it's following a pattern what about a three-way fork in the road if x is less than y then say x is less than y else if x is greater than y say x is greater than y else if uh X equals y then say x is equal to Y well you can probably see where this is going on the right hand side it looks almost the same in fact if I add in the printfs it's really almost the same at least logically but there is one at least one curiosity seemingly a typo but it's not this time yeah yeah the double equal signs does not match scratch but it's not in fact a bug or mistake in C anyone have an intuition for why I did use two equal signs instead of one here yeah misten for exact well otherwise it would be staken mistaken for a variable specifically assignment of a variable so recall that in previous code when we used the get string function we used an equal sign to assign from right to left the value of a variable and that's a reasonable decision equal kind of means that the two should ultimately be equal even though you think about it from going right to left unfortunately the authors of C kind of Paton themselves into a corner and presumably decades ago when they realized oh shoot we've already used a single equal sign how do we represent equality of two values the answer they came up with was all right we'll just use two instead and thus was born this decision is it the best one who knows uh crazy enough in other languages like JavaScript uh you have not just one but two but also three equal signs in a row to solve yet another problem so reasonable people will agree as to how good or bad these decisions are but in C this is what you must do but there's an bad design decision here too it's still correct the code left and right but I bet I could critique the quality of the design of both the scratch code and the C code for reasons [Music] what okay no really good intuition do we have to ask this third question else if x equals y so short answer no logically right just based on arithmetic either X is less than y or X is greater than y or what's the only other possible answer they must be equal logically so technically you're just kind of wasting the computer's Time by asking this question because it already knows at that point the answer and you're wasting your time as the programmer bothering to type out more code or more puzzle pieces than you need because logically one stems from the other so I can tighten this up get rid of the else if just use an else and I can do the same thing over here and C thereby avoiding the double equal sign altogether but not because it's wrong but because you're wasting time because now you're potentially asking only two questions two Boolean Expressions instead of 50% more by asking a total of three questions at most other questions then on this kind of code logically or otherwise no all right so if we have these puzzle pieces so to speak at our disposal how can we go about actually using these well suppose that we actually want to do something with values let's introduce variables in see as well we saw an example using a string a moment ago but what about with something like integers well you might not have used this in scratch but here's the orange puzzle piece in scratch via which you can create a variable called counter to count things and you can set it equal to some value like zero now you can perhaps guess where we're going with this if I want in C a variable called counter and I want to set it equal to zero I use a single equal sign CU logically you read it from right to left or technically it's executed from right to left but that's not enough in see what's missing from the screen I need a what so we need a data type and if it's going to be an integer indeed I'm going to use int and now the other mistake I keep making is so a semicolon at the end of the line so it's a little more verbose than some languages but if you read it left to right this is how you tell C to give you a variable called counter of type int and initialize it to a value
Original Description
***
This is CS50, Harvard University's introduction to the intellectual enterprises of computer science and the art of programming.
***
TABLE OF CONTENTS
00:00:00 - Introduction
00:01:01 - Machine Code
00:05:58 - Visual Studio Code for CS50
00:09:14 - Hello, World
00:18:40 - From Scratch to C
00:20:29 - CS50 Library
00:31:14 - Format Codes
00:35:43 - Hello, World
00:36:11 - Hello, You
00:40:22 - Types
00:41:23 - Conditionals
00:47:58 - Variables
00:50:50 - compare.c
01:01:19 - agree.c
01:09:38 - Loops
01:15:40 - meow.c
01:24:48 - Functions
01:33:32 - calculator.c
01:36:06 - Scope
01:41:45 - Function Composition
01:44:14 - Linux
01:52:36 - Mario
02:08:32 - Integer Overflow
02:13:22 - Truncation
02:16:47 - Type Casting
02:18:07 - Floating-Point Imprecision
02:20:55 - Y2K
02:23:35 - Video Games
02:25:21 - Boeing
***
HOW TO SUBSCRIBE
http://www.youtube.com/subscription_center?add_user=cs50tv
HOW TO TAKE CS50
edX: https://cs50.edx.org/
Harvard Extension School: https://cs50.harvard.edu/extension
Harvard Summer School: https://cs50.harvard.edu/summer
OpenCourseWare: https://cs50.harvard.edu/x
HOW TO JOIN CS50 COMMUNITIES
Discord: https://discord.gg/cs50
Ed: https://cs50.harvard.edu/x/ed
Facebook Group: https://www.facebook.com/groups/cs50/
Faceboook Page: https://www.facebook.com/cs50/
GitHub: https://github.com/cs50
Gitter: https://gitter.im/cs50/x
Instagram: https://instagram.com/cs50
LinkedIn Group: https://www.linkedin.com/groups/7437240/
LinkedIn Page: https://www.linkedin.com/school/cs50/
Medium: https://cs50.medium.com/
Quora: https://www.quora.com/topic/CS50
Reddit: https://www.reddit.com/r/cs50/
Slack: https://cs50.edx.org/slack
Snapchat: https://www.snapchat.com/add/cs50
SoundCloud: https://soundcloud.com/cs50
Stack Exchange: https://cs50.stackexchange.com/
TikTok: https://www.tiktok.com/@cs50
Twitter: https://twitter.com/cs50
YouTube: http://www.youtube.com/cs50
HOW TO FOLLOW DAVID J. MALAN
Facebook: https://www.facebook.com/dmalan
GitHub: https://
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from CS50 · CS50 · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Hello, World: Hadi Partovi
CS50
Content Distribution and Archival in a Digital Age
CS50
CS50 2014 - Week 1
CS50
CS50 2014 - Week 3
CS50
CS50 2014 - Week 0, continued
CS50
CS50 2014 - Week 4
CS50
Week 3, continued
CS50
Quiz 0 Review
CS50
CS50 2014 - Week 3, continued
CS50
CS50 2014 - Week 7
CS50
CS50 2014 - Week 7, continued
CS50
Breaking Through The (Google) Glass Ceiling by Christopher Bartholomew
CS50
Introduction to Amazon Web Services by Leo Zhadanovsky
CS50
CS50 2014 - Week 9
CS50
How to Build Innovative Technologies by Abby Fichtner
CS50
Light Your World (with Hue Bulbs) by Dan Bradley
CS50
Building Dynamic Web Apps with Laravel by Eric Ouyang
CS50
CS50 2014 - CS50 Lecture by Steve Ballmer
CS50
CS50 2014 - Week 10
CS50
This is CS50 with Steve Ballmer?
CS50
Meteor: a better way to build apps by Roger Zurawicki
CS50
Data Analysis in R by Dustin Tran
CS50
Data Visualization and D3 by David Chouinard
CS50
CS50 2014 - Week 6
CS50
Build Tomorrow's Library by Jeffrey Licht
CS50
CS50 2014 - Week 9, continued
CS50
Essential Scale-Out Computing by James Cuff
CS50
iOS App Development with Swift by Dan Armendariz
CS50
Sam Clark Leads Yale Students on Tour to CS50 at Harvard
CS50
3D Modeling and Manufacture by Ansel Duff
CS50
CS50 2014 - Week 5, continued
CS50
hello, world
CS50
CS50 2014 - Deep Thoughts - Hash Table
CS50
CS50 2014 - Deep Thoughts - Binary Tree
CS50
CS50 2014 - Deep Thoughts - Scratch
CS50
CS50 2014 - Deep Thoughts - MySQL
CS50
LaunchCode Visits CS50
CS50
CS50 Live, Episode 100
CS50
CS50 Field Trip to Google
CS50
This is CS50 AP
CS50
Week 4: Monday - CS50 2011 - Harvard University
CS50
Week 2: Wednesday - CS50 2011 - Harvard University
CS50
Week 1: Wednesday - CS50 2011 - Harvard University
CS50
Week 11: Monday - CS50 2011 - Harvard University
CS50
Week 3: Wednesday - CS50 2011 - Harvard University
CS50
Week 12: Monday - CS50 2011 - Harvard University
CS50
Week 1: Friday - CS50 2011 - Harvard University
CS50
Week 3: Monday - CS50 2011 - Harvard University
CS50
Week 10: Wednesday - CS50 2011 - Harvard University
CS50
Week 2: Monday - CS50 2011 - Harvard University
CS50
Week 9: Monday - CS50 2011 - Harvard University
CS50
Week 7: Monday - CS50 2011 - Harvard University
CS50
Week 5: Monday - CS50 2011 - Harvard University
CS50
Week 5: Wednesday - CS50 2011 - Harvard University
CS50
Week 7: Wednesday - CS50 2011 - Harvard University
CS50
Week 8: Monday - CS50 2011 - Harvard University
CS50
Week 9: Wednesday - CS50 2011 - Harvard University
CS50
Week 8: Wednesday - CS50 2011 - Harvard University
CS50
Week 10: Monday - CS50 2011 - Harvard University
CS50
Week 2: Wednesday - CS50 2010 - Harvard University
CS50
Related Reads
📰
📰
📰
📰
How to audit a Lovable, Bolt or v0 app before launch: Audit Vibe Coding by Inithouse
Dev.to AI
Amid hardware legal battle, OpenAI releases a $230 keyboard for Codex
TechCrunch AI
7 advanced Claude Code tips from 17 months of intense use
Dev.to · YK
Three handoff boundaries around a coding-agent workflow
Dev.to · Nekoautomata Miki
Chapters (29)
Introduction
1:01
Machine Code
5:58
Visual Studio Code for CS50
9:14
Hello, World
18:40
From Scratch to C
20:29
CS50 Library
31:14
Format Codes
35:43
Hello, World
36:11
Hello, You
40:22
Types
41:23
Conditionals
47:58
Variables
50:50
compare.c
1:01:19
agree.c
1:09:38
Loops
1:15:40
meow.c
1:24:48
Functions
1:33:32
calculator.c
1:36:06
Scope
1:41:45
Function Composition
1:44:14
Linux
1:52:36
Mario
2:08:32
Integer Overflow
2:13:22
Truncation
2:16:47
Type Casting
2:18:07
Floating-Point Imprecision
2:20:55
Y2K
2:23:35
Video Games
2:25:21
Boeing
🎓
Tutor Explanation
DeepCamp AI