[ Silence ]
>> All right.
Welcome back.
This is week two of CS50.
By now if you've dived in to problems sets one,
you probably encountered at least one of these.
So this is a photograph of an actual logbook of an actual
and in fact the first known bug in the computer program.
This was plot, this moth here under the yellow tape
from the Harvard Mark II computer, the successor
to the thing that's in the science center back in the 1940s
and an annotation was made
that this was indeed the first known bug literally to be found
in a computer and apparently the term stuck.
Next time you're down in D.C. you can actually see that bug
in our own Smithsonian so realize
that it has entered our own nation's history here.
But, your own bugs are perhaps a little less,
less worthy of enshrining but you will get better this week
and beyond at tackling these new topics.
So a very rapid review of some of these things actually looked
at last week and then we'll dive in to some actual examples.
So this was representative of a pair of Boolean expressions
and softball question.
The double vertical bar is just to know what type of Boolean.
So oaring two things together, so either the thing
on the left has to be true or the thing on the right
and if so, then you will, "Do this".
This by contrast was a Boolean and which meant both left
and right had to be true.
We saw similar constructs in scratch
and then we introduced conditions as well.
So you can have one fork in the road, two, three, four,
any number really but if you kind of extrapolate mentally
from some sample code like this,
you can imagine perhaps this getting a little unwieldy once
you have five or six or seven or so forth conditions.
So it turns out there's another alternative syntax
that functionally achieves exactly the same thing
and this indeed is consistent with this reality in programming
that you can do almost anything in multiple ways.
This is the so-called switch statements and we'll see
that it's actually a bit more limited than if else if else
if because everyone of the cases can only as well see be an inch
or a charr essentially.
You don't want to use other data types but it simply allows you
to enumerate in a slightly more human friendly way several
different cases that you might want to apply.
And then lastly last time we looked at loops and we looked
up perhaps the most syntactically complex one here,
this four loop.
And if you looked up during the music a bit ago,
you'll see that Foxtrot cartoon which actually was playing off
of this idea before loop, before loop has three segments
where you can initialize some variables,
a condition that you check every iteration and then one
or more updates that happens at the end of each iteration.
But we also have while loops which are little simpler
but you need some way of breaking
out of them potentially, so we'll see examples of those.
And then lastly, and this is the one
where maybe your curiosity should be peeked just a little
bit that might come in handy with in particular with Pset one
where you want to do something and then maybe do
that same thing again and again and again.
For instance this is a very common snippet of code to use.
If you want to prompt the user for some inputs
and they might be difficult.
They might type in a negative number.
They might type in "monkey" as I did last week and you want
to again, again and again tell them to do something
until they have satisfied some conditions.
So we'll see this construct in action as well.
So without further ado, let me go ahead and pull
up the CS50 appliance here and this is a buggy 1.C program
so if you're following along at home or on your laptops,
this is included in today's PDF and .zip file
but this is indeed a buggy program.
It's supposed to print out 10 stars on the screen.
But why does it not in fact print 10 stars
and what does it actually print?
>> Eleven.
>> Okay so 11.
So the consensus is 11, why is that?
So this is the sort of mistake
that should hopefully get easier to spot.
We're starting counting at zero and that sort of good forms,
they're not strictly required.
The problem is though that we're counting up to an equal to 10.
So if you just start counting on your fingers
that means this iterate this loop is going to iterate
for I=zero, one, two, three, four, five, six,
seven, eight, nine, 10.
So that's actually my 11th finger
and so that's indeed one too many star.
So an easy fix here might be what?
Just make it less than 10.
You could just delete this if you really wanted to,
you could do something like this
but again the former is probably preferred among programmers is
to by convention start at zero.
All right so that's buggy 1.c. Let me go ahead
and open up another one here.
This one is supposed to print 10 stars,
one per line but it does not.
What's the bug here?
[ Inaudible Remark ]
>> The line, the line break needs to be in the colon star.
>> Exactly, so the line break needs to either the inside
of the first printf here so that it actually gets applied again
and again after every star
because even though I've been dented in this nice pretty way,
remember that any time you have a condition
like a four statements
or a while statements or an if statements.
Id you have one line of code, you don't need the curly braces,
if you have two or more, you do.
So it does not matter how nicely you indent things,
you could also fix this problem by including
that curly brace there, another one here, for good style.
Let me go ahead and move the cursor back where it belongs.
And this too would work, so again another example
of two different ways to do ti.
Which one might you prefer?
Yeah, the one-liner is kind of nice
to be honest putting the backslash and right
after the star because you don't need the curly braces,
you don't need the second line of code, you don't need
to call printf sort of foolishly twice
and so there's multiple ways again to do something like this.
All right, how about one more here, so let me go ahead
and open up buggy 3 and in this case,
I am going to just defer this because I was not suppose
to open buggy 3 at this point in the story.
So we'll come buck to buggy 3 there.
So buggy 3, it's going to be pretty damn interesting.
So let me go ahead instead and open up something else just
as a sort of warm up here.
And again, raise your hands or look confused as visibly
as you can if you have any questions and we'll pause
or slow down at any point.
So this is a really stupid program.
It computes the total
of two numbers mathematically but that's it.
And I point this out because one,
it's actually syntactically correct,
but when I try to compile this.
I'm not sure GCC is gonna like it.
So notice the familiar now includes standard IO.h. Now
technically I don't even need
that because I'm not using printf here
so this really is a useless program.
So I've got int main void
and that's just copy pasted from last week.
Now I'm declaring x as one, y as two and z is x plus y.
So that actually looks pretty reasonable.
I'm declaring variables on the left and assigning them values
on the right but let me go into this directory and I'm going
to go ahead and type make math 1
and unfortunately GCC is yelling at me.
Error, unused variable Z than some crazy looking dash W thing,
all warnings being treated as errors.
But what's going on here?
Yeah
[ Inaudible Remark ]
>> Yeah exactly.
I may very well have computed Z and it's correct.
It's the sum of x and y but what was the point
of this whole exercise?
So one of the features of GCC that we've enabled by default
and the interests of pushing you toward correct code
as well designed code as possible is to yell at you
when you do something that's just a waste of time.
If you're not actually gonna use z as you might,
by using something like printf.
Printf presents what would it be for an integer?
>> D.
>> Present D for an integer may be backslash n for good measure.
Now this might make the compiler more happy
because now I'm not only declaring z,
I'm using z even though the program itself is
still underwhelming.
But if I now go back down here, let me zoom in
and rerun make math 1 now it's indeed happy and if I go ahead
and run math 1 I get back the answer three which is
of course one plus two.
So just to point out this error message that even
when you see things at first glance
that look a little cryptic just read into it at least the part
that frankly does not look overwhelming and see
if you can infer where the error is.
In fact if I go ahead and break this again
and delete the printf, let me zoom in and recompile math 1,
notice that it's actually being a little more helpful
than spitting out this message here.
Unused variable z yes, but it's actually telling me GCC that's
in math 1.c that I screwed up.
It specifically at line 19
and then somewhat less usefully specifically,
look at character number 9, give or take,
so nine characters into that row.
So it's actually pointing you toward what's probably
the error.
Now realize this isn't a golden rule.
If you actually have multiple errors,
you might actually be informed that you've got an error
at line 15 when actually it's on line 14
because you've done something wrong above it.
So sometimes the compiler can get confused but again look
for these clues as you try to diagnose these initial bugs.
All right so let me open up math 2,
which is now trying to do a bit more.
So in math 2.c I actually am fixing this problem.
So we already did that.
So you have a copy of the correct code there.
In math's 3.c, we're gonna go ahead now
and use a floating point.
But this two is actually a little broken.
So let's take a look at the code.
I've got standard IO for the sake of printf in main void
so that's void our plates and now I'm doing float answers
so a float just as a recap, it's how many bits?
>> Thirty-two.
>> So it's 32 bits.
It's not the biggest possible floating point value
but 32 bits is still a lot surely we can represent
something as relatively small.
It's 17 divided by 13 which should be one point something.
You would like to think that 32 bits is enough
to represent the number one, give or take,
but then I go ahead and divide 17 by 3 here.
I store the results in answer but I'm
in printing it out dot 2f.
The dot 2 denotes what?
>> Two decimal places.
>> So just two decimal places.
Percent f generally means give me a floating point value
but point two means only show me two numbers
after the decimal point.
What am I plugging an answer?
So this actually feels okay.
But let me go down here now and let me zoom in
and run make math three.
>> It does compile okay but when I now run math three,
I'm pretty sure 17 divided by 13 is not 1.00.
Frankly I don't quite remember exactly what it is.
Pretty sure it's not 1.00.
So what's going on here?
What's the problem?
>> We divide the two integers [inaudible].
>> Yeah so this is something we haven't talked about explicitly
but indeed, when you divide two integers
in C, what do you get back.
Well you're gonna get back an integer by nature
of mathematical operations in C. So 17 is an integer.
Why? Well it's obviously an integer
but more specifically it does not have a decimal oint in it.
So C views 17 as an int.
13 meanwhile also looks like an integer.
There is no decimal point so it too is treated as an int.
And that's actually a bit of a white lie.
It's treated as along typically but the results are the same.
It is not considered a floating point value.
So 17 divided by three gives me one point something.
Well that something can't fit into an integer.
It can't fit into an int and so the point something, something,
it's just thrown away.
This is called-- this was called truncation.
So the number is just truncated and you lose that.
So even though I'm then taking the answer
and I'm saying it is afloat, it's too late,
you've already thrown away everything
after the decimal point when you did the original division.
So if the problem then is that answer,
even though I'm calling it afloat is actually storing the
result of an integer divided by an integer which--
whose results is an integer, how do I fix this?
Yeah in the back?
[ Inaudible Remark ]
>> Yeah so I can actually introduce this other feature
of C known as typecasting or more-- so simply to cast and--
a variable from one data type to another is to cast it
so what you can do is what simple parenthesis,
you can do something like this, yes, 13 is actually written
as an integer but I would like the compiler to treat it
as though it's afloat.
And this is actually legitimate
because you're not converting apples to oranges.
You can reasonably convert an integer to afloat,
you just add a decimal point, essentially point 0000000.
So now this is effectively 17 divided by 13.00000 or be it
with some imprecision.
So now when the division happens, I get back afloat
on storing that float in a float called answer and so let's see
if my answer is now any better to make sure to save always
with control S or the file menu.
Let me go ahead and recompile math 3.
No errors, that's good and let me go ahead
and rerun math three enter.
Ah, that's the number I was hoping for.
So this might be sort of low level detail
but this is absolutely gonna be important even if he set one
where you're for instance trying to provide a user with change
and you're dividing some total amount by 25 cents or 10 cents
or something like that.
You're gonna need to beware, be mindful of this kinds of issues
that you might illiberally be throwing pennies away.
In fact if you think now, if you ever see
in the classic office space or the precursor superman three,
you might recall that the scam that they waged
in office space was to kind of skim the fractions
of pennies off of the dollars that we're going
through Inatech, the company.
Well this actually relates, right?
Those guys were programmers and what they were referring
to was one, this inherent imprecision
of floating point values that we saw last week and also the fact
that sometimes these remainders are just potentially
thrown away.
If you've never seen this movie, I do recommend.
Yeah?
[ Inaudible Question ]
>> Good question.
Why do you have to cast the 13 as afloat and not the 17?
Well first, it suffices to only due one of them so that's fine
and notice what happens here.
If I do this and save then recompile with make math 3
and then rerun so that actually would fix it as well.
I just chose one arbitrarily.
I could do two and frankly there's an even
simpler approach.
You could certainly just avoid this whole new concept afloat
of casting rather and just say fine.
Make it 13.0 and make this 17.0.
That might work as well.
Yeah?
[ Inaudible Question ]
>>So you can it looks a little weird
but you could also do this.
See it's perfectly content with that if you just
like the elegance of no trailing zeros.
Any other questions on floats?
Yeah?
>> We have done the typecasting, so is answer a float or an int?
>> It's a good question so before we did the typecasting.
Is float an answer or an int?
It is a float because we explicitly made it a float
but it was assigned an integer value
so what happens there is actually called implicit,
it's casting or implicit conversion.
So it is indeed a float
and conceptionally the point zero is just append to it
when the equal sign moves the value from right to left.
Any question over here?
Yeah?
>> Both of them need decimal places?
>> No, only one of them needs decimal places,
so essentially the sort of more powerful number takes control.
So while floating point number with precision
with the decimal point sort of supersedes the weakness
of an int and so you just need just one of them.
So again, the takeaway here is not
that the next time you divide one constant value by another,
you should be mindful of this.
But rather when you're taking arbitrary user input,
maybe dollars and cents, these are the kinds
of issues you need to be careful of.
And certainly in the real world,
if you're the person implementing the next automated
teller machine, these are absolutely the kinds
of issues you need to be mindful of when dealing with any kind
of currency and fractions thereof.
Alright, so let's transition now to this file here.
This is a file called nonswitch.c,
just to convey the idea that's it's actually not using
a switch.
Let me scroll down just a little bit here and see
if we can't read through this program.
At the very top, I'm using the CS50 library, standard I/O,
so that's a hint that I'm probably using printf,
I'm probably using get int or get string, something from CS50.
And now here is my main routine.
And the comments kind of reveal what's going on here.
So in that first line, I'm asking the user for an integer.
Notice that just aesthetically, I'm not using a backslash N
at the end of the line.
This is purely a stylistic decision.
I just want the cursor to blink to the right
of the prompt rather than put it on a new line.
But that's not strictly necessary.
The next line we use last week ints and gets GetInt.
So it's relatively straightforward now hopefully.
In future weeks, we'll actually look inside of GetInt
as to how it's working.
But for now, it's your-- how--
welcome to be blissfully content just assuming it gets an int
and hands it back to you.
So now we're finally using Boolean expressions in C
that are actually using the and expression here.
So in short, this seems to be a simple program that says,
if the user inputted a number that's between 1 and 3, go ahead
and you tell them, you picked a small number.
Else-if it's between 4 and 6, you pick the medium number,
else if you pick 7 through 10, it's a big number
and anything else, negative 0 over something huge,
it's gonna say you picked an invalid number.
So here too, just to point out in FAQ were a common mistake.
Realize that when you end two things together,
you don't necessarily want to say for instance,
if N is greater than 5, and end N is less than 4, do this,
'cause if you just think through that logically,
make sure that the two ranges you're comparing are actually
inclusive and not something that's greater than 5 and less
than 4, which is obviously impossible.
So just think about it.
If you're ever running into a bug
where you're using these Boolean expressions,
just consider what your actual logic might be.
So this is starting to feel a little ugly, right?
I've got 4 different conditions, it's a little hard to read
with all the ands and the greater than, equal signs.
And just to be clear to express the notion of greater than
or equal, in a-- on paper, you would say, angle bracket
and then the line under it,
there's no such key on the keyboard.
So the convention is angled bracket and then an equal sign.
Two separate characters with no space.
So let me improve this, debatably, with a switch.c,
nonswtich-- switch-- let me go ahead
and improve this as follows.
So rather than do this, I could actually say switch
and then what do you wanna switch on?
Well, whatever the value of N is,
and now I've got some placeholder text here
and what I can start to do is say,
alright, in case 1, do this.
And then I'm gonna steal my text from down here,
you pick a small number, and then I'm actually gonna do this.
I need to say break.
But then, I can do this-- oops, don't do that.
Then I can do this, I'm gonna go up to 4, we'll come back
to the ones in the middle.
You picked a medium number
and then I'll do one more for good measure.
Case, let's see, I think it was 4, 5, 6 or 7 was the next one.
You picked a big number.
And then just to make sure I capture every possible scenario,
I'm actually gonna have
at the very bottom here what's called the default case
where you picked an invalid number.
And then I'm gonna close the curly brace.
So again, we'll fix the fact that we're skipping 2,
and 3 and 5 and 6 in just a moment.
But this is just another syntax
to achieve exactly the same thing.
It doesn't have all of these angle brackets and such.
Instead the switch statement says, look at the value of N
and then check this list of possible cases
and whichever case actually applies, go ahead and do
that one and only that one.
So I can actually now round this out.
You can have multiple cases.
I can say case 2 and case 3.
Down here I can say case 5 and I can say case 6 and then lastly
down here, I can say case 7, case 8, case 9,
and I think I had 10 before, so case 10 and that's it.
So arguably, this too is now starting to devolve
in something a little messy but at least,
it's a little more schemable.
Rather than have to parse something visually,
that's kind of a big jumble of text.
It's pretty wide, it kind of-- it take-- requires more thought.
What's nice about switch statements, just as a feature
of the language is that bang, bang, bang, bang, bang.
You can see what the applicable cases are.
So just realize this is an option, but the only gotcha is
that what you switch on generally has
to be an int or has to be a char.
There're a couple of other things you can use
so it's somewhat limited.
Yeah.
[ Inaudible Remark ]
>> Exactly, case 4 or 5 or 6 are all gonna do the same thing.
They're gonna say you pick the medium number.
But this fact, I've introduced, notice this new keyword break
which you can actually use in a loops as well.
Notice what happens if I don't have that break.
So I think I got my syntax right.
I'm gonna ahead and save this in my terminal window down here.
I'm gonna go ahead and make,
this is still called nonswitch even though we've changed it
to a switch.
Compiles okay, so that's always a good sign.
Nonswitch, give me an integer let's say 5,
you pick the medium number.
Let's say 1, you pick the smaller number.
Let's say monkey, retry.
So that's the CS50 library catching that 0,
that's my own program catching
that saying it's an invalid number.
But notice what happens if I forget this break statement
which literary does what it says.
Break out of this chunk of code.
If I forget this and I forget this-- oops, not that.
If I forget this, and this one, leaving out the breaks,
which is easy to do and now recompile my code
and make nonswitch and then run switch and type
in 1, what's happened here?
Right, this is absolutely a bug but that's
because again C being a computer pro--
being a computer language needs to be told exactly what to do
and what this case statements mean is the instant you match
one o these cases, the codes just starts executing everything
you've written below it,
and only once you hit type break semicolon does it break
out of the whole switch statement.
So this is both an advantage sometimes and a disadvantage,
and advantage in that we can consider multiple cases
but a disadvantage if you leave out that break.
Strictly, it's not necessary to have a break under default,
but perhaps as a matter of good style and consistency,
it's good to have it there.
But it doesn't need to be at the bottom.
Yeah.
[ Inaudible Remark ]
>> It's a good question.
So what is it about switch that makes it the case that all 4
of those outputs are printing?
It's literally the definition of switch.
When you match a case,
start executing code until you see break.
So the subsequent case statements are ignored.
So the compiler is smart enough to realize, oh I've seen case,
I've seen case, I've seen case but until it sees break,
it's gonna keep executing everything that I happen
to have indented here.
So it's just the definition of the statement.
Other questions?
Yeah, in the back.
[ Inaudible Remark ]
>> Ah, good question.
Is there a way to switch to consider a big range of numbers?
No, you need to go back to the if condition and your use
of greater than or less than if you actually wanna consider
a range.
So you wouldn't wanna use a program like this for 1 to 100
because frankly, then this switch implementation would just
be messier and uglier and much longer
than the corresponding if-else approach, so again,
just another tool for the toolkit,
another way in which you can solve these kinds of problems.
So let's-- let me go ahead now and open
up one more example here.
So this one is called positive1.c
and it's the first version of a little program
that actually uses that feature of a loop called do while
to actually prompt the user again and again and again,
especially if he or she is being difficult.
So there's a couple of interesting nuances here though.
So notice first, that again the program starts in a familiar way
with these two libraries and a bunch of comments up top.
Int main void is the same as usual.
But now notice a couple of new things.
So 1, do and then notice there's nothing parenthetically
to right.
It's just do and then open curly brace,
because what's interesting about do while is
that these lines are always going
to get executed no matter what.
So it's an opportunity
to do something before you even check some condition.
But at the bottom of the loop, you're only going to do it again
if that condition checks out.
So in other words, if the user here provides a number that's
less than 1, I'm gonna go through the do chunk
of code not only the first time, but again and again and again
until the user finally cooperates
and gives me something that is not less than 1, like 2 or 3
or 4 or 1 itself, at which point the loop will terminate.
And then, it's finally just gonna say thank you--
thanks for the 2 or whatever it is I typed in.
So, just to be clear, let me go ahead
and run this at the bottom here.
So this again is positive 1, so make positive 1
and I'll zoom in, enter, compiles okay, positive 1,
I demand that you give me a positive integer.
I'm gonna give it negative 1, it's gonna do it again,
negative 2, negative 3, negative 100, 0 still not cooperating,
but if I finally give it 1, thanks for the 1.
And this is a way again of maybe in say piece
at 1 actually doing something again and again,
but notice what I did.
What's kind of interesting about my declaration of N here
that I've not done in past examples?
[ Inaudible Remark ]
>> Yeah, I kinda declared it up top
and this was why I think we proposed this last Friday
as an option but then decided uh, just do it all
at once 'cause it's more elegant, right.
Every example thus far we've not had int end declared way
up there.
We did something like this.
But this introduces a problem now.
So N is clearly a number that I want to use in this program.
Not only getting it inside of the loop,
but I wanna use it obviously in the printf
at the very bottom of the program.
But here is a gotcha of C,
when you declare a variable it only exists within the confines
of the most recently opened curly braces.
Those curly braces define buzz word called scope.
So int N as declared here
between those curly braces only exists
in your computer's memory while you're executing code
in between those 2 curly braces.
The moment you pop out of that loop, for instance,
at the very last line, N is gone, the RAM,
the memory that it was occupying, those 32 bits,
have been taken away from you,
reclaims for some other random purpose in the computer,
and you no longer have access to those bits.
And thus N is out of "scope."
So what you'll see if you make this mistake is the following.
Let me go ahead and recompile,
now that I've saved this file we'd make positive 1
and already, there's a whole bunch of errors.
Again, this shouldn't necessarily mean you've made a
whole lot of mistakes, you made one
that actually has a ripple effect
on the rest of your programs.
So what's going on?
So first of all, look for the first sort
of reasonably phrase line, alright.
So in function main, that's apparently where my issue is.
This denotes line 22 of positive 1.c unused variable N.
So this is the error we saw before and it is unused now
because I'm declaring N inside those curly braces.
But then, I'm not using it,
it's like Z in that silly example earlier.
But there's something more here--
down here, then it's saying confusingly
on line 24 which is down here.
N undeclared, first use in this function.
So GCC is being consistent with this story.
The moment you exit curly braces N is gone.
So on line 24, the bottom of the program N no longer exists
and so the compiler recognizes this much and yells at you
and doesn't even let you compile or run this program.
So to just roll back, what's the fix here, what's the solution?
[ Inaudible Remarks ]
>> Yeah, quite simply, you declare N outside
of the scope of that loop.
And even though frankly, it looks, or might start
to feel a bit ugly to kind of put this variable
in no man's land up there.
That is indeed the correct solution.
It's still inside of main, so that means every part
of main has access to it including inside
of the do loops curly braces.
But at least now, it's within scope for the entire function.
Now just as a teaser technically and those of you
with prior programming background and especially
in Java, might be in the habit
of putting what are called global variables.
Where you declare variable outside of main even,
the advantage of this as we'll see in future examples is then,
every function you write, not just main,
you can write your own functions just
like you can write your own scripts and scratch.
Every function you write will have access to N
but this is generally considered very bad, very messy practice.
So we'll come back to this, but for now,
the correct solution is indeed
to put it right inside there outside of the loop.
Yeah.
[ Inaudible Remark ]
>> So you could.
So if you wanted to have a more specific yelling at the user
like that is negative, I don't want that, or some kind
of informative message, absolutely you could do it.
But you have to redo this loop.
The advantage of do while loop is that if you're content
in just saying the same thing again and again,
mean look how easy it is to do that.
But the downside is you can't provide more informative
messages like, that's 0, or that's negative.
To do that, you're probably gonna wanna introduce some
if conditions inside of the loop.
And maybe even not use a do while, just use a while loop
or for loop as we'll soon see and yell
at the user appropriately.
Yeah.
[ Inaudible Remark ]
>> Good question, is there a way to destroy a variable
within the scope of the program?
No. But we will have that feature in PHTP.
In the back.
[ Inaudible Remark ]
>> Does N have a default value?
Short answer is it depends.
Let me-- we'll come back to that before long.
So for now, assume, that if you do not give a variable a value,
it's gonna contain what we're gonna call literally a
garbage value.
It's gonna contain some unknown value
and indeed that's the common case for it to be some piece
of junk, some random pattern of bits that just
so happens to be there.
Oh, let's go here.
[ Inaudible Remark ]
>> Okay.
[ Inaudible Remark ]
>> Good question.
Is there any limit on the number
of logical conjunctions you can use in this parenthetical here?
If you wanted to say while N is great or is less than 1
or N is greater than say 99, if you wanted to only be
at digit from 1 through 99.
No, you could keep oaring things together ending things together,
you might wanna use parenthesis
to make sure the logic is all correct.
The only limit really is on readability.
And what a reasonable programmer would sort of be comfortable
with or yell at you at if it's just becoming unwieldy frankly.
Alright, yeah.
[ Inaudible Questions ]
>> Yes, within the confines of the curly braces,
you could keep reassigning N of their value in different lines
of code again and again and again,
that is perfectly correct.
The only thing you don't want to do as we--
as we discussed on Friday, is you don't want to redeclare
that variable by saying int again.
Once you've declared it stick with it, don't specify int
on the left hand side again.
So here's a slight variant of this.
So this is a version called positive2.c and its example now
of introducing a Boolean variable.
Bool is now a type in C that's built into C,
it does exist n C plus plus, in PHP in other languages.
But the CS50 Library gives you access
to a Boolean data type that's just true
or false in lower case.
And notice that just with this modification,
you can actually make the code a little more readable,
a little more like English.
So at the top here, I've this time declared a Boolean--
called thankful, just because I wanted to sound kind of cute
and read like English.
And I'm initializing that Boolean value to false,
and again, false is in all lower case.
Then I've got a do loop, and I've got printf,
I demand that you give me a positive integer
and I'll notice a difference
in this program is I am getting an int from the user,
but what am I doing with it?
I mean really nothing, I'm comparing it,
so I'm kind of using it for something but I'm throwing
that value away as soon as that line of code is done executed.
But in English, those 2 lines if get int greater than zero,
thankful equals true, what's the implication?
Well, it just means that this program is meant to be thankful
when the user finally provides it with a positive number.
Now why is this useful?
Because now, in my wild condition inside
of those parenthesis down here,
now we can introduce another piece
of syntax namely the equal, equal sign that says, well,
while, thankful is false, while I'm not thankful,
do this loop again and again and again.
We've seen Boolean expressions before, if you have a greater
than sign, or a less than sign, alright, just logically,
that's gonna evaluate to a bool, true or false?
X is less than Y, true or false, yes or no?
Well, you can literally put a Boolean value there
like thankful and compare it against a Boolean value
like false, or "true" to express the exact same thing.
But we can do with this slightly more elegantly
but we should first tease apart this.
Why am I doing equals, equals instead of equals, do you think?
[ Inaudible Answer ]
>> Exactly.
[ Inaudible Remark ]
>> Exactly.
So if you think back to what single equal sign means,
this is the so-called assignment to operator,
I might keep saying equal sign.
But in programming, this is the assignment operator
and it puts the value on the right
into the thing on the left.
Now the problem is the world kinda painted itself
into a corner because the first time someone needed
to write a program that needed to express the comparison
of 2 values where in English or in math, we would say equals
to compare it to values.
Kind of out of luck 'cause we already used the equal sign
on our keyboard to know assignment
of values from right to left.
So the world decided that well, fine,
let's just put 2 equal signs.
So equals, equals does an actual comparison,
equals does a single assignment.
So realize what could happen here.
What if I accidentally do this?
And this 2 is a very common mistake early on.
This code will compile, but what's gonna happen now?
[ Inaudible Answer ]
>> Exactly.
These mistake, stupid as it is this 1 character I made the
mistake with my keyboard is automatically every time the
while condition executes, it's going to assign
to the variable called thankful, what value?
>> False.
>> False. And then it's gonna evaluate it.
So again, just like in math, order of operations.
The stuff inside the parenthesis happens first,
then the big parenthesis themselves happen,
so thankful gets a value of false,
then the question is asked, well,
while false what's gonna happen then?
Well, false is false which means it's gonna break out.
So in other words, if you have while thankful, gets false,
this things is never gonna loop more than once,
because no matter what the user does,
as soon as you hit the while condition thankful is gonna get
a value of false, and bam,
the while loops not gonna repeat this itself,
because again it only repeats if it is true.
Alright, so 1 last example here, let me scroll
down to let's say positive 3 just
to introduce one more piece of syntax.
For those who remember what the previous example looks like,
what's the one difference in this program?
>> Exclamation point.
>> Yes, so there's this new piece of syntax,
the exclamation point otherwise known as bang in programming
and bang thankful here just means not thankful,
it inverts the value of a bully in expression
so I actually don't need to be so verbose.
I don't need to say wow, thankful, equals equals false.
I can instead just say, more idiomatically while not thankful
and that's how you would pronounce that, not thankful
and it just inverts whatever the thankful value is
so just logically now you can read it quite easily do print
that, get an int from the user, while you're not thankful
and you're only gonna become thankful
when the user does what?
Final [inaudible] check?
[ Inaudible Remark ]
>> Gives you a positive integer, that's it.
So again, three different ways this time
that we've done something but what's nice now is
that we have the ability to express ourselves
with just slightly new pieces of syntax,
but these programs are somewhat underwhelming to run,
let's add something that's just a little graphical now.
So here's one other example called progress.
Progress 1 actually introduces another header file
and another function that you won't generally use
but it does hint at fancy features to come.
Notice that because I read the manual, it turns out I was told
to include uni-standard.h, that header file,
if I wanna use the function called sleep
and you can probably guess what sleep does, it puts the program
to sleep for one second in this case.
So what is this thing seem to do?
Well, it's apparently gonna simulate progress
from zero to 100 percent.
So notice this is not a bug this time.
In my four loop, I deliberately want to go from zero to 100,
because I want to count from zero up through 100 in this case
and apparently it's gonna print
on every iteration percent complete, percent D,
that's an integer, we're gonna plug in the value of Y,
and now this looks a little cryptic, but take a guess,
why do I have percent D, percent, percent?
[ Inaudible Remark ]
>> Yeah exactly.
So this is what we generally call escaping a character.
Here too is one of these painting yourselves
into a corner.
If you have decided as a world to use percent
to mean here comes the format code for print
out like percent S, percent D, percent F, well you're kinda
out of luck if you want to actually say percent
because the compiler apparently has been trained to know
that anytime you see percent, another letter is gonna come
after it, but if you want a literal percent,
the way of doing that is to say percent percent.
Now you can imagine this actually becomes messy,
how would you do percent percent?
[ Inaudible Remark ]
>> Percent, percent, percent, percent, right,
or 3 percents is 6 percent, 4 percent is 8 percent,
but thankfully this is not a common case, right?
Odds are this is not a common program to write
so the world just made a judgment call.
Fine, that might happen but it's very rare.
So, what's this actually gonna do?
It's gonna print one per line, once per second,
this kind of progress bar.
So let's try this, let me open up a bigger terminal window here
so that we can see more at once and now we compile progress 1.
It compiles okay.
And again, for the-- to be a clear,
all I did was I opened a separate program that's called
terminal, this little black icon there,
and it just lets me do the same thing full screen just
so it's a little bit prettier, enter.
Alright, so it's getting interesting.
Alright, you can really see and feel this 4 loop.
Frankly, I'm already getting a little bored
so why don't we go ahead and hit Control C to kill this program
but let's assume that it's actually go up through 100
which it should because according to the code,
we have less than or equal to 100,
but this is obviously not a very user friendly progress bar,
right?
It would be nice if it's just the number updated itself.
But notice the take away here.
Print F is pretty limited, print F is like a kinda
like an old school typewriter, once you type out a word
and do back slash and enter, that's it.
You can't really scroll back and change what you typed
because it's already emblazoned on the page.
So in this case here it'd be nice
to somehow more elegantly just change the percent sign
so we can actually do that.
I mean, go ahead and open up version 2 of this, progress 2.
Now, it's a little fancier 'cause I had to fix a bug
but notice the difference now.
What am I actually using to print out the percent?
I'm not using percent--
backslash N, I'm instead using what?
>> Percent R.
>> So percent R. So this is one
of the silly computer is [inaudible]
and triple multiple times during the semester.
Long story short, in the world of Unix and Linux,
these older operating systems and modern operating systems
that are mostly command line based,
but just like the appliance
that now a days do have graphical environments,
the world decided that to end a line in a text file,
another is when you hit enter, what actually goes in the file,
well, [inaudible] backslash N. Now, unfortunately,
the folks at Microsoft decided years ago
that when you hit enter on your keyboard,
what actually gets saved in the file?
It's not just backslash N,
it's something called backslash R backslash N.
So 2 characters get saved in the file.
Those of you who actually remember typewriters might know
that on a typewriter, the old mechanical thing
when you hit enter on the keyboard, not only does
that roll that scroller kind of scroll this way,
also the printing head moves back to the left,
so that's what Microsoft is being consistent with.
>> Backslash N moves the curl of the roll thing upwards
and carriage return, CR, backslash R, moves the head back
to the left of the screen.
So technically, Microsoft is kind
of implementing the old school typewriter the most accurately,
but then Apple came along.
He decided to hell with you we're only going
to use backslash R. So we have 3 different operating systems,
major operating systems, 3 different ways
and this is thankfully mostly irrelevant except when you try
to open a file that you created on the Mac on the PC,
a text file or when you open a file on a PC that you created
on the Mac or Unix or a Linux machine.
If you've ever opened a text file on windows in particular
with no pad.exe and even though it's suppose to be a lot
of text is all on one crazy long line,
that simply because no pad [inaudible] backslash R,
backslash N, and if it doesn't see it, which it might not
if you made it on a Linux computer or a Mac, with I--
all together, you're just gonna get some big mess.
Wordpad by contrast familiar, knows about just backslash N.
So long story short, we'll come back
to that with web programming.
But for now, we're talking advantage of this as follows.
Backslash R has the effect conceptually of moving the head
of that's being--
of the printing head back to the left without doing what?
Moving to a new line.
So it just moves the printing head back to the left.
So the effect now is that on every iteration,
I'm gonna reprint percent complete colon
and then a number.
But because I'm printing the same exact words,
and only changing the number, we have sort
of a nice simulation of animation here.
If I make progress 2 and run now, progress 2 notice
that we actually have a fairly pretty looking implementation
now of a progress bar that's still a little slow
for our taste.
But now we're exercising more control over the screen.
Now, can we do a little better here,
this last version of progress.
If I go in here, down to progress 3.c notice
that I can do this also in different way.
So how am I doing this differently?
Before I did a 4 loop, and frankly, I would say 8 times
out of 10 when I write loops in any programming language,
I typically by default use 4 loops.
Even though they're a little uglier,
they're let you express yourself a little more succinctly
but we can do this otherwise.
I could declare I as an [inaudible] up here.
I can then say while I is less than or equal 100
and then what do I have to do on each iteration?
I can actually manually increment I
with this plus, plus.
So again, I would actually argue this is a little messier
of an implementation 'cause look, I have I at the top,
I've got this I plus, plus.
And again, recall what I did a moment ago.
This just feels a little more compact.
Everything is more tightly knit, but again, this hammer is
on the point that you can implement these things
in many different ways just as in scratch
with different pieces of puzzle pieces.
Any questions, yeah?
[ Inaudible Remark ]
>> Oh yeah, say it once more?
[ Inaudible Remark ]
>> Oh, good question.
So, I'm actually kind of cheating
in making this seem a lot easier than it is
because the numbers I'm printing are actually going up fro 0 to 1
to 2 to 3 to 100, they're getting bigger.
If we actually counted in the other direction,
you can see what would happen here.
Let me go back to progress 2, let me actually initialize this
to 100, let me go ahead and say this should do this while I is
greater than or equal to 0, and what do I wanna change this to?
Minus, minus, alright.
So, same idea just slightly different syntax.
Let me recompile this, let me rerun it,
and now I can't quite see it 'cause my cursor is there.
Let's-- let me rerun this again.
Let's actually, I'm gonna teach this
so you can see what's going on.
I'm gonna put a couple of spaces at the end
so that my green cursor is not overlapping.
So if I rerun this, now notice that--
oh and actually think-- oh I can't do that.
I just fixed the problem by adding those spaces.
Alright. So, we're gonna have to look
through my green cursor here to see this
in this particular program.
So notice what's happening.
That projector cooperates, that's a bug, right?
So the green cursor is just an artifact of the gooey program.
But I should not still have a percent there
but I do because why?
>> Because the number--
>> The number used to be 100.
Now, if we re-- and there was, that's a 0 previously there.
And so now we have a percent overriding part
of that big number, but now at all of it.
So if we let this actually go down monotonously down to 9, 8,
7, we'll see what also yet another percent sign.
So in short I kinda cheated here to make it seem easier
but we could fix this obviously
by just hitting the space bar or some other trick.
But by default the line is not erased, it only prints
out what you tell it to do.
Alright, why don't we go ahead here 'cause it's a lot
to digest, why don't we go ahead and take a 2 minute break,
I will let this countdown, play some music
and then we'll resume.
[ Pause ]
>> Alright, we are back.
So as promised, bug 3 percent signs was not the
desirable outcome.
Know that we could address this in a couple of ways.
One, there is the slightly hackish approach
where I just hit the space bar a few times.
But you can actually do better.
And just to plant a seed, know that just as with percent F
where you can specify how many numbers should follow the
decimal point, also with percent D you can do what's called
specifying the width of a number,
how many spaces it will take up even
if it doesn't need that many digits.
So long story short, know that with printf
for which there is documentation online that I'll pull
up in a moment, there are these additional format codes
and tricks so that you can tell printf,
make sure you're using it least this much space even
if you don't need it for the size of the number.
Yeah.
[ Inaudible Remark ]
>> And the F flush 2 is the other loose end here.
So in general when you call printf,
what's really happening is you're handing a bunch
of characters to the operating system and saying,
"Please print this to the screen."
However for efficiency reason, slightly historical reasons,
the operating system typically will not display those
characters on the screen
until it actually receives a backslash N as well.
The idea being years ago,
it's kind of expensive computationally
to print a character, print a character.
So the operating system wanted a way
and do a whole bunch of them at once.
Obviously, in this program I wanted to print
without using a backslash N so F flush which stands
for file flush, this just means it's a message
to the operating system saying, "Please, whatever I sent you,
just print it now, print it now, print it now."
In general, you don't need to do that because in almost all
of our examples we've actually used backslash N.
So this is a rare case but good to at least remember here.
So in terms of documentation, you'll see a couple
of things in the weeks to come.
First of all, know that built into Linux and built
into this command line environment is what's called man
pages, manual pages so that almost always if you wanna look
up some technical details, you can type something
like man printf for manual printf.
And what happens once you hit Enter is you get back a list
of instructions here
and actually this one is slightly a corner case.
Let me do this.
Man in chapter 3 of printf and notice what I get,
the Linux programmer's manual
and this is a little overwhelming frankly
at first glance which is why we'll show you a more user
friendly version in a moment.
But long story short, this documentation
which we'll come back to later in the term tells you one
under synopsis what header file you need to use this function.
It mentions related functions and this we won't get
to for a while and not even all of them but printf, F printf,
S printf, turns out there is a bunch of them.
But if you ever wanna know the precise definition
of something even if its way more information than you cared
to know, it's almost always in this so called man pages.
Now, when we want you to look at here in PDFs of the problems
as we'll generally tell you what to type man something,
something so that you don't know it need to go around guessing.
But know that in the meantime frankly,
the more user friendly thing to do is if you go to CS50.net
and click Resources, what you'll see on this page is a bunch
of recommended resources.
These are the free alternatives to the recommended textbooks
and typically based on the week, we'll expand different parts
to just draw your attention to things
that we think would be useful.
In this particular this one up here, See Reference.
Again, on the resources page, this is a fairly simple website
that actually has much more user friendly documentation
for a whole lot of functions.
Sometimes you have to kind of know what you're looking
for 'cause they're categorized here on the left hand side.
So I don't see printf immediately.
But I do know that printf now is related to input
and output otherwise known as IO.
So if I click on CIO, there's a whole laundry list
of functions we've never looked at.
And most of these we won't even bother because you don't need
to know all the functions to make good use
of a language but there is printf.
And if you scroll down here, okay,
anything that is bob is probably fairly user friendly.
And indeed this is slightly more accessible descriptions
of how it works.
Now, some of the syntax we haven't gotten through just yet.
But notice in this purple box it's telling us standard IO.h.
It's telling us that printf and we'll come back to this,
returns an int even though we're not using this
yet just like main.
And it takes a constant char format comma dot, dot dot.
So when in doubt, just kind of ignore for now the things
that you don't quite understand but look
for the examples in particular.
And down here you'll see a chart of all
of the available format codes.
We've talked about percent D, we've talked about percent F
but it turns out there is a whole bunch of others.
And generally only a few of these do you need but know
that this documentation, the CA reference
on CS50.net is a wonderful place to start when you have questions
as well as any of the books that you might be dabbling in.
>> So a few FYIs.
One, Scratch is officially behind is.
If you have scratch boards at any point this week,
just drop them with the TFs who tend to hang
out in the front of the lecture hall.
Lunch, you are all cordially invited to lunch this Friday
and in future Fridays, if this is of interest,
go to CS50.net RSVP sometime today.
Typically, we'll limit the number of seats to 20 or 30 just
so that it's a reasonably intimate opportunity to chat
with me, the TFs, the CAs
and we'll generally go somewhere near
in the square or in the house.
So this Friday will be 1:15 P.M, if of interest this URL
and we'll announce that in future weeks.
So definitely some of you kind of forgotten the section,
so what we thought we do is rather than turn the system off
at noon today, 5 P.M. So please if you forget the section,
at least get to the course's home page.
Click the link there to section before 5 P.M today.
Super sections, we filmed one last night.
Super section is a temporary word for sections open
to everyone, real sections will start next week.
The video from last night's appears online.
If you're like to go in person, they're today and tomorrow
at 6 P.M. The rooms will be announced shortly
on the courses home page once the scheduling folks let
us know.
The Walkthrough 1 was last night, that is online
on the problem sets page.
This is a walkthrough
of the problem set standard edition itself,
and now some fun facts.
You submitted problems at zero where we survey--
we ask a number of survey questions really to get sense
of demographics and also for just for fun sort
of geeky type things like what you have and what you use.
So it turns out that 33 percent of you this year have an iPhone,
17 percent a BlackBerry-- sorry, 17 percent an Android,
13 percent BlackBerry and 33 percent of you are normal
and just had sort of non smart phones and 3 percent have other
for some definition of other.
Just if curious, 39 percent of you have AT&T followed
by Verizon followed by T-Mobile.
No one is using Sprint anymore apparently
and then other is 4 percent.
In terms of the demographics, so as is typically the case,
sophomores are winning this year followed
by freshman, juniors and seniors.
Realize seniors, you're in very good company.
There is almost a hundred of you so let's do feel
like you're the oldest person in the room, you are not.
We have folks though from GSAS, HPS, extension school
and those local high schools so we have quite the diversity
of students this year.
I was a little disappointed to see
that Mather was nowhere close to number 1 this year.
But Adam's House has the most aspiring computer scientist.
[ Applause ]
>> Followed by Elliot House and then--
[ Noise ]
>> And then there's a lot of noise in there.
So my own Mather did not win this year.
Though in past years the data might have been artificially
inflated to make Mather win.
So laptops, most of you have, this is not surprising.
A few of you do indeed have desktops
but that's several hundred laptops floating
around on campus.
And then more technically interesting,
here is the distribution of OS's if you're curious.
And if you're thinking you're the only one still running
Vista, you're not.
There are a few of you.
[ Laughter ]
>> And so here is a rough sense of numbers, Windows 7 followed
by Mac OS 10.6 otherwise known as Snow Leopard.
So just realize this is the diversity of operating systems.
But when you aggregate it together, Macs are winning now
by 56 percent, Windows, 41, and Linux, 4 percent.
So more [inaudible] 50, let me send home this message.
So we were really thrilled to see this
in particular not only have we retained the same percentage
of more comfortable students,
those with prior programming backgrounds been programming
since you're 6 years old and the like.
But also for the first time, these segments
of those less comfortable is now the largest and also is larger
than last year's 46 percent.
So this is wonderful and we're so pleased to have all
of you 55 percent, 35 and 10 percents and it is now our vow
to keep you all on track and succeed by terms end,
in terms of experience too unless you do not believe what I
say, 54 percent of you have no, no prior programming
or computer science experience whatsoever,
41 percent [inaudible] and 5 percent said a lot.
So, a word now on psets 1 and onwards so--
oh, on, on the CS50 Appliance.
So in the interest of wording off some FHUs,
know that there is an increasing amount of documentation online,
these URLs are sighted both in the PDFs of pset 1 as well
as linked on all those pages.
But this is the reference page where for any in all questions
for installing the CS50 appliance,
know that this now links to this additional page
that has a whole lot
of troubleshooting tips essentially almost all
of the problems folks might have run
into with getting the appliance up
and running is documented there.
There are very common things that people run into on Macs
and PCs alike, so consult these URLs.
And then lastly, if you have a PC, generally that's
within a few years old.
Most PCs actually support something called Hardware
Virtualization
or Hardware-Assisted Virtualization
or VTX or similar.
These are just words saying that built
into modern CPUs is the ability
to run virtual machines particularly fast.
So some of you have found when installing the Appliance,
it's just downright unusable because it's so slow and that's
because some manufacturers turn this feature off by default.
So typically if you go to the Here, if you're a PC user
and you're just finding the Appliances just deathly slow,
something has gotta be wrong
because you got a 2 gigahertz computer, lots of RAM.
Any program should run well.
Go here, follow the instructions
and odds are you can enable this feature
at which point things just become much more pleasurable.
On Mac, this is a feature enabled automatically
by the default.
So this is only for Windows and Linux folks.
Regarding grades now, as you might have seen
on the second page of the pset
and this will recur throughout the term,
50 grades problem sets fairly coarsely and its qualitatively
as possible whereby the TFs will really prioritize providing you
with hand written or typed qualitative feed pack focusing
less on plus 1 minus 1 and the like.
In fact, the 4 axis that we focused
on when evaluating work is one scope whereby we mean just,
did you do the pset or did you cut a lot of corners?
Did you do half of it or the like,
how much of it did you actually bite off correctness.
Does it do what it's supposed to do?
Or, do you have 3 percent signs appearing in your program?
Or, are there other bugs correctness.
Design is harder to define
and it's something you'll get better at overtime.
It's how well is your program design?
Do you have loops and conditions that are nested
like 10 layers deep such that the wrapping on the screen
and you could have just done something simpler?
Or, is it nice and compact and elegant?
And again, this is a message we'll send recurringly
throughout the term that you'll get better at.
But design against [inaudible] not just does it work,
but how well was it implemented.
And that's where the qualitative feedback comes into play.
And style frankly is one of the easiest things
to get right 'cause all you have to do is mimic the style
of code you see in sections and lectures, the CS50 style guide
which is mentioned in pset 1.
Style refers to the simple things like,
did you include comments in your code that tell you
and the reader what you're doing?
Did you indent your lines of code properly?
Did you give variables nice names?
And this is always the access
where people just throw away possible points frankly
because it's sort of the last thing you think about
and so you just don't worry
about hitting the spacebar properly, honestly.
Not only is it good style, it also helps you chase down bugs.
The worse thing to do is if your code is a big jumble
of indentation and you're like, "Ugh, I'll fix that later."
It's best to do it now because if you keep things nicely
and anally indented like I try to do in class,
you'll actually be able to spot potential bugs
and logical errors more easily.
So do try to get into that habit.
In terms of how we evaluate, it's really very course buckets
where 1 is poor, 5 is best.
So early on in the semester, the target range
for most students know is in the range of 2s, 3s, maybe some 4s,
generally not so much 5s but know that 3 is indeed good.
It does not translate a 3 out of 5, that's 60 percent, oh my god,
I got a D on the first pset.
3 is good and the course has this abstraction between letter,
grades and numbers because again,
we do focus very much on the qualitative.
So if I may, I have to put on a scary voice for just a moment.
The course goes to great length in the syllabus.
And on page 2 of every problem set to emphasize the rules
on academic honesty which frankly essentially reduce
to your welcome and you're encouraged to talk
about problem sets, go up at white boards with friends,
discuss things in the D-holes and the like.
So long as those conversations are in pseudo code
or in English, and so long as they stop at the point
of actually communicating in code.
The line is crossed when the conversation becomes, "Oh,
can you send me your file?"
or "Can I see what's on your screen?"
When the line is crossed again, when code,
the actual code is involved.
And again, just to send this message home
and it gives us no pleasure
to cite these statistics every year.
[ Pause ]
>> So this is a slide I keep updating every year
and it is the number of students this course alone has add
boarded in the past 4 years, and it gives us no pleasure
to give people mandatory time off from the college.
But realize it happens, but realize it happens only
in this egregious cases
where again the conversations have evolved into,
"Oh my god, its 2 A.M."
Just send me your code and I will submit that.
Or it's over sharing or it clearly you're sitting side
by side typing up the same thing.
Again, it's very easy to navigate these waters
and pedagogically by all means converse with classmates,
white boards, dining halls and the like.
But again the line is crossed per the syllabus
and the fine print in each project
when code is actually shared visually or electronically.
Okay, non-scary voice.
Typecasting, so typecasting, is this notion that we saw earlier
of converting one type to another,
but it's actually more useful than just these simple things
of [inaudible] and the like because one
of the domains we'll be focusing
on this week is that of cryptography.
And for those slightly familiar, what is cryptography in English?
[ Inaudible Answer ]
>> Coding, yeah.
So it's the art of encrypting or scrambling information, right?
So back in grade school if you wanted
to pass your crush a secret note and you want to hide it
from the teacher, you might say like some message
but then you might rotate all of the letters
by some number of places.
>> So if you wanted to stay in the letter A, B,
C to your crush, you would say B, C, D or something simple
like that but enough sufficiently complex
that when the teacher grabs the piece of paper from you
and intercepts it, it's not clear what it is unless he
or she actually tries
to decipher the actual encryption you were using
back then.
Now, thankfully fast forward to modern day,
you can do much more sophisticated things
and encryption is something we take for granted.
Anytime you buy something online, every time you log
in to Facebook using https and word of Firesheep and all
of your friends trying to hijack your accounts,
you are using encryption.
Even things like the 33 percent of you with iPhones
and 17 percent with Androids.
Typically, the iPhone these days is automatically encrypted
with a secret key.
And so if your phone is ever lost and you enable
that feature called remote wipe where you can send the message
to Apple and they can send the message to your phone
that says Delete It, all the phone is doing these days is
just forgetting that secret key.
And without that key, all it looks like is random zeros
and ones to the bad guy that just stole your phone.
So there is a lot of applications just
to very useful consumer things and we'll introduce this week
and in problem set 2, this arts of cryptography.
And it pertains to a little something called typecasting
in this case.
I'm gonna go ahead and open
up ASCII.c. Another example that's been prepared here
that apparently does this.
We got a loop at the top, a for loop,
and we got some printf then another for loop.
And notice inside of each loop, this is just
for demonstration purposes, I've hard coded the number 65 and 26.
Well, 26 is probably the English alphabet.
What was 65 if you recall from last week?
[ Inaudible Answer ]
>> Yeah, so capital A. So this is just a simple little
diagnostic program I wrote
to show me what the number equivalent is of every character
on my keyboard, at least the alphabetical characters.
So I seem to have a loop that is starting at 65, it's not zero
but it's totally legit to start somewhere else it makes more
sense, I'm iterating up to 65 plus 26
so that'll give me all the way to Z hopefully, I plus plus.
And now notice what's happening here.
I'm printing out percent C
which is a character then a colon then percent D,
and what am I plugging in?
Well, notice I'm plugging an I both times
but the very first time I am "casting it" to a char
because I wanna actually see I not as the number it is
but as the char, the character it represents
so I might see A 65, B 66 and so forth
and then take a guess here, 97 represents what?
[ Inaudible Answer ]
>> Lower case A, so let's see this in action.
So let me make this a little bigger.
This is again called ASCII 1 and ASCII again is just the acronym
that denotes the code use to map letters, to numbers
and vice versa so make ASCII 1, everything compiled okay.
Let me go and run ASCII and indeed,
it's a little long of a list.
But if I scroll all the way back up,
that's exactly what I had promised.
So we can now see this conversion here.
Now what's the relevance?
Well again, think back to grade school if you ever did send one
of this silly notes, well you had it rotate or convert letters
to some other letters, well, how did you really do that?
Well you shifted them one, A becomes B, B becomes C,
but how do you express that if you want a computer
to do it not-- and do it way more sophisticatedly
than a small kid could, well,
you probably wanna convert the letter like A
to a number then do your math like plus one
and then covert it back to a letter
where we already have that capability here.
Let me go ahead and open up a variance of this.
If I go and open up ASCII 2, we'll see this.
In ASCII two, I'm doing something a little prettier
'cause they've got a little overwhelming
to have it all display on the screen.
So again, just to mention that format code I mentioned earlier,
present 3D means no matter what put three--
use three characters here to represent the number
and just prepend it with white space,
just the spacebar character automatically.
So what is this gonna do?
Well this is just a different aesthetic, I'm gonna go ahead
and make ASCII 2, the code is almost exactly the same
and then I'm gonna run ASCII 2, and what happens?
Well now I just got a chart.
So again fairly simple, esthetic modification
but its a little more user friendly now,
but I wanted everything to line up so notice again, percent C,
percent D but notice on the right hand side,
I actually said percent 3D.
Why did I use 3D?
Do you think for the third column and not for the first?
[ Inaudible Answer ]
>> Okay, I couldn't make any of that up.
But yes, so I was probably correct, right?
It's because the numbers
in the third column there actually are three
digits potentially.
Yes you start at 97, 98,
99 but then you get three digit numbers,
but for the capital letters, it was all single digit's
so I could have said percent 2D
but it wasn't necessary 'cause I know they're all gonna be two
digit's, but that's all.
So we're just now massaging the output aesthetically
by using this desperate format codes.
Well, let see if we can do something a little more
interesting than just printout this letters.
So this is not a complete implementation
but it is a demonstration of a game
that you might recall known as Battleship.
So Battleship, remember, actually even
if that sounds cool,
you're gonna be very underwhelmed in a second.
So if I make Battleship and then run Battleship,
that's all you're getting today.
So we have the layout of a battleship board.
This is that like little game
with the plastic board that's got all the holes,
you put the pegs in and a little fake ships and you say,
"A2" and you sank your battleship,
that kind of game, feeling familiar.
If-- yeah, [laughs] so, it's really--
I sound stupid, I sounded saying that.
So with Battleship, we have this opportunity though
to format this output in a little interesting way, right?
I clearly want a grid of some sort and I also need
to be careful with like the number 10 'cause all
of a sudden my grade could get screwed up because all
of a sudden I have a two digit number.
So just to see how we did this, let's scroll
up to the code here, it's starting to look more complex
but it's just a repetition
of this same constructs from before.
So I'm first gonna print the top row of numbers.
So I printout back slash N space, space,
space and I just figured that out honestly by trial and error.
I want a little white space and then I want
to indent the board a little bit.
What do I do next?
I wanna print one through ten and so here I have percent D,
again and again and notice a couple of white spaces
after each for esthetic.
So that's actually pretty straight forward but now here,
notice we have our first example
of a nested loop whereby have an outer loop
where convention says use I as your counter.
So I is zero, go up to 10, I plus plus,
notice now, what do I wanna do?
What am I doing here?
Percent C, so remember the output
of the screen did this for me.
I had all the letters of the alphabet on the left hand side,
well, what am I doing then with this percent C?
That's how I'm getting every letter of the alphabet.
Let me scroll this back here.
Why am I doing A plus I?
This feels a little weird.
Yeah.
[ Inaudible Remark ]
>> Yeah, exactly.
I wanna change the letter I'm printing on each iteration
by adding one to it again and again.
So A, I know is gonna be represented
by some number, it happens to be 65.
It turns out that even though in the previous ASCII examples,
I was explicitly casting.
You actually don't need to explicitly cast C
in the compiler or smart enough to know
that a char is an int and an int is a char.
At the end of the day, the only difference is how you interpret
those zeros and ones.
Now how am I gonna interpret the zeros and ones here?
Well printf is gonna print the character.
So it doesn't matter if I past in a char specifically
or an int, it's going to be displayed as the character
so I can now use the short hand notation of start
with the letter A, capital A, whatever that is plus I to it
which initially is gonna be zero.
So what's A plus zero?
It's just A 'cause at 65 plus zero is 65 and it's printed
as a char so it's A, but on the next iteration,
I is 1 and then 2 and then 3, dot, dot, dot,
25 and so in this way, can I increment even letters
of the alphabet from A to Z. Now notice this in--
nested loop so to speak.
Nested in the sense that it's indented in inside
of the outer most curly braces, so J gets 1,
J is less than 10, what is this doing?
This is just printing out zero, zero, zero, zero, zero.
So what's really going on here?
This is actually a very common example
of using 2 nested for loops.
If you want to printout rows and columns,
you essentially need two loops, generally for loops
by convention and so the outer most loop is doing what?
Iterating from right to left or top to bottom?
>> Top to bottom.
>> So it's actually doing top to bottom.
So the outer most loop involving I is top to bottom
and the inner most loop is doing the columns.
And you can infer this again
because if I'm printing the holes
by using this lower case O, that's happening inside the loop
and this make sense because if this thing is like a typewriter,
you better start from the top and go right, right, right,
right because the moment you go down, that's it.
You can't go back and add anything to the previous line
as we discuss earlier with backslash N.
So the outer most loop I is essentially gonna iterate
over our rows but on each iteration of a row,
we wanna go dot, dot, dot, dot, dot from left to right
to generate all of these zeros.
Now this is not by means of full-fledged game,
it's just the esthetics of the board
and the very last line is just to printout some blank space
but it does demonstrate now how we can nest these kinds
of things.
So perhaps a little more familiar--
a little more familiar is this example here.
So you might recall this incredibly annoying song
from great schools as well or school bus rides.
So 99 bottles of beer on the wall, 99 bottles of beer,
take one down, pass it around, 99 bottles of beer on the wall.
I also thought stupid saying that.
But there is the song that you might remember saying is
from childhood.
What's nice for our purposes today is
that it's obviously very cyclical which contributes
to it's annoyance but it's also an opportunity
to decrement this number again and again
and again while still doing a lot
of the same thing at the same time.
>> So let's see how this might be implemented at the end.
If I make beer1 and zoom in on this and hit Enter
and then type beer1, it's gonna prompt me for a number,
I'll say, "99" Enter,
it's pretty fast implementation of the song, right?
We can make it really tedious by inserting--
[ Laughter ]
>> We can make it really tedious by inserting SLIP
or something like that.
But if I scroll up, I have indeed started all the way
up at the top 99 and counted it all of way down.
So let's just see one way in which we can do this.
So let me zoom in on my code, the very top says,
"How many bottles of beer will there be?"
and then I use get Ns.
So this is kind of old hat now, now here's a common convention.
If the user does not cooperate, you could pass
through them again and again
but I decided just a design decision,
if the users not cooperating, I'm not just gonna quit.
And if you wanna quit a program and see, you return a value
from main and you should return anything, except what?
>> Zero.
>> Zero, right, so zero generally means success
and that should be returned by default at the end
or if explicitly by you, if all went well,
but if something did not go well
like the user was just not cooperating,
you should probably return something other than zero
and the convention is at least return one
of if you wanna really have fine [inaudible] in control
to return one for the first possible error,
two for the next, three for the next
but anything other than zero.
Now if I don't return, I keep executing.
So if the user did give me a positive number,
I start singing this song, and how might I do this?
Well notice how we might structure this with the loop.
So I'm first gonna just printout a new line,
then I'm gonna iterate from I equals N down to zero,
so we did this before with our progress bar
and I'm gonna printout percent D bottles of beer on the wall I,
percent bottles of beer a beer, I, take one down pass it around,
that's just the same thing and I'll notice here,
here's how I go from 99 to 98, then the loop repeats,
then the loop repeats, dot, dot, dot.
But this is far from perfect.
Where are some opportunities for improvement here would you say?
Yeah.
[ Inaudible Answer ]
>> Yeah, this is really me cutting more corners, right?
This is me avoiding the issue
that at some point this program is gonna get down all the way
to the bottom and say one bottles of beer on the wall
and I didn't wanna look like I'd made a bug
so I just parenthesize the S for 98 other conditions just to say,
"Now, I'm handling both scenarios."
But clearly, we can do this better.
We could have some kind of the condition inside of this loop
and say if I equals equals one printed
as bottle otherwise printed as bottles, what else could we do?
[ Inaudible Answer ]
>> What's that?
[ Inaudible Answer ]
>> Okay, so we could have the loop, just go down to one
and then special case as we'll see the last chunk of this song
and just printout verbatim one bottle of beer on the wall
or zero whatever the lower case is that you might wanna include.
Any other thoughts?
[ Inaudible Remark ]
>> So you could even be a little more efficient than instead
of conditionally spitting out one sentence or the other,
you could just special case the S, printout the singular
and then just printout the yes optionally yes or no.
So if I go back in here, let's see.
Beer1, the biggest number we can represent
with int is roughly 2 billion-- oh, dammit [laughs], alright?
That's a command line arguments more on that next time.
1, 2, 3, 4, 5, 6, 7, 8, 9-- alright.
Why don't we leave it there and we'll see you on Wednesday.
[ Noise ]