>> Welcome to CS50 this is the start of week two
and I actually got an email just this weekend from one
of our own TFs who had been here at last week's lectures
when we talked about some of these more arcane topics,
namely one called typecasting which we'll look
at in more technical detail today,
but his email started as follows.
Hi David, you introduced the concept of typecast,
recall call this as converting a char to an int or an int
to a char, last week, and exemplified the importance
of understanding the types of operators.
In case you want to insist on this point one day,
here's a video of an event that changed my life.
I was 14 years old watching this on live TV so what you're
about to see is a video of ARIAN 5, Flight 501.
This was a European rocket, there were no humans
on board this rocket but at the risk of pulling up YouTube
in class again, let me go ahead
and show you exactly what this teaching fellow is referring to.
[ background noise ]
So there weren't, to be clear, any humans on board
but the explanation for this explosion, which wasn't all
that many years ago, was this.
Because of a different flight path, a data conversion
from a 64 bit floating point value
to a 16 bit signed integer value caused a hardware exception.
More specifically an arithmetic overflow
as the floating point number had a value too large
to be represented by a 16 bit signed integer.
As it was an unmanned flight there were no victims
but the breakup caused the loss
of four cluster mission space craft, resulting in a loss
of more than US $370 million because of one line of code.
So if you find yourselves getting hung up on some
of the esoteric nature of some
of the lower level syntax realize
that these are just building blocks.
They're doing far more interesting things and certainly
when you're actually coding real applications far more important
applications do arise.
So I asked this teaching fellow if he could elaborate on,
you know, why was this actually changed your life?
And he responded, I think that at first I was fascinated
by space and I wanted to engineer rockets and satellites.
To me computers and programs were amazing but a toy.
While the conquest of space was serious stuff.
Progressively however as I was studying engineering
and sciences in high school and then college the memory
of this event helped me realize that software engineering
and computer science were much more noble then I
initially thought.
I think the reasons were three.
One, software is useful enough so that some of it was
in this rocket sent into space.
Two, it is critical enough that a malfunction result
in the rocket exploding and three,
writing software is actually such a craft
that even these rocket engineers from all
around Europe could get it wrong.
It made software engineering
and computer science a whole lot more valuable to my eyes.
He wasn't the only one so we've linked to the Wikipedia article
that discusses the real in depth history of this particular story
but one or part of the article concludes as follows.
Flight 501's high profile disaster brought the high risk
associated with complex computing systems
to the attention of the general public, politicians
and executives resulting in an increased support for research
in ensuring the reliability of safety critical systems
so we appreciate, if nothing else,
as you dive into your own problem sets.
One this week and into future problem sets
that even these small bugs absolutely can recur
in the real world and if you think about some
of the P-Set problems you're working on now,
your code might be this long or this long, a few dozen lines,
maybe 100 at some point very soon,
but if you're finding yourself having a bug with this line
of code, imagine what happens
when you literally have their implement rocket ships
and operating system which are millions of lines of code long.
So thankfully there are tools and there are other languages.
And one of the goals of this course is to introduce you
to progressively better and better approaches to design,
to style, to correctness and so
by semesters end it won't necessarily feel
like you're struggling with these if conditions and loops
so much, you'll actually be thinking the much bigger picture
and that will happen quite soon.
What some of you might have seen as you came
in today is a little something called ASCIImation.
This is free time to the extreme.
This is someone having taken this idea
of ASCII using ASCII characters to actually represent,
not just pictures but an actual movie
so this is his interpretation of the original Star Wars movie.
I bring this up only because in problems that won for problems
that won, well you dabble a little bit in this idea
of ASCII art but realize that as the semester progresses we'll
very soon have more expressive graphical capabilities.
I thought, and speaking of, what you'll find if you haven't poked
around recently on the course's website is you.
So we took all of your answers to Problem Set 0 where one
of the demographic questions, where is your home town,
recall we didn't ask for your home address, just your city,
state and country And what we did was,
we used an off-the-shelf API.
Application Programming interfaces, it's called.
The students last year in fact used this for one
of the tail end problem sets in the course
and we embedded a Google map in the courses website
and then we proceeded to represent each and one
of you with a little marker.
The projector in here is making this a little darker
than it actually is on a real computer but if we zoom
in down here we might see that Dapo is from Lagos, Nigeria.
And if we click on any number of our other folks here,
is he here now, you will see where each and every one
of the 500 of you are from.
So with that said, where are we going?
So we're going to lunch this Friday.
Not all of us but one of the traditions we've started
in this course because its fairly large, is,
on a semi-weekly basis to get to know some
of the teaching fellows, the course assistance,
myself and so we have CS50 lunches.
Either in one of the dining halls or somewhere in the square
and we generally do this by RSVP first come first serve
and its really just an opportunity for 20,30 40 of us
to head somewhere and grab a bite together
so that the form is not on line yet but starting tonight
if you are free this Friday at 1:15ish p.m. which is otherwise
when lecture would be if we still had it on Fridays.
Go to cs50.net/rsvp and think of this as just an opportunity
to chat us up, ask about the course, talk about whatever,
and its sort of very low key and edible office hours.
So we'll do that on occasion if you are interested.
So problems Set 1 is now out.
if you haven't dived in yet that's totally fine.
I take great thought, I have great fondness for those
who do dive in at 7:01 PM on Friday nights much
like myself back in the day.
But just a couple of comments on this.
So last week got very arc and quickly.
For those of you without prior programming backgrounds all
of a sudden we had this blinking prompt and a black
and white terminal and I was banging out code fairly rapidly
and was fairly out of context most likely for all of you.
so realize, if you walked out of last week thinking, wow,
scratch just got harder, well realize once you actually sit
down with this week's pdf and walk yourself
through the check boxes, well you find
that it actually all very quite accessible and you get familiar
with the new interface soon, we'll see different interfaces
over time and so let me make and emphatic point here too.
Especially as you do this P-Set,
if you are finding yourself a bit overwhelmed
or if you're just feeling like there's a disconnect
between what you heard in lecture
and what your expected to do, talk to us.
Talk to me, drop me a not, attend office hours,
there are any number of resources and at the end
of the day, please, if you're on that point thinking, damn,
I really should not have signed that study card with this course
on it, at least have a conversation with me.
I would love to be your barrier
between exiting the course altogether and just kind
of sneaking away thinking this isn't for you.
we can make it work for you.
so what is this P-Set all about?
well there's essentially three noteworthy parts in each
of the addition and in the standard addition you are
introduced to the candy machine that is free in the lounge
in Maxwell Dworkin which you are welcome to start frequenting.
We'll occasionally hold some office hours there and hang out
but the challenge here is really just to get your hands dirty
with Linux and with C. And what you'll find in,
even though the problem is relatively simple in concept,
we challenge you to implement a program that allows you,
the human, to guess how many Skittles are in a candy machine.
You simulate this candy machine using some pseudo-random numbers
and we walk you through the process
of generating pseudo-random numbers in a computers memory
and then ultimately you, the human, gets to interact
with your own program and for those of you
who have prior backgrounds you'll realize this is really
just a warm up exercise if nothing else
to get you acquainted with the new environment, the cloud,
with the new language, C. but then do the problems
to become a little more sophisticated.
so for instance, the next question asks you to take
on the role of a cashier.
So it turns out that in the United States and in Europe
and in other countries the currency systems are designed
in such a way that very naively can a cashier at a store,
if they have 20s and 10s and 5s
or the similarly labeled quarters, nickels and dimes,
if they're all in sorted order
that cashier can very mindlessly hand people change
by just starting with the biggest denomination
in the drawer and working his or her way on down,
handing the person the amount of change they're due
and this is an algorithms that's just generally thought
of as greedy.
In other words if you literally take the biggest bill possible,
a 20 but if you owe them say 30 buck you obviously don't want
to take another 20.
you then take a slightly smaller bite but a big one, a ten.
Do you ultimately hand that human being the fewest number
of bills or the fewest number of coins.
So what's nice is when greedy algorithms
which are generally easy conceptually and to implement
and to execute what's really nicest is
when they're also optimal.
But as you'll see in a moment for the hacker version
of this problem set we throw a wrench into the works
and you don't necessarily have all of the bills
and coins that you need.
So in this program here you are asked,
you implement its program, that has to figure
out how many quarters, how many dimes, how many nickels
and how many pennies to hand someone given a finite amount
of change and its going to reduce some
of those basic building blocks from scratch.
So some if conditions, some subtraction,
maybe some variables but this too will get you familiar
with this new environment and this new language
and then we thought we'd try to get trendy and so we pulled up,
isawyouharvard.com, the final project from CS50 last year,
and we thought, wow, this is perfect.
This is a graph, this happens to represent who is spotting whom
on campus based on the data she's collected,
and its really nice and really simple bar graph
that we can plot so we're not going
to actually use the same API that Tej is using, which happens
to come from Google, it too is free,
just like the maps we looked at a moment ago
but we can simulate this using ASCII art.
Using characters on the keyboard to give a decent approximation
of what a bar graph is and so here will you be asked
to ask the user for the number of people spotting whom,
based on gender and then you'll plot this graph horizontally
and this is clearly going to involve some kind
of looping structure, some conditions, maybe a bit of math
because we specified too how big the users screen is going to be
so you're going to have to figure
out the proportions accordingly.
Now for those of you who decide to tackle the hacker addition
of this P-Set and realized this is generally the minority
of the students in the class.
Anyone is comfortable, less comfortable more comfortable
like is welcome to do this.
It doesn't matter what you declared yourself as,
you can decide week to week.
We have the same warm up exercise involving some candy
for you but then we hand you credit card numbers.
So in the second portion
of the hacker addition are you handed a definition
of what it means to be a credit card number.
It turns out these things have patterns
and there are algorithms,
procedures with which you can verify
if credit card number is legit or not.
And so in this part
of the problem set you implement a validity checker
for credit cards to actually ascertain yes or no,
this is a credit card or this is just some random sequence
of numbers that someone is trying to use to pay
for something on the phone.
Toward the tail end
of the hacker addition do you implement the same idea
of graphing with some ASCII art this chart
but this chart we compel you to rotate it 90 degrees.
You actually have to make a vertical bar chart which,
if you think about how you would implement this in screen,
thus far we've only seen PrinTif.
Of printing to the screen and PrinTif's gotcha is
that it pretty much prints line by line by line
which lends itself to horizontal bars.
Print a row, print a row.
But if now these bars are stacked up high you're going
to have to be a little more clever when it comes
to figuring out, when do you draw this bar versus this bar
and that will be the hacker addition this week.
So those pdfs are on line and just FYI, if you were one
of those like me who downloaded the pdf for hacker
at 7:01 PM do redown load it because I screwed
up in the middle of the night
and I made the bars the wrong shape in the sample output
so grab the latest pdf.
So what exists in the way of support?
So we've echoed this multiple times.
Helpatcs50.net is manned by the CS 50 staff
and our response time tend to be remarkably fast.
But in the interest of economies of scale,
what we also released this weekend is the courses
discussion forms or bulletin boards.
There is certainly redundancy in the types of questions we get
because there are absolutely some frequently asked questions
so on the course's home page now
on the left hand side will you find the link
to discussion aka help.cs50.net any time thenceforth you have a
question that you think probably someone else might have
and its not something that's particularly personal
or particularly unique to your own code, absolutely turn
to the bulletin board first for two reasons.
One, to check if someone else has asked the same question,
its nicely browzeable and searchable,
you can save yourself sometime, get an immediate response or,
two, post the question if you think it might benefit others
and we spell out in the main page
of the discussion forms exactly where that line is
between oversharing and asking the right kind of questions.
Posting a few lines of your code saying here I'm having trouble
figuring this out, that's probably fine,
saying here's my program, doesn't work, help, too much.
The idea is to actually engage us more privately
with such things hence the email address.
So let me for just one moment put on my scary voice now
that we're at the start of the semester.
So the course takes very seriously issues
of academic honesty.
It is very clearly spelled out in the courses syllabus
and for your convenience we include it on the second page
of every single problems set throughout the semester.
It explains as best we can where that line is
between collaborating and working and learning and working
with and learning from your classmates
which is absolutely encouraged and where that line is
between actually taking their ideas, taking their code
and then presenting it as your own.
as you'll see in the syllabus and do read this paragraph
if you haven't already, the line essentially boils
down to its absolutely okay to talk with your friends,
talk with people in your section,
stand up at a white board together,
sort of brainstorming ideas, writing things
down in pseudo code and tackling the problems conceptually
together but where we draw the line in the syllabus is,
don't go to the point of talking in exact C code.
Don't look at the person's screen
and certainly don't say hey do you mind sending me your code?
To be honest, almost every time there are instances
of academic dishonesty in this course its not
because it was this fine line between oversharing,
talking a little too much, it was 2 a.m. and someone decided
to copy the code from their friends computer,
their friend made the mistake of actually sending them their code
in poor judgment and its those kinds of issues,
so realize its absolutely the type of course
where it's a community, you're certainly encouraged to learn
from and work with each other but do mind that line
and in conclusion in scary voice,
I made a little animation.
[ background noise ]
So that is the number of people this course has add boarded
over the past several years.
recent years so this is perhaps more effective I can say
verbally so realize we are computer scientists.
Realize we retain the archives
of all past problem sets that are submitted.
Realize we have the capabilities
to cross check every problem set submitted
against every problem set submitted and we're very good
at what we do and it gives us no pleasure to escalate things
to the administrative board but we do it in fairness
to your classmates who are really giving it their all,
so late days exist for reason.
When you're at that point at 2 a.m.
when your feeling yourself stressed and you've got
so much going on in your life, honestly that's when you cash
in the late day, go to bed or worst case reach out to me
or Jan Sorukki and we'll work something out if you're feeling
that temptation that frequently happens with stress
and we have these mechanisms in place so you can avoid it.
so hello world was the first program that we began with,
I have to make this awkward transition now
to happy time again, so we began looking in quite detail
at first scratch and then see and it turns
out you can do a bunch of things in all sorts of languages
and just so that you've realized that the ideas we're talking
about now are absolutely applicable to other languages
and event the tail end of the same course,
what I thought I would do is just grab a couple of snippets
of code, and actually let me not take for granted this work flow.
So I'm on a Mac.
I decide its time to connect to the cloud.cs50.net so I open
on my Mac a program called terminal,
I can zoom in on my font size here,
I'm going to type the command as the problem set 1 walks you
through cloud.cs50.net, I'm going to hit enter,
type in my password and bam.
Now I'm connected from my Mac to the remote server.
For those of you with pc's realize the problems
that actually walks you through the same process, you will see
as the P-Set directs there are some how-tos which is sort
of geek speak for tutorials, user manuals or what not
for both terminal which I just used
and If your finding this a little too fast realize we took
nice screenshots and walked you through the exact same process
and sequence of steps here and just so you've seen it before,
the half of some of you with PCs realize
that putty is a free program
that you can download off the internet, it is an SSH client,
it looks a little different,
it doe have a more interesting guy graphical user interface,
but at the end of the day once you follow this sequence
of steps you end up seeing the same thing.
Font might look a little different
but the result is actually the same.
and those of you running Linux probably know how to do this
with your own computers anyway but let us know if not.
Yeah?
>> [inaudible]
>> Why did I tell them that?
Oh so why did I tell the Mac people
to change your font colors and background?
So when you read through this tutorial, we strongly suggest
that you configure terminal or configure PuTTy in a certain way
so they graphically things look the same in terms
of color coding, syntax highlighting,
so things look a little prettier.
You do that on your Mac but those setting then sort
of put a lens in front of the server
through which you look at your code.
So we just change the colors locally but the effect is
when you look at remote things, they too are different colors.
That's all.
Is it necessary?
No, if you prefer just looking at the more generic white screen
that certainly fine and even I, in lecture today am switching
to white for readability sake and its really to each his
or her own, its up to you, but the structure is there.
so I am on the cloud, I'm going to go ahead into source,
my source directory which you have print outs of today
and what I thought I'd do is open up, for instance this,
which might make some of you feel more at home.
So this is hi.java.
so stupid name for a program but this is a canonical program
in Java, some of you already know what this looks like,
if you've ever wondered what Java's source code looks like,
it looks like this.
There's a few different key, oh sorry, I didn't print this one
out because its so useless for moving forward.
No, not as a language, just as an example.
You'll see that the syntax kind of similar in spirit,
there's a mention of main, there's parenthesis,
there's semi colons, there's closed quotes
but there's some other jargon there.
there's the word class, there's some additional bracket syntax
here so just realize at the end
of the day this program too get compiled in a similar way.
Instead of running gcc, someone writing this program would run
Javachi.java and then what you would do is run Java
on this program hi and there is in fact the same program.
I think I have another one here in, let's say, hi.php, nope,
that's not it, okay so here's perhaps the simplest php program
you can write and we'll be using php toward the town
of the semester to actually implement things
like isawyouharvard.com or any web site based application you'd
like to make you can kind of infer how this thing works.
Echo, sounds like its pretty similar to print,
the n are familiar, the, are the same.
There's some new syntax there
with the open bracket and then the ?
but again the point of showing you these little teasers
of other languages is that once you have a solid foundation
in one language, maybe two languages or different types
of languages as might be covered in this course and follow
on courses, you can very easily bootstrap yourself
to other environment.
To be honest, I learned in 50, the language C,
I took CS51 the next semester
and learned the language called lisp and C++ at the time
and that was it for my formal introduction
to programming languages.
Every other language I've learned
since has been completely on my own and from friends
and from projects and the likes
so realize its very empowering just getting your foot
in that door.
Well what about this issue of imprecision?
So let me go ahead and whip up a program like, let me take a look
at this for one sec, let's do, yeah.
So I'm going to go ahead and create with nano,
imprecision.c this is not among your print outs
because we're doing it in real time, first thing I'm going
to start off with is include standardio.h
and what's the point of that?
Quick sanity check?
It will give me PrinTif so I can actually interact
with standard input the keyboard and output the screen such as
through printf, I'm going to say int
and we'll explain eventually why you say int, main,
I'm going to say void because main
at the moment does not take any arguments
but we'll soon peel back that layer and I'm going
to get myself ready to start coding
by putting the curly braces there in advance.
So now I'm going to do a couple of things.
I'm going to say float, to get a floating point variable,
x gets let's say .088 which just so happens
to be a floating point value one
of your classmates mentioned before class
when we were chatting so it's a perfect example,
we'll go with that one.
Let's say float y= and I have a .01 and now float z is going
to equal X plus y. so now to the astute, the mathematicians
in the room, this value of z is now .89, at least it should be.
Now let's make this more relatable to the actual piece
at hand, this is like change so one of the problems
in that problem set is again change making
where you have quarters which might be .25,
dimes which might be .10, pennies which might be .01
so surely there's an application already
for floating point values so suppose I'm trying
to add 88 cents and 1 cent here to get 89 cents
and then display this value.
Well let's do that.
Let's do PrinTif % f for the floating point format string
if you don't remember these as an aside one
of the best resources early on if we don't mention things
in the problems set at hand if you go under C
in the resources page of the courses web site one
of the best references here is this thing called c reference
and all you have on the left hand side are links
to the categories of functions that come built into C
so for instance if I'm dealing
with PrinTif you should probably know intuitively now it has
something to do with IO right?
because it standard IO so if I follow this link and then scroll
down I'll see a whole bunch of functions we've not looked at
yet and we're not going to bother looking at all of these,
you pick them up as you go but there in fact is printf.
So here is some nice documentation
with all the format codes for printf,
there's some example code on this website which is why we
like it so this should help get you going as well if you feel
that you didn't quite see the right approach
in say, some class.
So here we go percent F, let me do a new line F
so that things don't blend onto the multiple,
don't stay on the same line, ; let me go ahead and quit
with control X, Y for yes, enter for save and now
to compile this I've got a few options,
I'm going to start getting more efficient
and just say let make do it for me.
figure out all the flags, figure out the -o and all
that mess and hit enter.
And nothing bad seems to have happened,
which presumably means something good happened,
so now let's go ahead and run imprecision with .
/imprecision.
Okay. so that actually looks pretty good.
Answer looks right, I seem to have gotten some free zeros
at the end of it but remember from last time
that we can actually exercise a bit more discretion
when it comes to seeing the places after that decimal point
and I can do that by saying .and let me see 10 decimal places.
That was like 6 or 7 there, let me go a little farther
to the right and see what's really inside this variable Z,
I'm going to go ahead and hit control X Y and enter.
I'm back at the prompt and I'm going to rerun it and
yet I see the same thing.
Sanity check?
>> [inaudible]
>> You have to recompile, right.
Again, it's sort of a neophyte mistake,
you get used to it very soon.
Let's remake this with imprecision, enter.
I've recompiled my code, now if I rerun it
and we move the cursor to the top, enter.
Interesting.
So that was kind of a lie, so when we've said before
that computers only have a finite amount of memory
on this a finite amount of precision which is another way
of saying if you've only got a fixed number of bits,
surely you cannot represent with a fixed number of bits,
32 or 64 the infinite number of real or rational numbers
that exist in the world so there's got
to be some approximation going on and there you have it.
at 88 cents plus one cent you do not
in fact get 89 cents you get just shy of 89 cents
so again those of you who are fans of Office Space
or Superman 3 this is the kind of stuff
that they were literally referring to in that movie.
These rounding errors, you start to add all that up
after billions of transactions
and this is how these guys start to make some money.
So why is this relevant?
Well suppose I add to this program a little condition.
Again, just to hammer this home, if Z is equal to 0.89
because that's a reasonable check to make,
let me say printf and just say equal.
I'm just doing a little bit of diagnostic work here.
now I'm going to say, let's say else if Z is greater than 0.89,
let me go ahead and printf greater than .089 print greater
than backslash N else let's go ahead
and printf it should be obviously less.
I could say else if Z is less than but its redundant,
I can just say less because there's only three possible
scenarios here but I could, to be clear, say Z less than 0.89
and we'll get the same result.
So let's see what's actually going to print.
Let's save, quit, remake it, rerun it and in fact it's less.
so you'll see how to deal with this.
Well in the problems that we walk you through the process
of suggesting, well you know, if you've got floats,
and the problem is floats well why not work with cents,
why work with ints so we propose very simply
and this does actually work out to solve this particular problem
in this case, multiply those dollars, cents by 100
and what do you get back?
Well $1.99 becomes 199 pennies and if you round appropriately
as you'll see in the spec than it becomes 89
which is an actual int.
but therein lies the reason and this isn't quite the same bug,
certainly that resulted in the explosion of that rocket
but its this kind of idea,
not understanding what's really going on under the hood
and not understanding what the machine is doing for you
and writing one stupid line of code
and $300 million later, you've got a problem.
Now just to push back, in case you're thinking,
well this is ridiculous, I should come back
in 20 years once mankind's gotten better at providing me
with tools to avoid these problems and we have.
There are other languages, we get to them toward the tail end
of the semester, but again,
too many people don't understand these underlying implementation
issues and that's why we continue to have bugs
and security holes and more on that in just a bit.
So where did the first bug come from?
It was, as legend have it, a bug inside of a very old machine,
one of which you can actually see in the science center,
not the bug but the machine, that big Mach 1 computer,
take a look if you've never,
at the little touristy plaques that are on it.
its quite a part of this schools and computers history
but this is supposedly the first bug that was taped,
with some cellophane tape
by a computer scientist named Grace Hopper to a piece of paper
in her lab notes documenting why the computer had malfunctioned
that day.
These days bugs clearly has a different meaning but derived
from that spirit so let's see
if we can take a look at a bug ourselves.
I'm going to open up buggy1.c. This is the first
of the programs you do have a print out of,
so if you'd like to follow along at home there, go ahead
and take a look at this, take say, 30 seconds, 60 seconds
and decide for yourself and confirm with a partner what
in fact the bug is with this thing here.
Don't worry we won't do this every time you have a question.
[ Music ]
All right, so short program, if you didn't catch this it's okay.
You'll very quickly get better at spotting these things and one
of our roles at office hours is to glance at code like this is,
bam, unstick you and move you along your way, what's the bug?
>> [inaudible]
>> Where is it?
Hopefully alphabetically in the handouts.
Is it not there?
It should be.
Buggy1.c. Okay what's the bug?
Its supposed to print 10 stars but it does not
because it actually prints all right, it prints 11.
So this is again one of these newbie mistakes.
You get used to it too and I point this out again,
never to poke fun but because these are the kinds
of stupid little bugs you trip over at first,
you sink too much time into.
So once you get past some
of these frequently encountered bugs can you really start
focusing on the juicier problems.
So the problem here is that I started counting at zero
like a good computer scientist or a computer but I then went
up to and equal to 10.
So if you actually think through the iterations there,
because recall that in a 4 loop the initializations happen first
on the left, the condition gets checked, then something happens
and then the incrementation or the update happens that will,
in this case actually print 11 stars.
And so the fix could be a couple of things.
The quickest fix and perhaps the stylistically common fix is
to just do that.
When you're iterating from something to something you start
at zero and you go up to but less than that other value.
If you really want to be more consistent with sort
of normal human beings, we could absolutely count from 1
to 10 literally, but just realize
that probably shouldn't start this habit
because there are some lower, there's some other features
of programming languages, arrays being one of them
which we'll talk about this week but your just going to get
in trouble if you insist on counting
like normal human beings.
Start counting in this way.
So let's take a look at a second little example here.
Let's go ahead and look at buggy2
which should follow that one.
This one too is supposed to print 10 stars
but this time one per line because I whipped
out a backslash N but it does not.
So a little sanity check?
What's the bug here?
>> [inaudible]
>> Right. so another frequently encountered issue.
Even though you typed this code out so prettily,
you hit tab a couple times or the space bar
to nicely indent things.
It's very readable, seems consistent
with the CS50 style guide which is discussed in problem set 1.
Unfortunately the compiler only knows to execute one line
of code after a 4 loop unless you have encapsulated it
with curly braces like this and then one down here.
So this would be correct if I want to print a star
and then print a new line, print star new line, star new line.
But let's take a look at what actually happens if I go
with the original version, which is just this one.
So let me go ahead and make buggy2 and then let me go ahead
and run buggy 2 and in fact they're all on the same line
but if I go back into nano, scroll down
and obviously I could just fix it like this,
but demonstrating a little point here.
So I could just go in here, put that curly brace,
put this curly brace, save, quit, recompile,
rerun and there we go.
Stupid program one star though is now per line and let me point
out one thing too, because when we get questions a lot
of the time on help
at cs50.netinthelight very commonly we see code
that clearly won't compile because you've got a ;
over here, a parenthesis over here, and that's normal
because it's a lot of new syntax for a lot of folks
but I can't emphasize enough, before diving in
or before wondering wherein lies this problem, look back to some
of the examples from last week or even this week.
They're very short very deliberately
so that you can actually look at them,
get a sense of what correctly structured code is like,
look at this one and say, okay it starts with int,
main then open curly brace and just make sure you're mimicking
that kind of syntax and then you'll realize
that there is some logical sense to this kind of structure.
All right, so moving
on to something more interesting involving type casting
as that teaching fellow alluded to in his email to me.
so typecasting is just this process of taking one data type
like an int and casting it, converting it to a char
or vice versa, you can do this with a few different data types,
we've talked about char int like a letter A going to 65
or 65 going to the letter A. this will be useful
in applications of cryptography and other things
but you can even cast from a float to an int.
you can take 1.99 put parenthesis int in front of that
and that casts it to an actual int but what's the answer?
So it's just 1.
you throw away everything after the decimal point
which may be what you want, in fact as you'll see
in the standard edition of the problem set
for this week we tell you that if you ever do have
to round these bars when figuring out, sorry,
their width, go ahead and round
down so its not always 100 percent of the length,
we tell you to round down and if you need to round
down casting can do the trick but we're going
to see other data types before too long.
Certainly toward the tail end of the semester
when we're implementing more sophisticated programs we might
want to implement the notion of a course, right?
The Harvard courses web site of the CS50 app,
we clearly have inside our server's memory the notion
of a course.
The notion of an instructor.
The notion of a Q guide rating.
There's all these conceptual entities and yes,
we could represent all of those things with just numbers
and strings and the like but as we'll very soon see,
you can make your own data structures.
You can make your own data types so if you want
to actually represent the notion of a course
and a course has a name, a catalogue number and ...
some other stuff.
Well you can essentially join a whole bunch
of variables together, call them something new.
The course data type and then start manipulating that
but if you choose to do that,
typecasting doesn't mean you can take a course and cast it
to faculty member or vice versa, it has to actually make sense
so in this context of primitives where at the end
of the day its just bits, doesn't make sense some time
to cast one thing to another.
So let's take a look at ASCII1.c This too is among your printouts
toward the beginning, let me go ahead and scroll down here
and I've left the comments into this one,
just because it's a few more lines of code,
feel free to mark it up if you like,
but what does this actually do?
Well this is just to hammer home the point from week zero
and if you want to represent letters and sentences and words
on the screen, well it turns
out you can do this using just the underlying integer
representations but if you cast things
to a char you can very explicitly see that 65 is
in fact capital A. 66 is in fact capital B and so forth
and so what is this really going to do?
Well here we have a 4 loop,
certainly by the time you've dived into problems that one,
this kind of syntax will look more familiar,
even though we've started counting at zero before,
it's totally legit if I want to start at a fixed value like this
and iterate from 65 up to 65 +26.
Now arguably this is a bit of a cheat, I just didn't want
to do the math that late at night
so I just did the addition here because the computer can do it
but certainly we could add those together
in advance an probably save ourselves some cpu cycles.
What's going to happen here?
Well this line of printf prints a character followed
by A semicolon and a space and then one or more digits.
What am I putting in there?
Well I'm putting I both times.
I'm plugging I into both of those placeholders
but I'm first telling the compiler,
you know what, treat I as a char.
Treat it as a character so that what's printed is not 65;
5 but hopefully A;65 and as an aside,
it turns out its not strictly necessary to explicitly cast
or explicitly say, open (char) here.
I'm doing it really just to be deliberate and clear
but the compiler or printf is really smart enough to know
that its this thing over here
that dictates how those bits are rendered
and not necessarily this so realize that.
As for the bottom half here 97 happens to represent little a,
98 little b and so forth so there are charts
that show you what these mappings are
but now knowing 65 is big A 97 is little a we've got 52
letters, representations that we can figure out
and every other character on the keyboard has its own.
so let's run this.
MakeASCII1 seems to have compiled okay, let's go ahead
and run it and what do I get?
Well just get a big long chart showing me the
so called ASCII table so we've pretty much scratched the
surface of this verbally only but A is 65, B is 66, T is 84
and then sure enough, little a down here is 97.
all together this is a pretty unwieldy program.
If you spit out output like this its already annoying to me
that I have to scroll up just other see what the program told
me, so let's see if we can do a little better.
Let me go ahead and open the second version of this,
nanoASCII2 and scroll down
and notice I've done something a little differently here.
again just a little trick especially for something
like problem set 1 or future P-Sets where you want to start
to control the aesthetics of your program a little more,
not just dump stuff to the screen like printf makes
so easy, well here, same kind of iteration.
But what am I doing?
Well I'm printing out character, some white space digits,
some more white space and then the 3 D. What does this
denote here?
So 3 spaces so I figured this out, frankly by trial and error
or if I were more astute I'd sort of anticipated this
but once I get to the lower case letters, it starts at 97
and then 98, 99 it eventually becomes three digits so just
to be anal and aesthetically pretty I wanted to make sure
that all those numbers take up three columns of text
so that everything aligns nicely so I eventually went back in
and said, all right, make this 3 D and not just D
for reasons we'll see literally in a moment
and then we have another character, so what's over here?
well let me scroll over to the right,
since the lines a little long actually,
let me just scroll back, shrink the font a little bit,
so what do we have here?
the first place holder is going to get the character equivalent
of I, that's copy paste
from last time then literally I, copy paste.
Well here I just did some trickery.
I realized, you know what,
big A and little a they're always the same distance apart,
they're always 32 characters apart,
65 to 97 so let me just do this all at once, the current value
of I plus 32 will take me from the upper case
to the lower case range and lastly over here I'm casting
to a char the result of doing that same calculation,
I plus 32 so in the end, what do we have here?
ASCII 2, let's go ahead and run ASCII 2 so its not perfect
but my screen, my fonts.
My screen's a little small, my font's a little big
but now I feel like, okay
at least I'm now controlling this machine a bit more.
so maybe a little underwhelming in the context of today's guise
and what not but again the take away for now is control
and specifying to the machine what you want it to do for you.
any questions?
On this little ASCII exercise?
Yeah?
>> [inaudible]
>> Oh, good question.
And when in doubt we'll always try so let's scroll down here
and let me get rid of what I thought was a fairly clever
trick, let me save, quit, recompile, and now rerun
and so you know, its not that bad,
I'm being a little uptight here
but that's the problem I was trying to solve.
I wanted to make sure each of those numbers took
up three places and not just two potentially.
All right so one last variant of ASCII.
Let's scroll on down and realize
if you really have free time you can transform these very basic
primitives into the entirety of movies.
Well now notice two here,
this isn't necessarily the way you should do things,
but just to hammer home this point that at the end
of the day all we're doing is manipulating bits.
Zeros and ones and we happen to group those bits as bytes
like a char is one byte, recall,
an int is 4 bytes recall generally.
Turns out we can even iterate over characters just
to make all the more clear what, that there is this equivalent.
I can iterate from the character c starting at capital A,
I can do this as long as that's less than or equal to capital C
and then I can do this instrumentation,
again here I'm being very deliberate with all
of my parenthesisation the compiler does not need all
of these hints necessarily but notice let's start on the inside
of the parenthesis just like you would in grade school math,
focus on the deepest ones first.
So here's c, I cast it to a number and then I add 1,
because again the goal is to just start incrementing
on each iteration, then I don't want to print a number I want
to print a char so I cast c back to a char and then this line
of code is the same and at the end of the day, sure you want
to iterate and call it a character, that's fine,
its still just a byte, its still just a number underneath
the hood.
Well you might recall
from childhood a game called Battleship.
Now I can't do justice to this game
with my little command line programs yet but I can print
out the board thereof.
So when you start using interfaces where the user has
to now see data and isn't really tolerant
of just a blinking cursor and line after line of text.
We can absolutely begin
to implement what we would call graphical interfaces,
albeit in a command line environment so if you don't,
if you've never played this,
this is essentially a plastic board you get as a kid,
you've got numbers on the top, letters on the side
and you put these little ships inside these holes that I chose
to represent with the lower case zero there.
what's interesting about this particular exercise is just how
nicely formatted everything is and also there's some kind
of looping going on here and that certainly might be a trick
that proves handy in problem set 1, let's take a look
for a moment at battleship.c. it turns out to print all
that out there's not all that much going on but again,
there's some decisions I need to make at each point so I claim
with this comment up here that I'm first going
to print the top row of numbers.
Well first I print some white space so new line,
just because I want to move it down a line just
because it looked prettier to me, then indent three spaces.
Again, just to keep things pretty,
but then what am I doing?
It looks like I'm just printing 1, 2, 3, 4, 5, 6, 7, 8, 9,
10 on top of the little battleship board like we saw.
Well then what do I do after that?
Just a new line, so this white, the problem I've taken
out first, it just prints the row of numbers
and so this is again to echo the point from last week,
especially when you're diving into P-Set 1,
do not try to implement the entirely
of the Skittles problem, the entirety
of the change making problem, the entirety
of the I saw you program because inevitably you'll have one
or two or three bugs and you'll have to chase them
down altogether it just adds complexity and wastes time,
start by just implementing the numbers, save, compile, run,
looks good and now move on to the next part.
That next part is this.
Print the rows of holes represented by lower case o
and the letters in the left most column.
So I had to do some thinking here.
now I don't want to print one row, I've got to print one row
than another and then another and another
but in each row I kind of have to iterate this way so I have
to go this way and then this way so that's just looping
in two different directions so you can absolutely as you could
in scratch, loop using nested loops.
Using wild, do wild with 4 loops, I decided to go
with 4 here and as follows.
So 4 int I gets 0 up to 10
so this loop here is this controlling the cursors top
down movement or left right movement would you say?
so it is in fact top down.
Now why is that?
Well on each iteration
of the outer loop just conceptually you're probably
going to print as we've seen printf behave before,
one line at a time so to print this and this
and this that's got to happen on the inside
because the only one I've printed this and this
and this am I allowed to wrap around to the new line?
and that's the roll being played by this outer loop
so indeed this outer loop, I,
represents the rows not the columns per se.
now what am I doing here?
I'm printing out a character place holder followed
by literally a plus I so here I started to understand
that I know that this cast can happen and I don't have to be
so explicit any more and so this is going to print A
when I is zero, B when I is 1, C when I is 2
because you're just adding 65 plus that value.
Then what do I print next?
Well I just need to print 10 of these holes in the board
so I print a lower case o space, space to line things up
and then a new line eventually,
notice that its not inside the 4 loop its
at the end nor is this thing inside the 4 loop that's
at the end and the end result is to print this, this,
this and this but before you advance
to the next line you're going this, DDDD this DDDDDD
and so you get this looping structure
and this is very similar in spirit to a little something
that you might do for instance in say, a picture like this.
Why don't we go ahead and take a five minute break.
All right.
so we are back.
Let me verbally answer two frequently just asked questions.
So some of you noticed that all
of a sudden I started making main look a lot more complicated
than it used to be by including int, part,
C char, star, art B, bracket.
So the reason for this is that this week
when we start action teasing apart what a string actually is.
So far we've talked about a sting as being a word, hello,
a sentence or what not but it ultimately it's a sequence
of chars so it turns out that program like, that you write
that have main functions can take strings, can take words
as arguments themselves so this is a foreshadowing
of exactly the syntax that we're going to start using this week
and beyond, it's a little more sophisticated then just saying
void but it useful when you actually want to take input
from the user that moment they run the command.
Case in point, you've been running GCC or soon will,
you've been using nano or soon will,
those programs take what we've been calling command
line arguments.
Nanohello.c make hello.
So that word has to somehow be handed into your program
and the means by which you're going to empower you
to hand inputs, words, strings and the like.
Add the command line to your programs is by way
of these inputs to main.
The thing inside the parenthesis
but we'll come back to that before long.
As another FAQ I suddenly seem
to have stopped using double quotes
and instead using single quotes, the reason for this is, again,
it reduces to an issue of types.
When I'm using double quotes as an argument as an input
to PrinTif so that is a string, what we've been calling it.
a string, recall from last week is just a sequence of chars,
a sequence of characters.
When you have just one character and you want to be sure
that that one character is in fact being represented
with just 8 bits, a single byte,
must you use single quotes around it.
if you don't as we'll see next week and perhaps this Wednesday,
if you don't that's A,
if you use double quotes it will actually be treated as a string
or really a one character word, a one character sentence
and that has implications for how much memory is being used
and also for potentially the security
of the information being stored there.
>> [inaudible]
>> Ah, good question.
When you are printing backslash N can you use single quotes?
No this needs to go inside of double quotes
so I have been very particular in using my double quotes
and single quotes and pretty much you should,
just a safe generalization?
Almost always use double quotes unless you know what you want
to print is and individual char and you've hard coded it
into that program as such.
All right.
so a little bit of a familiar if annoying song.
So I needed something that had a lot of simplicity in it,
just repeats ad nauseum and something ideally
that starts counting downwards
so you have this song the kids used to sing on the school bus
for instance and what's interesting
that there's a couple of changes that happen over time
with each annoying verse of this song, the 99 becomes 98,
the 98 becomes 97 and you count down to one or zero or whatever.
But notice too inside of each verse there is a change
in let's call it I itself and it doesn't happen on every loop,
it actually happens inside the verse itself and then
if I really want to be anal, this last line when I say,
something bottles of beer on the wall, when I get down to one,
I probably want to fix the English
so that it just says one bottle of beer on the wall so it seems
like there's an opportunity for a condition
and if else there even though its only useful
at the very tail end of that program.
So let's go ahead and open
up a little program called beer1.c first incarnation
of this.
I'm again using cs50's library and what's going
on here in this program?
So the first thing I've decided
to do is ask the user for a number.
All right, how do I do that?
Well I literally use printf an ask them for a number
and then I use getin from cs50's library and recall
that get int is a function and a function is kind
of this black box that might take input, it doesn't have to
but might take input and might return output and if it does
in fact return output that you care
about you better do something with it
and in this case you better store that return value,
that output in a variable end so we can use it later.
Now here's what we'll start calling error checking
or rigorous error checking
and they won't necessarily see it specified pedantically
in every problem set, check for this, check for that,
make sure the user can't do this.
This should become natural before long.
If you're writing a program that takes and form
of user input it is ultimately and should be up to you
to make sure that that users input cannot
in any way break you're program.
Its not an excuse to say, oh,
well they shouldn't have inputted in a negative number
and a case in point, not to over emphasize that explosion
of that rocket ship you make assumptions
and bad things eventually happen, especially when lots
of people and lots of users become involved.
So I'm doing a sanity check here.
if the user has typed in an int, which is allowed by get int,
but that int is 0 or negative, I don't want to deal
with this user so I'm simply going to say,
sorry that makes no sense and then I'm going to return 1.
So this is a piece of new syntax.
It turns out that when you are writing a function which we are,
this thing called main, function tab can have return values,
this is that point I was just making, the return value
of get int is what data type presumably?
So its an int and you know,
I kind of have been waving my hands at it,
what's the return type of main?
Its been always int, even though I've not used this explicitly
so it turns out that even the function called main
which is the one you have to start your programs in c,
even it has a return value
and thus far every program I've written has had a return value,
every implementation of main
that I've written actually has a return to value
but it returned implicitly a value of zero.
So if you don't specify a return value at least in main,
the value of zero is just assumed so you don't have
to waste time and effort at the very bottom of your function.
Now why is this useful?
Well there's a lot of things that can go wrong
when you write a program, we've seen visually an example
of that, we've certainly seen a couple of buggy examples today
of that, so the idea that a program
or function can return a value is useful
because its only mechanism for informing the programmer
or the human, the user, that or whether
or that something went wrong.
So zero is good.
Zero means nothing went wrong, I'm not going to tell you
that nothing went wrong but unfortunately with programming
and with computers can we make a heck of a lot of mistakes.
There's as many as four billion mistakes exist when it comes
to programming, even that is technically an
over simplification.
But this is good because zero means good and I can assume
that zero always means success.
You return zero, good stuff happens,
but in case you made any number of the billion possible mistakes
that someone can make, you got a billion other integers you can
return so that you can signify those errors.
Now I'm exaggerating, hopefully your not hand error checking
for a billion different things in a program.
Usually you check for one or two that can actually happen
but the point here is this.
I've decided arbitrarily by human convention
if this thing goes wrong I'm going to return this
so called sentinel value, just a special arbitrary number,
the number 1 why, because its different from zero
and that's really all it is.
So if you've ever been using your Mac or your pc and you all
of a sudden get some popup that says an error has occurred
or it freezes, very often
in these little dialog windows do you see a number.
Maybe it positive, maybe it's negative,
it generally means nothing to you but guess
who it does mean something to?
Right the programmer.
The person at Microsoft, Apple or whoever who wrote it,
so not all that useful for you unless you call tech support
and tell them what you're seeing on the screen
but these error codes.
These return codes are generally used by the developer,
the programmer to actually understand what's going wrong.
So here by convention I'm returning 1.
Really this program is so simple it doesn't matter what I return
but again, convention, return a non-zero value.
All right so let's assume that the user is not being difficult
and I'm proceeding to sing this annoying song so I'm going
to print a new line first, just for aesthetic reasons
and it turns out this program is not that hard to implement.
Let me go ahead and iterate from I equals,
oh this is interesting, so even though thus far,
just by habit I've been incrementing from zero on up
or one on up, there is nothing stopping you from doing it
in the reverse direction, in fact here,
because conceptually I'm starting at 99 and going
on down, I don't want to confuse myself by starting the loop
at zero by printing the opposite, 99,
let's just start at 99.
so int I gets 99 or whatever the value of n is,
I'm going to sing this song so long as I is greater than zero,
maybe the song is supposed to end at zero or one,
I wasn't sure so I said keep going until its zero,
we definitely don't want to go negative and then
on each iteration do I minus minus
and this recalls a shorthand quotation.
We saw plus plus even as far back
as our sock changing example,
but really this is shorthand notation
for I gets the assignment operator, I minus 1, right?
or if you do the plus plus that is equivalent to I plus one
or there's yet other shorthand notation you might see
in on line resources or the TF's code or in books,
you can do I minus equals 1 to decrement or I plus equals one
to increment, frankly this is why most people just do I plus
plus or minus minus because its much more straight forward.
As an aside there is also a minus minus operator
and a plus plus operator.
In many context they do the same thing,
in some context they don't, we'll see over time when
and if you should actually care but generally put it after
and you'll be pretty safe.
So let's take a look at this song, its got four lines,
prints some number of bottles and notice here,
I'm already kind of taking a shortcut, I didn't want to have
to write too much code.
What's my cheat here?
>> [inaudible]
>> Yeah bottles, like cut this corner, right?
it's not wrong grammatically its just the parenthesis are only
useful eventually so we'll get there right?
baby steps.
so the first line is print some number of bottles of beer
on the wall and I'm inserting to that format string,
that placeholder I, some number of bottles of beer, same thing,
, I, take one down and pass it around, that's just text
so notice printf again, it doesn't have to take any commas,
or anything after it, now I have
to do a little bit of math but not much.
Some number of bottles of beer on the wall but now I want
to do the decrematation.
So now is there a risk that I'm actually going
to say negative one at any point?
>> [inaudible]
>> Disagreement so push back.
What's, how is this happening?
Well let's see.
There's a loop here, we're starting at n
so we're definitely starting big but I'm checking this condition
on every iteration is I greater than zero so its only going
to be the case, even at the very last iteration that I has
to be greater than zero, so on my very last pass
through this loop I is going to be minimally.
So 1, so if I is one I think I'm safe, so 1 gets printed here,
because its I, 1 gets printed here because its I,
1 gets printed here, or rather, no, zero gets printed here
because its I minus one but recall what happens
with a 4 loop after each iteration, you don't go back
to the left of this thing, its the update that happens,
I becomes 0, the condition is checked
and so in fact we are safe.
So its close but we are in fact safe because I'm stopping
so long as I is greater than or equal to 0, the error would be
if I did something like this
or any other number of logical quirks.
So now what's one difference toward the end of this program?
Well at the end I decide to exit and no
because I've used a non-zero return value technically I don't
need this return 0 because 0 will be assumed but as a matter
of good style, if I'm going to start taking the trouble
to return values explicitly let's be consistent
and actually return 0 at the end.
For all intents and purposes, certainly in this course,
its not generally going to matter
but when your programs do get larger
and more sophisticated is this a very useful habit
to already be in.
but let's see if we can, well let's actually sing the song,
so let's, well that would be awkward,
but let's just do the program version.
Make beer, let's run this first.
So make beer one, let's go ahead and run beer one.
How many bottles would there be?
Well its not going to fit on the screen but let's try it.
99 and sure enough, if I scroll back up in time it's a whole lot
of iteration going on, seems to check out at the top,
99 goes down to 98, 97 and at the very bottom 0 bottles
of beer on the wall so not a great program,
because I'm totally cutting corners
with the parenthesization of the s, but its not bad.
Yeah? Oh , good question.
So when in doubt let's just answer it definitively.
So let's go ahead and do what's pretty reasonable,
maybe I'm not even quite sure early on of the logic
so let's resave that, go down, sorry, that's not correct,
greater than or equal to, so the syntax follows the English,
greater than or equal to 0 so I argue this is going
to take us one step too far.
It will compile, so this is not a compilation error,
this is s logical error.
This is a programming conceptual mistake, not a syntax error,
so let me go ahead and no rerun beer one,
doesn't matter what it is, I could do 199, its still going
to run fast and in fact now I see this aesthetic quirk.
So I see in fact a negative 1 because percent d just means one
or more digits whether positive or negative.
Yeah?
>> [inaudible]
>> Oh, I'm sorry, okay I'm sorry, I misunderstood,
so let's do that too, so let me go back and let's say,
let's just rerun it with this
so negative 99 beers, I should catch that.
Because of my if condition, my error checking
at the top of the function.
>> [inaudible]
>> Oh, okay.
so this is where I say for all intents
and purposes it doesn't matter in this course
because you don't see the return values but in a week
or two's time you're going to find that PrinTif
as a debugging tool, a tool with which to find mistakes
in programs is only so useful.
When your programs get, start taking input from users
and you might have a lot of variables in mind,
you can't just rely on PrinTif as a useful tool so we're going
to start using what's called a debugger.
Something called GGDB.
You may recall from last week I just mentioned terribly briefly
that there's this other flag GGDB
that includes some special stuff
in your program when you compile it.
well, long story short, we're going to get
to the point very soon of not only being able
to run programs you write but be able to run them
in a simulation mode whereby you can step
through your own code line by line by line.
Interact with it, change it and in
that context will be more useful to know what the return value is
because you'll be able to see it in that simulator.
>> [inaudible]
>> So it's a good question.
In the first one, it's not really necessary.
Your welcome too so long as your consistent with these lessons,
return 0 for instance by default
but at some point soon will you need to get to that point,
and if you are, in fact already in problem set 1,
doing any error checking which you might very well be,
check the number of Skittles that are in the machine
and so forth, then absolutely.
Start returning 1 then 2 then 3
to represent arbitrarily your various return values.
But again, and we'll talk more about some of these details
in section but let's introduce a pretty bad bug here.
so let me go back into beer 1.c and let me scroll
on down, and you know what?
Let's actually omit this error check at the very top
so let me save that,
and actually let me fix the other mistake,
so we're not changing too many things at once,
I'm going to go back to the original but notice,
I've not done my original check, save, recompile beer 1,
rerun beer 1, whoops, rerun beer 1, 99, seems to work,
let's try negative 99.
Hm. So okay, so its not quite right, right?
so in fact let's make one other mistake just
to see how well we can really break the cloud here.
so let's actually suppose that I goof and I do,
while I is less than 0.
so let's recompile, and again this bang trick I'm doing,
again, exclamation point XYZ will actually get the last
command that started with XYZ so let me recompile this, oh,
and this is another message, if you get this and you,
I just want to recompile my program,
well you already did is what that message is telling you.
all right.
that ones come up before too.
So let's rerun beer1, 99 bottles.
Okay I've really broken this now let's be difficult, negative 99.
so what's going to happen.
Can we reason through what's going to happen?
Say that's a lot of ideas.
So a couple things could happen.
One, the assumption you have to make is this is an int,
even though I'm messing around with the input its still and int
and we know and int, like any data type in a computer is going
to be a finites size, probably 32 bits, maybe 64 bits
but in this case, 32 bits,
the biggest negative number we can represent with an int is
so negative 2 billion so frankly we might be here a while
if we keep waiting for this thing to go
but eventually you're going to go to negative 2 billion
and then you're going to keep going a little too much
and what's going to happen?
You're not going to overflow to another int in memory,
what's going to happen if you only have 32 bits and now you're
at the point of representing those,
the biggest negative one possible.
Its probably, something's going to change, right?
if you're just flipping 0's and 1's as zero becomes a 1
and 1 becomes a 0, just like the board exercise we did
and the hands being raised the other day.
If you only have so many premutatons of hands in the air
or 0's and 1's on the board, well eventually
if you keep adding 1 your probably going to wrap around.
Its wrong, but you're going to wrap around from what appears
to be a negative number
to what's an arbitrary positive number probably positive 2
billion and you'll get in this loop.
Now this really will take a while so let's see
if we can't speed up this bug, why don't we,
instead of doing this, we could do minus equals how
about 1000 at a time.
this program is 1000 times faster now,
negative 99 let's see if that's fast enough.
No that's still going to take a while.
Let's do, that's pretty fast, let's recompile, rerun,
be difficult again, okay.
I fixed it right?
it stopped.
So it didn't go positive it seems, I lied right?
so it did become positive, right?
the only condition in which this song ends and says, wow,
that's annoying, is when that condition is no longer true
but the condition I just changed was to be sure
that I is always less than 0 so logically
if this program stopped and I didn't kill it
like with control c, it just stopped on its own,
it said wow that's annoying,
it must be that I became 0 and in fact it did.
It simply wrapped around back to a positive value,
but condition exited so it kind of fixed the programs execution
but it didn't fix the logical error at hand.
So you have the correct version, I have made a complete mess
of this particular version, but the take away here is again,
not only do computers have a finite amount of precision,
they also have a finite amount of capabilities when it comes
to storing a large or potentially large number.
Let me point out one little teaser, if I may.
I pulled up this web site in advance,
some of you might have a ps3 or Wii or Xbox.
If you have a Wii you can crack these things, there's this
so called homebrew club that allows you to do fun things
with your Wii and I thought I would read this and it related
to this idea of computers only having
so much finite memory space and we'll see more on this
when we discus a raise.
How the Zelda TP Exploit works.
Stack, buffer over flow.
During a stack buffer over flow a program writes outside
of the intended program data structure in the memory address,
so not the same problem we just induced, but definitely related
to this idea of finite storage and maybe not checking
if we're using memory that doesn't belong to us.
This is used in the twilight house
so this is the twilight Zelda game so for the familiar,
when you're in a game, a lengthy name of Opona the horse is used
to generate a stack overflow,
this occurs during a conversation with a man
when you load your save, when he loads the name and in order,
when he loads the name to use in the dialog box
or when you're entering the next zone
where you have to ride a horse.
This is to say, we will start Wednesday's lecture not
with an explosion but with this particular gaming error.
See you then.
I ?? ?? ??
??