>> All right, welcome back.
This is CS50 and this is the end of week one.
We are so pleased that so many
of you have returned to us indeed.
There are a total of 646 of you who have returned
to us this year, roughly 246 of which are still sleeping
or at home it seems now.
But that's okay, everything will remain online.
The lectures go up quite quickly
and we will transcribe them into notes.
The transcripts thereof and yet other resource will be
on the course's website.
But a couple of mentions now because this is, of course,
the beginning of the semester
and you certainly have the discretion
over the next several weeks to remain with or leave us.
Let me make a personal request that if you do decide
that life's getting in the way or you are thinking
to yourself you are the least comfortable person
in the room do reach out whether during office hours,
off to the side, or just reach out to me
so we can have a conversation.
We have a team of over 80 TFs and CAs,
all of whom are very eager to make sure that every single one
of the 646 in this room make it through to term's end,
and you can and you will but do engage us in a conversation
if you are feeling more
than just a little bit stressed at any point.
With that said, we would like to, and do take advantage too
of the option to do pass-fail which we can do
up until the 5th Monday, and more on that in the syllabus.
So with that said I cordially invite all 646 to lunch,
most any Friday during the term.
Because it's a large course we
like to make sure there are more opportunities to chat with me,
with the TFs, with the CAs, and often with industry guests
and recruiter friends of ours so that you have the chance
to make the course feel much more intimate.
So typically what we will do every Friday or so is open
up an RSVP, starting next week, where we will take 20
or 30 folks in the class out to lunch somewhere in the square
or a house and really just have a casual conversation.
Because we will no longer after today have lectures
on Fridays we will try to use Fridays for that lunch slot,
but for those for whom it's impossible we will try
to make other opportunities available.
So more on that next Monday when we set up the RSVPs.
So with regard to our team of some 40 TFs and 40 CAs,
all of whom are here to help you throughout the semester --
oh, very nice indeed.
So that's our staff.
You can take a look at it online, but you should know
that office hours have commenced.
Indeed, our high-tech, fancy, iPad-based approach
to office hours did begin in [inaudible]
and we thought we would share a few statistics.
So, over the past few nights alone,
though this is just term start, we had over 25 questions asked
on Monday, almost 100 questions asked on Tuesday and Wednesday,
and 2 questions asked last night.
Which is great because no one is taking late days
yet really, so that's terrific.
But in terms of the wait times, which has been the target
of this whole initiative, on Monday the average wait time
between raising your hand and getting help from a TF or a CA,
and even on Tuesday though this bar looks big...that's seconds
on the left-hand side, so the wait time was just
over 2 minutes, and then that decreased again on Wednesday
when we threw more man power at it
and our response time last night was really good,
it was 0 seconds, so Thursdays are clearly the sweet spot.
But in fact, quite the opposite.
So do realize that one of the best things that you can do
in tackling the problems sets is to start early,
no because they are going to take all week necessarily
but honestly so that you have that option
if you are stressed out, you hit some barrier,
or you hit some stupid bug and you just don't see it,
you can call it a night and you can take a break.
And honestly to this day any time I work
on coding projects the moment I start
to feel myself getting stressed you just get stupid,
or I do at that point.
And it is just not worth trying to force through it,
better to take a break and come back a little more refreshed
and a little more excited.
So what's on the horizon?
So sectioning has commenced.
You will use the FAS sectioning tool, which is linked
on the course's home page between now and Monday
so that we don't have to rush putting you into sections
that might conflict with your other classes.
The sections themselves won't officially start
for another week out so what we will have this coming Sunday,
Monday, and Tuesday is one super section per day
to which anyone can come.
They are not based on track.
It's simply an opportunity to get together with just a couple
of TFs and generally more students this first week
for an opportunity to discuss the problem sets
or lecture material or the light.
The schedule for those will be posted
on the course's website home page.
So what lies ahead?
So believe it or not starting this weekend
or this coming week, the first C-based problem set you will
tackle will be, we hope, quite a bit of fun.
Not only will you get this thing called the CS50 appliance
installed on your computer,
you will also implement a few programs.
One, the simplest of them,
is what is generally called Hello World.
And we have seen that as recently as Wednesday
where you just make a program do something silly,
like say hi, or the like.
But then we will wrap up to things more interesting
and reminiscent, perhaps, of the types of problems you might want
to have solved in scratch where you will be challenged
to implement a simulation of sorts and that interaction
that I had up here in the first day
where I offered either $10 million up front
or just one penny a day, and you will get an opportunity
to just get comfortable with the syntax and implement
that sort of comparison.
You will also be challenged
to solve what is generally called a greedy problem,
but more on that in the spec,
and we also drew inspiration this year and last from one
of CS50's own students, [inaudible],
who graduated in 2010.
Her final project, if familiar,
was this site called Isawyouharvard.com.
If you click on this page here are statistics.
You will see that she is using a free library,
or API from Google, that allows you
to create visualizations quite easily by plugging
in data she has in her database and generate charts as to
who is spotting whom or where sightings occurred.
We will implement this and it will be a little less sexy
in the context of the appliance using C implement charts
like these.
Then fast forward [inaudible] then these fairly primitive
charts will fairly quickly evolve
into something more sophisticated.
Now those of you tackling the hacker edition
of this P set will tackle some similar problems
but there will be a twist to each of them
where the bar will be raised and you will have to think
of it harder and again the hacker editions assume
that you have some prior programming experience
or you simply want to push yourself as hard as you might,
but again we do expect and we do encourage a super majority
of the class to tackle the standard editions by default.
The walkthrough now for problem set one will be this Sunday
at 7 pm.
We are going to exit Maxwell [inaudible] because it's hard
to get in on weekends without swiping and so we will relocate
to another building but the location will be posted
on the course's home page.
And now the last, perhaps most compelling announcement,
is that there is an event in Saunders around 2 pm today
so we will adjourn early.
So that is our parting Friday gift for you.
Thank you.
So let's dive right in.
So we looked Wednesday for the very first time at how
to write a real program by using real programming language,
and by real I just mean a little more traditional.
A little less user friendly than scratch
but ultimately much more powerful because with a language
like C, and later PHP and JavaScript,
can you command a computer
to really do some sophisticated things without some
of the limitations or challenges that you might have run
into in scratch where you might have just found it hard
to express yourself sometimes
because a puzzle piece just didn't exist
or you didn't know where to find it.
So we introduced C and we introduced the CS50 appliance
and just to kind of get things flowing, what, in sort of easy
to understand terms, is the CS50 appliance.
Someone?
>> An operating system inside of a window.
>> Good. So it's an operating system inside of a window
on your computer so it allows us to create the illusion that all
of you are running the same operating system.
It happens to be called Fedora, which is a version of Linux,
but what that means is that you will all have a uniform desktop
open in a window on your computer no matter
if you have a Mac or Windows or any other type of machine.
But once you get this thing installed and the PDFs
from problem set one, which will be posted later today
on the course's website will walk you
through the process of installing that.
Once you have your environment on the computer,
we opened up a very simple text editor last time,
akin to notepad or text edit or even Microsoft word,
but much simpler than that.
So if I go to menu in the CS50 appliance and I go
to programming and I go to G edit here or,
notice at the bottom just like in Mac OS
and Windows I can click an icon that is just right there,
always at the bottom...I get this text editor like this.
And in the top here I have a blinking prompt
and a big white space where I can start writing code.
And at the bottom I have what we call a terminal window,
and this is just another program that happens
to be embedded inside of G edit
and it just facilitates the process of doing what?
Running your program, and before that compiling your program.
Because in Linux and also in Mac OS and even in Windows,
if you have the right tools, the first programs will write
and assume a command line environment where you don't
so much double click icons and chose things from menus,
rather when you want to write a program you type it's name
at a prompt.
That program might be GCC, which was the name
of the compiler we used.
That program might be called hello, which you yourself wrote,
but ultimately you can run it in this window.
Now as you acclimate and the problem set will mention this
as well, but this gets very limiting.
You have got 90% of the screen for your code and 10%
for this terminal window.
Well realize also under the CS50 menu you can go to menu,
programming, and then terminal,
and then you can actually get a full screen version
of this very same tool.
It's black and white instead of white and black
but the program is exactly the same and then just like a Mac
or a Windows computer you can just alternate with these icons
at the bottom between whatever program you want to use.
So just realize you have options,
especially if you find this interface limited.
Now later in the term we will transfer
to more sophisticated tools
but for now the intention very deliberately is
to keep things simple so we can focus on the ideas and the code
and not so much on the intricacies
of stupid new programs.
We will get to more sophisticated things
before long.
So how do you actually go about writing a program?
Well, you open up G edit, you type in some code
and we will come back to that in a bit, and then you save it.
And then you save it with what?
Easy question from file extension last time.
So .c. So .c is just a convention
where if you are writing a C program call it .c
and in the world of scratch your files happen to be called .sv,
but your operating system may have even hid
that file extension from you.
So that's it.
It's just a convention.
Then once you have a file called Hello.C,
recall that we can compile it in a couple of ways
but the simplest that we focused
on ultimately is just to type 'make hello.'
Now, make is not a compiler.
It is just one of these automating tools
that just makes it easy to figure
out what compiler commands to type so you don't have to think
about it, or type out something very long and tedious.
So 'make hello' will look in your current folder
for a file called Hello.C,
and if it is there it will translate it
into those 0s and 1s.
So how did you proceed to run a program called hello?
Good, .slash hello, so generally .slash
and .this way would be forward slash
and the other way would be backslash.
Windows is back slashes
and usually other OS's are forward slash, or just slash.
But exactly, dot slash and then the name of the program, hello,
and the dot slash is just a nuisance that specifies
that it is in this folder because I put it there,
it is not some program I installed
in some special default location
as you would typically do on your own computer.
So that's how we might make it and that's how we might run it,
now let's do some more interesting things.
So to start writing programs in scratch you had
when green flag clicked, or maybe when I received,
if you were using event, and that block indicated
that this is the guts of this program.
It's a script.
Well in C, as in a lot of programming language,
made is the equivalent of that.
This is the name of the function,
the sort of miniature program you need to write
with a simple text editor that automatically gets executed,
gets run, whenever you type dot slash hello,
or whatever your program is called.
And so main is really the guts of our program, but main itself,
though a function, can call other functions.
Recall that on Wednesday we used several times a function called
Print F and the F stood for...just formatting.
So with Print F you don't just need to print
out verbatim letters and numbers,
you can format them in interesting ways.
And indeed problem set one will have you leverage Print F
to print things out like money and the like so
that you don't have to figure out how
to insert a decimal point in the output,
you can just tell Print F to make this look
like a decimal point, make it look like a piece of currency.
So Print F takes we call them arguments or parameters,
or more generally inputs.
And those were things in between the parentheses
and it could take 0 arguments or 1 argument or 2 arguments,
you just separated them by commas.
But by far the most common thing we saw was just
to have a very simple function.
They used Print F and it looks a little something like this.
So I am going to go ahead and preemptively go to file, save,
and I'm just going to put this on my desktop for now.
I'm going to call this Hello.C, and hit enter.
And again the problem set will walk you through this
but even though it looks a little different from Windows
and Mac OS, it's the same idea as poking
around on your own hard drive.
So I'm going to click save, and notice the top
of the window has changed,
indicating that this is indeed Hello.C.
And silly though this is to dwell on file save,
the advantage of this in G edit is because the files ends in .c,
G edit is going to do something fancy
for us called syntax highlighting,
where it will colorize everything I type in a way
that hopefully makes interesting things pop out,
rather than leave my code just black and white,
so it's not saving the colors in the file it's just showing them
to me as I go, but recall I began this program
with includes standard IO.H, then I had [inaudible].
Now notice what G edit is doing to, which is both helpful
and annoying depending on your view.
It has started added parenthesis for me, so I typed main
and then did open parenthesis, it preemptively
because it knows I'm writing C and figured
if you open a parenthesis and you probably want to close it,
I will do that for you.
So realize that tools like this try to save you keystrokes
but it can get annoying if you are not expecting it
so just know you can disable this by going to edit
and preferences and poking around.
So after this I had some curly braces
and those two were automatically inserted partly for me
and then I just said something like oh hi world.
So let's go ahead and now compile this code
and we have now the following end results.
Let me go into my desktop
and notice what I am doing down here.
At the [inaudible] prompt we have, by default,
my so-called home directory.
This is where all of my files get stored and notice
that the thing in parentheses that just says tilde,
this is just shorthand notation for exactly that.
You are in your home directory.
But I said a moment ago that I saved this file on my desktop,
so recall from Wednesday that the command
to change directory is quite succinctly CD.
So by typing CD desktop and hitting enter notice
that my prompt changes, reminding me parenthetically
where I am, and if I now type LS for list, I will see everything
that is on my desktop.
And indeed if I minimize this window temporarily and go back
to my desktop there is Hello.C. It wasn't there before
but I created it with G edit.
So let me maximize this window again and I will zoom in so
that it is more legible.
And if I now want to compile my very first program
for the second time, I type make hello.
Quite simple as that, so make hello, enter.
The fact that no error messages appear, just this one line
of output, means make indeed automated the compilation
of my program.
Notice that if we weren't using make we would probably have
to type a fairly long and fairly annoying cryptic command
like this, GCC [inaudible] and so forth,
and we will explain what those mean,
but for now make just simplifies this process.
So to now run this program as we proposed before, I can do hello,
but not quite hello because it is indeed
in my current directory.
So just to make this more clear, this gets frankly even
in lecture a little annoying using such a small window.
We can do exactly the same thing with this terminal window.
I click terminal, I do CD desktop, I type LS,
and I see the same file plus another one.
What's nice about the black and white version of terminal is
that it also colorizes files based
on whether they are executable, or directories, or files,
so it is a little more user friendly.
So know that it exists and similarly I can now run hello.
And if I sort of accidentally tried
to recompile it then it realizes you haven't changed your code
and it is not going to waste time regenerating the same 0s
and 1s.
Bam, we are now done with hello.
So let's tease this apart and start adding new features.
So at the very top here we have sharp include standard IO.H,
and just in easy to understand terms what was
that doing for us on Wednesday?
>> [ Inaudible ]
>> Exactly.
That directive includes standard IO.H, specifically
in angled braces, and it is telling the compiler,
GCC specifically and in turn make,
and for any functions I might call and see if they exist
in a file somewhere on the hard drive called standard IO.H,
because if I myself didn't write them odds are someone else did
but I have to tell the compiler in what file they are,
and we call them declare.
So we have not used ourselves a .h file,
we will start using those before long,
but for now a .h file just contains the names of functions
that other people have written that you yourself can use.
Now fast forward down here and there is this mention
of [inaudible] and I mentioned briefly on Wednesday the notion
of error codes and the like, so for now just trust
that every program returns a number and the best number
to return is 0 and anything else is usually a problem,
so for now we are just going to take on faith it main,
and then in parenthesis void, and this is a new word,
but take a guess what it means if you say void
in between parenthesis.
Just nothing, it takes no arguments.
It takes no inputs and that is kind of sensible here
because all this program does, quite foolishly,
is just say oh hi world.
Oh hi world.
There is no notion of input
so I can explicitly tell GCC don't even expect any input
into this program.
Just do the same thing again and again.
So now the curly braces are just a convention.
Print F is the name of a function that happens
to exist in that file.
How do you know?
Well, you kind of learn these things in lecture
or you read them in documentation
and you just know what files to include.
Now between quotes we have what we call an argument
or a parameter and you just have to worry about the minutia
of things like the closed parenthesis, the semicolon,
and more interestingly this thing,
and what did backslash n represent?
Okay, good.
We will move quickly then, so new line.
And that is telling the computer explicitly to put a line break
after these words because otherwise it is not going
to appear.
All right, well we can do things
that are a little more interesting now,
like not just say oh hi world.
Let's say oh hi David, or some arbitrary name that I type in.
We need the ability now to get user input
so we can actually do this with the following syntax.
A word, recall from Wednesday,
is generally called a string in programming.
A word or a sentence, any sequence
of characters, is a string.
I'm going to call it S, only because I only have one string.
I know it's S and I don't need
to give it something more descriptive.
Then it turns out there is a function I can use called
get string.
It too takes no arguments, but just to distinguish the two
when you call the function
that takes no arguments you don't have to say void.
You only say void in something
like if you are saying preemptively don't pass
me anything.
So we will tease these apart before long,
but for now, get string.
Open string and close string is going to do exactly that.
It is going to get a string from the keyboard and it is going
to hand it to me in a variable called S. But unfortunately I am
about to run into a problem.
Let me go down here and I am going to change
that to percent S and then I am going to put a comma S
because if you recall
from Wednesday briefly this is how I dynamically inserted the
value of a variable into a string
that I don't necessarily know in advance.
I know I want it to say oh hi, something,
but to dynamically insert that something you use a format code.
A format code is just something that starts with percent,
percent S means string, put a string here.
So comma S means take that value, whether it is David
or whatever the user may type,
and put it inside of the string itself.
So unfortunately this isn't quite perfect.
Let me go down to my terminal window,
this is still called hello.
I am going to go ahead and make hello,
and wow, lots of issues here.
So when in doubt, and honestly, if a whole lot
of errors scroll it doesn't mean you made an infinite number
of errors.
It might mean you made one
and confused the heck out of the compiler.
So never start fixing errors from the bottom up,
always scroll back up and try to fix the first one first.
And there is the first one, error: unknown type name string.
Well it turns out we are kind of lying to you here.
It turns out in C there is no data type called string.
There is it, there is float, there is char
and a few others we mentioned before, but string is kind
of a CS50 simplification just for the first week or two.
So if you actually want to use this data type you actually need
to use another library, so I am just going
to do some quick copy paste because it turns
out in the appliance is a file called CS50.h. And in
that so called header file is not Print F this time,
but functions like get string and get it,
and some other user friendly functions that just make it easy
in these first weeks to do simple, reasonable things.
So now I am going to save this file.
I am going to go back to my terminal window and I am going
to go ahead and rerun make hello, enter,
and now all is better.
I still see this cryptic command
but I don't see the word error so now is better.
So let me go ahead and run dot slash hello, and nothing seems
to be happening but that is
because it is waiting for some input.
So let me try typing my name, enter,
and now it says oh hi David.
Well we can make this marginally more user friendly.
Let me scroll to the top, and rather than just kind
of blindly getting a string from the user,
let me first say Print F, say your name, colon, space,
semicolon, just to kind of format it in an interesting way.
Now let me go back to the bottom here.
Let me rerun hello and hit enter, and bug.
Man, not really a bug, just a stupid mistake on my part
because I didn't recompile the program.
And as an aside if you kind of get stuck
in those awkward moments where your program is running
and you didn't want it to run,
almost always control C is your friend and that will quit
out of whatever program you are running at the command line.
Control C and it just looks like carrot C
when it actually appears.
So let me rerun make hello.
That looks good.
Let me now rerun hello, enter,
and now it just looks a little prettier.
It's still underwhelming, the end result,
but at least now it is becoming a little more user friendly.
Yeah?
>> [ Inaudible ]
>> So to be clear for all pieces that you should start using,
in general you could download something like the CS50
or the CS50 library on your own computer
if you were programming outside of the appliance,
or more generally there are other functions altogether
called Scan F, or S Scan F,
which are generally used instead.
But more on those in the future,
for now the CS50 library simplifies these details.
Any other questions?
>> [ Inaudible ]
>> An excellent point.
So I seem to have contradicted myself whereby I said main does
not take any input and yet here we are clearly taking input
from the user, so long story short for today,
there are two types of input.
When you run a program at the so called terminal window,
recall that we are typing things like make hello.
Well, the program in this case is called make
and I am passing it input the name of the program I want it
to make, so this is what we will call
in a future week a command line argument.
It's input you provide when the program is run
and you can't really do this in a GUI,
a graphical user interface,
because you either double click an icon
to run something or you don't.
And in command line you can type words after the name
of the program to provide it with input
but notice what I've been doing is just been saying hello,
so in this sense does hello not take any command line input?
It does take input later
but it takes it via a different channel, a different mechanism.
And that mechanism in this case is called get string.
So we will come back to command line arguments before long
but for now our programs will remain relatively simple
so that we only get input inside of the program itself
with functions like get string and the like.
Any other questions?
>> [ Inaudible ]
>> A good question.
A word on spacing.
So what I have done now is what we will call a matter
of good style.
The fact that I hit the space bar
after this comma before the S is not strictly necessary
but it makes ultimately the code more readable.
Not necessarily if your program is only 5 lines long,
but when your programs are, as they will be before long,
100 lines long or even more it just makes it easier
for the human, you, to read it or even colleagues of yours
with whom you are working.
Similarly here is this a convention.
I am indenting just as I did with Rob
on the stage when we did PBJ.
He invented the pseudo code as we typed.
Similarly here am I hitting tab or really 4 spaces
to actually indent my code to just make it more readable
and more clear what the control flow, so to speak, is.
So you will see in problem set one that we ask you
to read a short style guide written by CS50
that essentially gives you some quick dos and don'ts
as you figure out exactly what kind of style you yourself
like with which to write code.
Yeah?
>> [ Inaudible ]
>> A good point.
So you may see if you read ahead and if you look
at other examples online that a lot of time people,
myself included, will write at the bottom
of main a statement like return zero.
Thereby, be ever so explicit what the exit code is
for this program.
I am actually leaving that off now as a matter
of pedagogical simplicity.
It is actually not strictly required.
If you leave it out zero is automatically returned for you.
So yeah, it's correct, but just a distraction so I tend
to leave it out until our programs get longer.
Let's come back in just a moment.
What else is there besides just get string?
Well in the CS50 library there are a whole bunch
of useful functions.
Capitalization does matter with C,
so the fact that we have capitalized get char,
get double, [inaudible] and get string is deliberate so that
because they are all capitalized
in this way it just makes it more clear to you
in these first weeks that this is a CS50 function
and not something built in to C.
Because eventually we will take these training wheels off
when you can get user input in other ways,
including from the web, but for now these are all
CS50 functions.
So what's the difference between these?
So get char gets a char.
A char? What is a char?
A character.
It's just a single letter or a single number
that was typed at the prompt.
And how was that represented?
Well, with 8 bits or 1 byte,
and recall when we had our human volunteers the other day they
represented a byte worth of bits
and they were representing ask characters, so long story short
if you want to ask the user just for the letter B
and then the letter O and then the letter W, you can ask him
or her for 3 chars one after the other and each
of those chars will be put by the computer
into a different byte, 8 bits, in order to store that value.
But we will see examples of that before long.
Now there's get float.
What's a float?
It's a floating point number or a real number.
It is something that has got a decimal point in it
and it is 32 bits typically, but this is somewhat dependant
on the machine that you are using.
And sometimes just 32 bits is too small so we instead want
to double it, so there is a double.
So the get double function, meanwhile, gets you a double,
but it uses 64 bits, which just gives you more precision.
One of the goals of showing you the video on Wednesday
of the various missile mistakes was to demonstrate
that actually taking into account or failing to take
into account how many bits, how many 0s and 1s you were using
to store your values,
can absolutely have significant effects.
And we saw this again 10 years ago in Y2K.
It wasn't quite an issue of bits per say, it was a matter
of digits then, but the idea was the same
if you only use 2 digits you are going to run into a problem
when the century rolls over
and you now need a third digit potentially to represent that,
as was the case between 1999 and 2000.
So what else is there in the way of type?
So there is char, there's double, there's float,
there's INT [assumed spelling]
and there's the goofily named long-long
and we'll revisit these before long in the problems
that will introduce you in more detail to some of these.
But again a char is one byte or eight bits.
A double is sixty-four bits or eight bytes
if you just divide by eight.
A float is half that, thirty-two bits.
An INT is also 32 bits and a long-long,
just to round this out, is generally 64 bits.
And so part of the problem set will actually have you playing
with money, the notion of ten million dollars
and potentially more for which you know you probably don't want
to run out of bits if the downside is you don't get
as much money as you're due.
So you'll see in this case PSet1
that these data types become applicable.
So one other detail here,
so in the CS50 library there's not only the notion of a string,
which we'll tease apart before long, that just represents
and sequence of characters, multiple chars,
there's also what's called a bull.
And we actually had bulls or the notion thereof in Scratch.
It turns out in C there isn't a bully and data type true
or false so we've created one in the library
so that you yourselves can represent the idea of true
or false and we'll see some examples thereof.
And then there's simple stuff, to be honest.
Computers at the end of the day are indeed calculators
and so there are mathematical operators built
into C. You can do plus and minus and divide and subtract
and so forth and just know, as an aside,
that just like in grade school
where there was a well defined definition of the order
of operations - multiplication comes before plus and so forth -
most of those same grade school rules still apply.
And this chart is not meant to overwhelm but just
to be a reference down the road if you're ever wondering
if does this symbol get executed
by the computer before this other one know that charts
like this exist and you can refer back to the lecture slide
when the problem arises.
But the simplest rules of thumb still apply.
Multiplication binds with higher priority than plus
so realize you might sometimes in code need some parenthesis.
Now let's finish up print death.
So print death we've used percent S thus far
but there's other format codes.
If you want to spit out a character,
you don't say percent S you say percent C
if it's just a single character.
If you want to print out a decimal digit you say percent D,
just a human friendly number.
If you want to print out a floating print value you print
out percent F, whether it's a float or a double,
and this just means that print F will take care
of putting the decimal point aesthetically wherever
it belongs.
And as we saw the other day it will also decide for you
if you don't specify how many decimal or how many numbers
to show after the decimal point.
And then lastly, and just as an aside,
there's also this crazy one LLD, long-long-decimal.
So this is actually important because if
over the next few weeks you use for instance a long-long
because you really want lots of bits to store a big number
but you try to print that number using percent D it's going
to look completely wrong.
It's going to be negative, it's going to be smaller and that's
because print F is going to be misinterpreting the bits
and essentially only looking at thirty-two.
So if you want to tell something
like print F I'm using sixty-four bits just realize
and refer back to things like these other format codes.
So those are just some building blocks.
Let's actually do something with them.
So just as in Scratch we had conditions so do we have them
in C and we saw a glimpse of this on Wednesday
and so the next several examples are really meant
to just translate what was more user friendly and puzzle piece
like to something more deliberate,
something more cryptic and will be increasingly familiar.
If you want to express the notion of a condition,
if this is true do this, well the syntax in C is to say if --
space -- open parenthesis -- and then something --
we'll fill in the something in a moment --
and then open curly brace and then do this.
Now in C this slash slash actually represents
something special.
For those already familiar it's a ...
>> Comment
>> It's a comment so a comment just means this is not actually
a code, it's just English
or whatever language I personally speak that's --
that's a notation to myself of what's actually going on.
You might not have noticed these in Scratch
but if you right clicked
on the scripts area you could actually paste
in a little yellow sticky, like a Post-It note,
and that was the equivalent in Scratch
of just notes, comments to yourself.
C also has this.
C also has another syntax that you might see in books
and my own examples whereby you can do slash-star-star-slash.
The advantage here is that this syntax can actually span lines
and you can say something like 'and this'
and that's all comment, whereas the slash-slash only applies
to one line.
So just realize they're two different styles and it doesn't
so much matter which one you use so long
as you're ultimately consistent.
Now this only lets you do something or not at all.
Can we do more?
>> What about pound or sharp?
>> Pound or sharp do not work in C. So the only two options
in C are slash-slash and slash-star.
So what if we want two options, two forks in the road?
We can do if this is true do this else do that and just
like in Scratch if we start embedding these things we can
have three forks in the road.
We can say if this do this, else if this condition do that,
else do this other thing.
So again, same ideas in Scratch, we just need to express them now
with a keyboard but the ideas are the same.
Yeah?
>> Is there a way to do automatic formatting in C?
>> Is there a way to do automatic formatting?
>> Yeah, like start [inaudible]
>> Good question.
So those of you with prior backgrounds might have used
tools that actually kind of fix any [inaudible], any sloppy code
that you write for you.
G edit does not do that.
A program called Eclipse that we will eventually use does that
and for those more comfortable are welcome to use other tools
if they'd like, but for now the goal is
to actually get you yourself into the habit
of writing good clean code
until the tools will actually start making this easier for us.
So in short, in G edit no,
you need to be hitting the tab key or space bar.
So bullion [assumed spelling] expressions,
just as in Scratch you can say if this is true
and this is true do something or you can say if this is true
or this is true do something.
And as I recall those box are generally green in shape
and they've got little diamonds, if you used any
of these in your program.
To express that same idea in C you can say
if this condition is true
or some other condition is true then do this
with whatever's inside the curly braces.
Now the vertical bar, vertical bar is just again C syntax
for saying or.
A single vertical bar in a few weeks we'll see means something
else so this is just the equivalent of or.
The equivalent of and meanwhile is this, and-and.
And so now with this syntax we can express doing something if,
only if, two things are true.
So let's actually try to use a program that leverages these.
Let me go ahead and close Hello Dot C. I'm going to go into one
of the prefab examples for today, which is available
as a pdf and also as downloadable code
on the courses website under lectures, and I'm going
to open a file called Conditions 1.C
and it looks a little something like this.
Now at the top of the file there's actually a whole lot
of text but this is just a comment and the fact
that I've hit the asterisk this many times,
this is just a human convention to kind of make super clear,
this is not only a comment, this is a pretty huge comment.
You'd better read this but this is just a matter of style.
You don't necessarily need to adopt the same convention.
What's important though is that the first character
at top left is slash-star
and the very last one involved is star-slash.
All the other stars are just an aesthetic curiosity.
But here I just have some comments so let's scroll
down to the more interesting part.
Notice that I'm using apparently the CS5 library.
I'm using Standard IO so I can preemptively guess
that I'm probably calling something
like get string or get ints.
I'm using something from the library
and I'm probably also using what other function?
I kind of infer the answer.
It's right there.
>> [ Inaudible ]
>> Right, print death, right?
So I included standard IO.H because I'm calling print death.
But otherwise this is familiar except for a few new features.
So let me scroll down here
and here's now a more compelling role of comments.
Thus far just saying do this is kind of useless,
it's meant just to be a placeholder.
But now another matter of "good style" -
and we'll reinforce this in section
over the next several weeks - is to not just write your code
and leave it to the reader, whether it's CF, a colleague
or you one month hence,
to figure out what the heck you meant by your code.
The best habit to get into from the start is
to actually make a note to yourself in one line or two
or three or more what's going on so
that you yourself honestly the next morning your code
and realize oh that's what I was doing and why.
Moreover someone else
in the real world can also understand what you're doing.
So what am I doing here?
I'm asking the user for an integer.
How do I do that?
Well as before I just have this aesthetic of I'd
like an integer please, colon, space.
But I could have said anything there.
The interesting part is this.
So what's going on here?
Well before I used get string
and get string returns, so to speak, a value.
It figures out how to get all the user's keystrokes,
it then bundles them up together and then hands me a value.
But if I want to keep that around I need
to put it in a variable.
Well in Scratch to create a variable you click that button,
like create variable, and you give it a name.
Same thing in C but you have to be more explicit.
You have to give the variable a type and you have
to say is it a string, is it an int, is it a float.
So the key difference here in C is
that you literally have to say that.
I want a variable called N, its data type --
per this keyword to the left -- is an int.
And what do I want to put into that variable?
I want to assign it, so the equal sign means assignment,
whatever it is that get INT has gotten from the user.
Now just as an aside because you'll see other syntax still,
these two things -- getting in the INT and saving the INT --
do not all need to be done in the same line.
It is not uncommon to see this instead.
I'm going to put a semicolon there and then on the next line
or somewhere else in my program I can do this.
So the takeaway here is that you always have to declare,
so to speak, a variable.
And to declare a variable just means tell me its type,
tell me its name, semicolon, that's it.
But to assign a variable a value you have
to eventually use the assignment operator, the equal sign,
but notice that you don't re-declare what?
>> Int.
>> You don't say INT again.
You already told the compiler what it is.
It would be redundant to say what it is again
and so you don't need to say it again.
Now why use Version 2 versus Version 1?
You know frankly again as a matter of style,
and this is something that you kind of pick up on your own.
It just kind of looks a little ugly, right?
I'm a little anal and I just kind of like the elegance
of this one line of code.
And so when we say code is elegant
or clean it's these little details where your code starts
to get more compact and just more readable.
And this too is a style that we won't enforce on you
but rather encourage exactly what conventions you adopt.
Now what about here?
This is the meat of the program.
Analyze the user's input somewhat inaccurately.
Now here's the syntax for this.
If N, which again is the INT that the user just typed,
is greater than zero print out, you pick the positive number,
backslash N, else you picked a negative number.
Now I disclaimed in parenthesis somewhat inaccurately.
Why? What's the bug in this program?
>> Zero.
>> Okay, good.
So zero is obviously not considered.
So if I type zero what's it going to say?
>> Negative.
>> You picked a negative number and that's not true.
Zero is neither negative nor positive so we can fix this
so I can actually do something like else if N is less
than zero say this and then otherwise - can we go ahead
and just copy and paste and then get rid
of the redundant condition there --
you picked, let's say you picked zero.
And now I have three branches,
the last of which is the catch-all but the only case left
to catch is zero so this would now seem to work.
But also I seem to be violating the previous slide.
What piece of syntax have I omitted here?
>> Curly braces.
>> Yeah, those curly braces.
Remember in every prior example in black and white I had if
and then a condition in parenths, open curly brace,
then some comment like do this, close curly brace.
Well it turns out this is okay if and only if all
that you're doing inside of the fork in the road is one thing.
If you only have one line of code frankly it just feels kind
of lame to add three lines in total just to say one thing.
So this is correct and frankly
when your code gets more fancy this is actually more readable
because it makes it even more clear what's inside this fork
in the road.
But as it is it like triples the size of this block of code
and it's just not necessary.
So this too is a matter of style but notice this would be wrong:
print F, oh by the way hi or something like that.
This is now wrong and the program will not even compile
in this case because even though I've indented it, that's great.
You can indent things all you want.
If you've used more than one line of code
and no curly braces the compiler's actually going
to complain.
So let's go back to the correct version.
Let me get rid of this and I'll leave
in the third fork in the road.
Let me go down now to this file.
Now this happens to be a file I created in advance and I put it
in a directory called Lectures and sub directory called One
for week one and then in a sub directory called SRC and now
if I type L-S here's a whole bunch of code
that we'll be playing with this week and next.
Let me go ahead now and say make --
what was the name of this program?
Conditions One, enter.
That looks good.
Let me go ahead and run conditions one.
I'd like an integer please.
Let's say one hundred twenty-three enter.
You picked a positive number.
How about negative three?
You picked a negative number.
And how about zero?
So it seems to have caught that.
So we now have conditions.
Yeah?
>> [Inaudible]
>> Sorry, a little louder.
>> What if you try and feed the program a float?
>> Good question.
So what if I try to feed the program a float,
which is clearly not an INT,
a float being something with a decimal point.
And again recall that I'm using get N, well let's see.
And again this too should be a recurring theme like when
in doubt -- and obviously it's fine now
if you don't have your own computer up --
but when in doubt just try it.
The worst thing that can happen is it will break something
and that will in itself reveal the particular answer.
I'd like an integer please.
How about 1.99 enter.
So it says retry.
So one of the things the C50 library does too for you is
that if you're calling get INT it's only going
to let you get an int.
If the user is difficult and types in something stupid
like monkey it's also just going to reject it
and automatically say retry.
So it does these kind of checks for you.
If I wanted to actually get a float I would have
to actually use get a float.
Now just a quick tip, how do I get rid of this program?
I'm kind of done executing it.
Control C will abort.
Yeah?
>> If you were to take input in several lines
of code how would get INT react to that?
>> Good question.
If you were to use multiple lines of input as in the case
of let me go back to Hello where I say something like 'Hello,
my name is David,' enter.
So get string can only get one line of strings.
So to get multiple lines
of input we'll actually need more sophisticated techniques.
We cannot use get string but that's fine because at
that point these training wheels will be off.
All right, so we now have conditions,
we now have bullion expressions.
And again a bullion expression, to be clear, is just something
in parenthesis that evaluates or is true or false, one or zero.
But there's a few other pieces --
there's a few other features here among them called switches.
So it turns out if you have a bunch
of conditions you don't have to say if, else if, else if,
else if, else if, else,
just know that there's this other construct,
this other piece of syntax altogether called switch
where all you need to do is actually enumerate cases one
at a time.
And we won't dive into detail on this one
but the takeaway here is that just
as in Scratch there's rarely if ever going to be one right
or even one correct way of doing something rather there can be
any number of ways and so also as a matter of style
when you start to have if, else if, else if, else if, else if,
else if that's just a lot of redundant words.
So switch is just another way, as we'll eventually see,
that you can simplify syntax
by just listing them case by case by case.
But the most powerful thing that we'll need ultimately are loops
because otherwise our programs can only do one thing
and once and that's it.
So with loops, recall from Wednesday,
we translated some sample Scratch blocks
into the corresponding looping constructs.
Now this is one of the scariest ones to look at first
but it's actually quite easy to use.
In a four loop you declare a variable,
you generally call it I by habit,
then you say how many times do you want to increment I, plus,
plus, plus, plus, plus, plus, at which point you want to stop
and inside of this loop you'll do something.
So we can actually do something a little silly.
Let me go over to G edit here.
I'm going to go ahead and just create a new file.
I'm going to call this on my desktop let's say Loop.C
and again I'm just going to bang out some familiar lines.
So include Stand IO.H. I'm not even going
to use the CS50 library.
INT, main, void, now I'm going to do print F. How about this?
So let's do INT N, get int.
Okay I just lied so I need the CS50 library so not problem.
So CS50.H bugs off.
So I'm getting an INT from the user
and now what do I want to actually do?
Well I want to look like this, for INT I gets zero.
So give me an INT, call it I, initialize it to zero.
Go ahead and keep doing this so long as I is less than N
and then keep incrementing I on ever iteration of this loop.
So Scratch kind of automated some of this for us.
If you use the block like change variable by one,
it's a little simpler.
But now let me do this, let me indent here and just as with
if if you're just executing one thing I don't need curly braces
around the four loop.
Let me go ahead and print out the decimal number followed
by a new line that's currently inside I.
So very simple program.
Ask the user for an INT, print it out, then increment it,
increment it, increment it.
So let's see what happens.
This is called Loop.C. Let me go ahead and type make --
it's on my desktop -- let me do make loop.
Okay that's good, no errors.
Let me go ahead now and run loop.
Okay I need to type in a number, ninety-nine.
Okay that's a pretty fast program, right?
I can now scroll way back here.
Now of course you can do some perhaps silly things.
What might be a bug now in this program?
>> [Inaudible]
>> Yeah, what if I'm kind of a difficult user
and I say how about negative one?
See what happens.
What happened?
>> [Inaudible]
>> Yeah it's already less
than N. It's already less than negative one.
So what if I kind of goof and do something like this, right?
This is a reasonable bug.
Let me recompile and do make loop and now let me go ahead
and run loop and now if I type something
like one okay that works.
Negative one, uh oh.
So now we sort of get
to empirically test what the capacity is of an [inaudible].
And just to think back to Wednesday,
what is the largest INT that we can actually represent?
>> 21478.
>> Yeah so it's like two billion give or take.
It's four billion total if you have thirty-two bits
but if you want to use some negative,
some positive you actually have to sacrifice half.
So it's roughly negative two billion to positive two billion.
Frankly this is going to take all day if we keep counting
up this way so let's actually do something a little fancier.
In my program rather than an increment one let me go ahead
and say multiply by two.
So this is just fancy syntax
that we'll come back to over time.
But this is just shorthand notation for saying --
actually let me do it more simply.
I on each iteration is going to get the value of I times two.
So keep doubling it, doubling it, doubling it.
That should get us out of here quicker.
So let's try this: make loop,
let me go ahead now and run loop.
Negative one, huh, what happened?
Let' scroll back up here.
What's going on?
>> Started at zero.
>> Yes, I'm kind of an idiot right?
I shouldn't have started counting at zero
and then multiply it by two an infinite number of times.
That was not intended.
So let's go ahead and do make loop,
rerun loop with negative one.
Interesting, it stopped.
It didn't keep going.
It should have kept going, right?
It should have kept going again and again because so long
as I is greater than N it just go on up to infinity.
So what might have happened?
Yeah?
>> It went past the highest number it could display.
>> Yeah it went past the highest number it can display
and more specifically.
>> It became a negative number because it overflowed.
>> It became negative.
So here's the curious thing.
Just as with our example with humans we had eight bits.
Just because I want to count beyond
that eighth bit it doesn't mean you get a free bit all
of a sudden and now you have nine bits and ten bits, right?
You are limited in capacity.
So if we've made all these humans raise their hand
and then we said okay add one more number to your total value,
what would they do reasonably?
Maybe one of them puts their hand down,
maybe all of them put their hands down.
In other words, if you keep changing zeros to ones again
and again and you run out of permutations you're going
to have to start over.
But unfortunately once you start over and overflow well,
what comes after roughly two billion when you overflow?
How do you start over?
It becomes negative two billion.
So even though we didn't see it
on the screen here what happened is the zeros and ones changed
into some pattern whereby it actually was representing a
negative number, because again we only have finitely many zeros
and ones in thirty-two bits or even sixty-four bits,
and so now we had the illusion of some negative number
and this badness happened.
It just stopped.
But the loop, a four loop is not the only option.
We can actually use something called a while loop
and this shouldn't be too scary too because even
in Scratch you had repeat blocks, you had forever blocks.
Same idea and we'll see different syntax.
And then there's also this one too,
a do while loop whereby it does something one time
and then again and again and again.
And so you'll see in Problem Set 1
in particular what something like this can do.
Now let me just go back to the terminal window here
and demonstrate just two things to peak curiosity
as to what lies ahead.
If I go into the pre-fabbed code here you'll see a couple
of things, one of which is called Thad Gavin [assumed
spelling], named after the guy.
So this is when you really want to be anal
and pretty print to your code.
You can actually make it look pretty
by formatting it in this way.
This is not what we mean when we say good style.
This is a submission for a special contest where you try
to outdo all of the other geeks.
But what you can do here, which is pretty cool,
is if we run Thad's program you can do some crazy things just
using these loops.
So this is a C program.
It was only a few dozen lines of code - you saw the whole thing -
but with loops and with C we can do things like this
and this is just the beginning.
So with that said, let's call it a day.
PSet1 will be posted tonight and we'll see you on Monday.
[ Applause ]