Comprehensive CS50 Course Review: From Basics to Web Development
Description
Explore the full journey of Harvard's CS50 course, covering foundational programming concepts, data structures, Python, SQL, web development with HTML, CSS, JavaScript, and cybersecurity essentials. Gain insights into practical applications, debugging, and best practices for secure coding and user interface design.
Keywords
CS50 course review, Harvard CS50, programming fundamentals, Python tutorial, SQL basics, web development HTML CSS JavaScript, cybersecurity, debugging techniques
Content
Introduction to CS50 and Computational Thinking
- CS50 is Harvard University's introduction to computer science and programming.
- Focuses on computational thinking: precise, logical problem solving.
- Emphasizes personal progress over comparison with peers.
Foundations of Programming and Data Structures
- Early weeks cover basics: variables, loops, conditionals, functions.
- Introduction to data structures: arrays, linked lists, trees, hash tables, tries.
- Trade-offs between time and space complexity discussed.
- Big O notation used to analyze algorithm efficiency.
Transition to Python and SQL
- Python simplifies syntax and automates memory management.
- SQL introduced for relational database management.
- Use of libraries and frameworks (Flask, Bootstrap) to build web apps.
- Emphasis on code readability, modularity, and error handling.
Web Development Essentials
- HTML for page structure; tags and attributes explained. Comprehensive Guide to HTML and CSS: From Basics to Advanced Techniques
- CSS for styling; classes, IDs, selectors, and external stylesheets.
- JavaScript for interactivity; event listeners, DOM manipulation. Java Programming Course: Introduction, Structure, and Setup Guide
- Responsive design and accessibility considerations.
Building Dynamic Web Applications
- Flask framework for Python-based web servers.
- Routing, templates, and form handling with GET and POST methods.
- Session management and cookies for user state and authentication.
- Integration of databases for persistent data storage.
Security and Best Practices
- Importance of strong, random passwords and two-factor authentication.
- Risks of SQL injection and mitigation via parameterized queries.
- Use of debugging tools and error handling techniques. Comprehensive Guide to Ethical Hacking: From Basics to Advanced Concepts
- Encouragement to use password managers and encryption.
Advanced Topics and Real-World Applications
- Image and video handling on the web.
- Speech synthesis and recognition with Python libraries.
- Face recognition and QR code generation.
- Overview of internet protocols: TCP/IP, HTTP, DNS.
Course Conclusion and Resources
- Encouragement to continue learning and practicing.
- Recommendations for tools: Git, local development environments.
- Community resources: Stack Overflow, Reddit, official docs.
- Final project as a capstone to synthesize learned skills.
Interactive Review and Engagement
- Use of live polls and quizzes to reinforce learning.
- Emphasis on understanding over memorization.
- Recognition of the course's comprehensive scope and depth.
This comprehensive review encapsulates the CS50 course's progression from fundamental programming concepts to advanced web development and cybersecurity, highlighting practical skills, theoretical knowledge, and real-world applications essential for aspiring computer scientists and developers.
if you want to learn about computer science and the Art of programming this course is where to start cs50 is
considered by many to be one of the best computer science courses in the world this is a Harvard University course
taught by Dr David men and we are proud to bring it to the Freo Camp YouTube channel throughout a series of lectures
Dr me will teach you how to think algorithmically and solve problems efficiently and make sure to check the
description for a lot of extra resources that go along with the course [Music]
all right this is cs50 Harvard University's introduction to the intellectual Enterprises of computer
science and the Art of programming back here on campus in beautiful Sanders Theater for the first time in quite a
while so welcome to to the class my name is David May so my name is David man and I took
this class myself some time ago but almost didn't it was it was sophomore fall and I was sitting in on the class
and I was a little curious but H didn't really feel like the field for me I was definitely a computer person but
computer science felt like something altogether and I only got up the Nerf to take the class ultimately because the
professor at the time Brian kernahan allowed me to take the class past fail initially and that is what made all the
difference I quickly found that computer science is not just about programming and working in isolation on your
computer it's really about problem solving more generally and there was something about homework frankly that
was like actually fun for perhaps the first time in what 19 years and there was something about this ability that I
discovered along with all of my classmates to actually create something and bring a computer to life to solve a
problem and and sort of bring to bear something that I've been using every day but didn't really know how to harness
that's been gratifying ever since and definitely challenging and frustrating like to these to this day all these
years later you're going to run up against mistakes otherwise known as bugs in programming that just drive you nuts
and you feel like you've hit a wall but the trick really is to give it enough time to take a step back take a break
when you need to and there's nothing better I dare say than that sense of gratification and pride really when you
get something to work and in a class like this present ultimately a a terms end something like your very own final
project now this isn't to say that I took to it 100% perfectly in fact just this uh this past week I I looked in my
old cs50 binder which I still have from some 25 years ago and took a photo of what was apparently the very first
program that I wrote and submitted and quickly received minus two points on but this is a program that we'll soon see in
the coming days that does something quite simply like print hello cs50 in this case to the screen and to be fair I
technically hadn't really followed the directions which is why I lost those couple of points but if you just look at
this especially if you've never programmed before you might have heard about programming language but you've
never typed something like this out undoubtedly it's going to look cryptic but unlike human languages frankly which
were a lot more sophisticated a lot more vocabulary a lot more grammatical rules programming once you start to wrap your
mind around what it is and how it works and what these various languages are it's so easy you'll see after a few
months of a class like this to start teaching yourself subsequently other languages as they may come in the coming
years as well so what ultimately matters in this particular course is not so much where you end up relative to your
classmates but where you end up relative to yourself when you began and indeed you'll begin today and the only
experience that matters ultimately in this class is your own and so consider where you are today consider perhaps
just how cryptic something like that looked a few seconds ago and take comfort in knowing just some months from
now all of that will be uh within your own grasp and if you're thinking that okay surely the person in front of me to
the left to the right behind me knows more than me that's statistically not the case 2third of cs50 students have
never taken a CS course before which is to say you're in very good company uh throughout this whole term so then what
is computer science I claim that it's problem solving and the upside of that is that problem solving is something we
sort of do all the time but computer science class learning to program I think kind of cleans up your thoughts it
helps you learn how to think more method meally more carefully more correctly more precisely because honestly the
computer's not going to do what you want unless you are correct and precise and methodical and so as such there's these
sort of fringe benefits of just learning to think like a computer scientist and a programmer and it doesn't take all that
much to start doing so this for instance is perhaps the simplest picture of computer science sure but really problem
solving in general problems are all about taking input like the problem you want to solve you want to get the
solution AKA output and so something interesting's got to be happening in in here in here when you're trying to get
from those inputs to outputs now in the world of computers specifically we need to decide in advance how we represent
these inputs and outputs we all just need to decide uh whether it's Macs or PCS or phones or something else that
we're all going to speak some common language irrespective of our human languages as well and you may very well
know that computers tend to speak only what language so to speak assembly one but binary 2 might be
your go-to binary by implying two means that the world of computers has just two digits at its disposal zero and one and
indeed we humans have many more than that certainly not just zeros and ones alone but a computer indeed only has
zeros and ones and yet somehow they can do so much they can crunch numbers and Excel send text messages create images
and and artwork and movies and more and so how do you get from something as simple as a few zeros a few ones to all
of the stuff that we're doing today in our pockets and laptops and desktops well it turns out that we can start
quite simply if a computer were to want to do something as simple as count well what it could it do well in our human
world we might count doing this like 1 2 3 4 5 using so-called unary notation literally the digits on your fingers
where one finger represents one person in the room if I'm for instance taking attendance now we humans would typically
actually count 1 2 3 4 5 six and we'd go past just those five digits and count much higher using zeros through nines
but computers somehow only have these zeros and one so if a computer only somehow speaks
binary zeros and ones how does it even count past the number one well here are three zeros of course and if you
translate this number in binary 0 0 0 to a more familiar number in decimal we would just call this zero enough said if
we were to represent with a computer the number one it would actually be 0 01 which not surprisingly is exactly the
same as we might do in our human world but we might not bother writing out the two zeros at the beginning
but a computer now if it wants to count as high as two it doesn't have the digit two and so it has to use a different
pattern of zeros and ones and that happens to be 0 1 0 so this is not 10 with a zero in front of it it's indeed 0
1 0 in the context of binary and if we want to count higher now than two we're going to have to tweak these zeros and
ones further to get three and then if we want four or five or six or seven we're just kind of toggling these zeros and
ones AKA bits for binary digits that represent via these different patterns different numbers that you and I as
humans know of course as the so-called Decimal System 0 through n deck implying 10 10 digits those zeros through nine so
why that particular pattern and why these particular zeros and Ones Will turns out that representing one thing or
the other is just really simple for a computer why at the end of the day they're powered by electricity and it's
a really simple thing to just either store some electricity or don't store some electricity like that's as simple
as the world can get on or off one or zero so to speak so in fact inside of a computer a phone anything these days
that's electronic pretty much is some number of switches otherwise known as transistors and they're tiny you've got
thousands millions of them in your Mac or PC or phone these days and these are just tiny little switches that can get
turned on and off and by turning those things on and off in patterns a computer can count from zero on up to seven and
even higher than that and so these switches really you can think of being as like switches like this let me just
borrow one of our little stage lights here here's a light bulb it's currently off and so I could just think of this as
representing in my laptop a transistor a switch representing zero but if I allow some electricity to flow now I in fact
have a one well how do I count higher than one I of course need another light bulb so let me grab another one here and
if I put it in that same kind of pattern I don't want to just do this that's sort of the old finger counting way of unary
just one two I want to actually take into account the pattern of these things being on and off so if this was one a
moment ago what I think I did earlier was I turned it off and let the next one over be on AKA 01 0 and let me get us a
third bit if you will and that feels like enough here is that same pattern now starting at the beginning with three
so here is 0 0 here is 0 0 1 here is 0 1 0 Z AKA in our human world of decimal two and then we of course keep counting
further this now would be three and dot dot dot if this other bulb now goes on and that switch is turned and all three
stay on this again was what number okay so seven so it's just as simple relatively as that if you will but how
is it that these patterns came to be well these patterns actually follow something very familiar you and I don't
really think about it at this level anymore cuz we've probably been doing math and numbers since grade school or
whatnot but if we consider something in decimal like the number 123 I immediately jump to that this
looks like 123 in decimal but why it's really just three symbols a one a two with a bit of curve a three with a
couple of curves that you and I now instinctively just assign meaning to but if we do rewind a few years that is
123 because you're assigning meaning to each of these columns the three is in the so-called one's place the two is in
the so-called 10's place and the one is in the so-called hundreds place and then the math ensues quickly in your head
this is technically 100 * 1 plus 10 * 2 + 1 * 3 AKA 100 + 20 + 3 and there we get the sort of mathematical notion we
know is 123 well nicely enough in binary it's actually the same thing it's just these
columns mean a little something different if you use three digits in decimal and you have the ones place the
T place and the hundreds place well why was that 10 1 10 and 100 they're technically just powers of 10 so 10 the
0 10 the 1 10 the two why 10 Decimal System deck meaning 10 you have eight and 10 digits zero through nine in the
binary system if you're going to use three digits just change the bases if you're using only zeros and ones so now
it's powers of two 2 to the 0 2 to the 1 2 to the 2 AK a 1 and 2 and four respectively and if you keep going it's
going to be Eight's column 16's column 32 64 and so forth so why did we get these patterns that we did here's your 0
0 0 because it's 4 * 0 2 * 0 1 * Z obviously zero this is why we got the decimal number one in binary this is why
we got the number two in binary because it's 4 * 0 + 2 * 1 + 1 * 0 and now 3 and now 4 four and now five and now six and
now seven and of course if you wanted to count as high as eight to be clear like what do you have to do what does a
computer need to do to count even higher than seven add a bit add another light bulb
another switch and indeed computers have standardized just how many zeros and ones or bits or switches they throw at
these kinds of problems and in fact most computers would typically use at least eight at a time and even if you're only
counting as high as three or seven you would still use eight and have a whole bunch of zeros but but that's okay
because the computers these days certainly have so many more thousands millions of transistors and switches
that that's quite okay all right so if with that said if we can now count as high as seven or frankly as high as we
want that only seems to make computers useful for things like Excel like number crunching but computers of course let
you send text messages write documents and so much more so how would a computer represent something like a letter like
the letter A of the English alphabet if at the end of the day all they have is
switches any thoughts yeah okay so we could represent letters using numbers okay so give me what's a
proposal what number should represent whatting the beginning perfect yeah we just all have
to agree somehow that one number is going to represent one letter so one is a two is B 3 is C uh Z is 26 and so
forth maybe we can even take into account uppercase and lower case we just have to agree and sort of write it down
in some global standard and humans indeed did just that they didn't use one two three turns out they started a
little higher up capital A has been standardized as the number 65 uh and capital B has been standardized as the
number 66 and you can kind of imagine how it goes up from there and that's because whatever you're representing
ultimately can only be stored at the end of the day as zeros and ones and so some humans in a room before decided that
capital A shall be 65 or really this pattern of zeros and ones inside of every computer in the world 0 1 0 0
00001 so if that pattern of zeros and ones ever appears in a computer it might be interpreted then as indeed a capital
letter a eight of those bits at a time but I worry just to be clear we might have now created a problem it might seem
if I play this naively that okay how do I now actually do math with the number 65 if now Excel displays 65 is an a let
alone B's and C's so how might a computer do as you've proposed have this mapping from numbers to letters but
still support numbers it feels like we've given something up yeah AIX by having a
prefixed okay so we could perhaps have some kind of prefix like some pattern of zeros and ones I like this that rep that
indicates to the computer here comes another pattern that represents a letter here comes another pattern that
represents a a number or a letter so not bad I like that other thoughts how might a computer distinguish these two H
yeah indeed and that's spot on nothing wrong with what you suggested but the world generally does just that the
reason we have all of these different file formats in the world like uh JPEG and GIF and pings and Word Documents do
do o c x and Doc Excel files and so forth is because a bunch of humans got in a room and decided Well in the
context of this type of file or really more specifically in the context of this type of program Excel versus Photoshop
versus Google Docs or the like we shall interpret any patterns of zeros and ones as being maybe numbers for Excel maybe
uh letters in like a text messaging program or Google Docs or maybe even colors of the rainbow and something like
Photoshop and more so it's context dependent and we'll see when we ourselves start programming you the
programmer will ultimately provide some hints to the computer that tells the computer interpret it as follows so
similar in spirit to that but not quite as standardized with these prefixes so this system here actually has a name ASI
the American Standard code for information interchange and indeed it began here in the US and that's why it's
actually a little biased toward A's through Z's and a bit of punctuation as well and that quickly became a problem
but if we start simply now in English the mapping itself is fairly straight so if a is 65 B is 66 and dot dot dot
suppose that you received a text message an email from a friend and underneath the hood so to speak if you kind of
looked inside the computer what you technically received in this text or this email happened to be the numbers 72
73 33 or really the underlying pattern of zeros and ones what might your friend have sent you as a message if it's 72 73
33 hey close hi it's indeed High Why well apparently according to this little
cheat sheet H is 72 I is 73 it's not obvious from this chart what the 33 is but indeed this pattern represents high
and anyone want to guess or if you know what 33 is exclamation point and this is frankly not the kind of thing most
people know but it's easily accessible via a nice userfriendly chart like this so this is an asky chart when I said
that we just need to write down this mapping earlier this is what people did they wrote it down in a book in a chart
and for instance here is our 72 for H here is our 73 for I and here is our 7 33 for exclamation point and computers
Macs PCS iPhones Android devices just know this mapping by heart if you will they've been designed to understand
those letters so here I might have received High technically what I've received is these patterns of zeros and
ones but it's important to note that when you get these patterns of zeros and ones in any format be it email or text
or a file they do tend to come in standard lengths with a certain number of zeros and ones alog together and this
happens to be 8 plus 8 plus 8 so just to get the message High exclamation point you would have received at least it
would seem some 24 bits but frankly bits are so tiny literally and mathematically that we don't tend to think or talk
generally in terms of bits you're probably more familiar with bites b t s is a bite is a bite is a bite a bite is
just eight Bits And even those frankly aren't that useful if we do out the math how high can you count if you have eight
bits anyone know say again uh higher than that unless you want to go negative that's
that's fine 256 technically 255 long story short if we actually got into the weeds
of all of these zeros and ones and we figured out what 11 one one one11 mathematically adds up to in decimal it
would indeed be 255 or less if you want to represent negative numbers as well so this is
useful because now we can speak not just in terms of bytes but if the files are bigger kilobytes is thousands of bytes
megabytes is millions of bytes gigabytes is billions of bytes terabytes are trillions of bytes and so forth we have
a vocabulary for these increasingly large uh quantities of uh data the problem is that if you're using
asky and therefore eight bits or one B per character and originally only seven you can only represent 255 characters
and that's actually fine or 256 total characters including zero and that's fine if you're using literally English
in this case plus a bunch of punctuation but there's many humans uh languages in the world that need many more symbols
and therefore many more bits so thankfully the world decided that we'll indeed support not just the US English
keyboard but all of the accented characters that you might want for some languages and Heck if we use enough bits
zeros and ones not only can we represent all human languages in written form as well as some emotions along the way we
can capture the latter with these things called emojis and indeed these are very much invogue these days you probably
send and or receive many of these things any given day these are just characters like letters of an alphabet patterns of
zeros and ones that you're receiving that the world has also standardized for instance there are certain emojis that
were represented with certain patterns of bits and when you receive them your phone your laptop your desktop displays
them as such and this newer standard is called Unicode so it's a superet of what we called ASI and unicode is just a
mapping of many more numbers to many more letters or characters more generally that might use eight bits for
backwards compatibility with the old way of doing things with ASI but they might also use 16 Bits And if you have 16 bits
you can actually represent more than 65,000 possible letters and that's getting up there and heck unic code
might even use 30 two bits to represent letters and numbers and punctuation symbols and emojis and that would give
you up to 4 billion possibilities and I dare say one of the reasons we see so many emojis these days is we have so
much room I mean there's got room for billions more literally so in fact just as a little bit of trivia has anyone
ever received this decimal number or if you prefer binary now has anyone ever received this pattern of zeros and ones
on your phone in a text or an email perhaps this past year here well if you actually look this up this esoteric uh
sequence of zeros and ones happens to represent uh face with medical mask and notice that if you've got an iPhone or
an Android device you might be seeing different things in fact this is the Android version of this most recently
this is the iOS version of it most recently and there's Bunches of other interpretations by other companies as
well so Unicode as a Consortium if you will has standardized the descriptions of what these things are but the
companies themselves manufacturers out there have generally interpreted it as you see fit and this can lead to some
human uh miscommunications in fact for like literally embarrassingly like a year or two I started being in the habit
of using the Emoji that kind of looks like this cuz I thought it was like woo happy face or whatever didn't realize
this is the emoji for hug because whatever device I was using sort of looks like this not like this and that's
because of their interpretation of the data this has happened too when what was a gun became a water pistol in some
manufacturers eyes and so it's an interesting dichotomy between what information we all want to represent and
how we choose ultimately to represent it questions then on these representations of formats be it numbers or letters or
soon more yeah and sorry why is why is what so popular popular
yeah so we'll come back to this in a few weeks in fact there are other ways to represent numbers binary is one decimal
is another unary is another and heximal is yet a fourth that uses 16 total digits literally 0 through 9 plus AB CDE
EF and somehow you can similarly count even higher with those uh we'll see in a few weeks why this is uh compelling but
heximal long story short uses four bits per digit and so four bits if you have two digits in HEX that gives you eight
and it's just a very convenient unit of measure and it's also human convention in the world of like files and other
things but we'll come back to that soon other questions the lights on the stage supposedly do the lights on the stage
supposedly say anything well if we had thought in advance to use maybe 64 light bulbs that would seem to give us uh
eight total bites on stage eight times uh eight giving us just that maybe good question other questions on zeros and
ones it's a little bright in here no oh
yes where everyone's pointing somewhere specific there we go sorry very bright in this
corner oh sure and we'll come back to this in some form in the coming days too at at a slower Pace too we have with
eight bits two possible values for the first and then two for the next two for the next and so so forth so that's 2 * 2
* 2 that's 2 to 8th power total which means you can have 256 total possible patterns of Zer and ones but as we'll
seen soon computer scientists programmers software often starts counting at zero by convention and if
you use one of those patterns 0 00 0 000000 0 to represent the decimal number we know is zero you only have 255 other
patterns left to count as high as therefore 255 that's all good question
question all right so what then might we have besides uh these emojis and letters and numbers well we of course have
things like colors and programs like Photoshop and pictures and photos well let me ask the question again how might
a computer do you think knowing what you know now represent something like a color like what are our options if all
we've got are zeros and ones and switches yeah RGB when RGB indeed is This Acronym
that represents some amount of red and some amount of green green and blue and indeed computers can represent Colors by
just doing that remembering for instance this dot this yellow dot on the screen that might be part of any of those
emojis these days well that's some amount of red some amount of green some amount of blue and if you sort of mix
those colors together you can indeed get a very specific one and we'll see in just a moment just that so indeed
earlier on did uh humans only use seven bits total and it was only once they decided oh let's add an eighth bit that
they got extended asy and that was initially in part A solution to the same problem of not having enough room if you
will in those patterns of zeros and ones to represent all of the characters that you might want but even that wasn't
enough and that's why we've now gone up to 16 and 32 and long past 7even so if we come back now to this one particular
color RGB was proposed as a scheme but how might this work well consider for instance this if we do indeed decide as
a group to represent any color of the rainbow with some mixture of some red some green and some blue we have to
decide how to represent the amount of red and green and blue well it turns out if all we have are zeros and ones airgo
numbers let's do just that for instance suppose a computer we using these three numbers 72 73 33 no longer in the
context of an email or a text message but now in the context of something like Photoshop a program for editing and
creating graphical files maybe this first number could be interpreted as representing some amount of red green
and blue respectively and that's exactly what happens you can think of the first digit as red second as green third as
blue and so ultimately when you combine that amount of red that amount of green that amount of blue it turns out it's
going to resemble this shade of yellow and indeed you can come up with numbers between 0 and 255 for each of those
colors to mix any other color that you might want and you can actually see this in practice even though our screens
admittedly are getting really good on our phones and laptops such that you barely see the dots they are there you
might have heard the term pixel before pixel is just a DOT on the screen and you've got thousands millions of them
these days horizontally and vertically and if I take even this Emoji which again happens to be one company's
interpretation of a face with medical mask and zoom in a bit maybe zoom in a bit more you can actually start to see
these pixels things get pixelated because what you're seeing is each of the individual dots that compose this
particular image and apparently each of these individual dots are probably using 24 bits eight bits for red eight bits
for green eight bits for blue in some pattern and this program or some other like Photoshop is interpreting one
pattern it's white or yellow or black or some brown in between and so if you look sort of awkwardly but up close to your
phone or your laptop or maybe your TV you can see exactly this too all right well what about things that we also
watch every day on YouTube or the like things like video how would a computer knowing what we
know now represent something like a video how might you represent a video using only zeros and ones
yeah yeah exactly and to summarize what video really adds is just some notion of time it's not just one image it's not
just one letter or number it's presumably some kind of sequence because time is passing and so with a whole
bunch of images maybe 24 maybe 30 per second if you fly them by the human's eyes we can interpret them using our
eyes and brain that there is now movement and therefore video and similarly with audio or music if we just
came up with some convention for representing those same notes on a musical instrument could we have the
computer synthesize them too and this might be actually pretty familiar let me pull up a quick video here which uh
happens to be an old school version of the same idea you might remember from [Music]
childhood so granted that particular video is an actual video of a paper based animation but indeed that's really
all you need is some sequence of these uh these images which themselves of course are just zeros and ones because
they're just this grid of these pixels or dots now something like musical notes like these those of you who are musicans
might just naturally play these on physical devices but computers can certainly represent those sounds too and
for instance a popular format for audio is called midi and midi might just represent each note that you saw a
moment ago essentially as a a sequence of numbers but more generally you might think about music as having notes for
instance a through G maybe some flats and some Sharps uh you might have the duration like how long is the note being
heard or played on a piano or some other device and then just the volume like how hard does a human in the real world
press down on that key and therefore how loud is that sound it would seem that just remembering little details like
that quantitatively we can then represent really all of these these otherwise analog uh human realities so
that then is really a laundry list of ways that we can just represent information again computers or digital
have all of these different formats but at the end of the day and as fancy as those devices in yours are it's just
zeros and ones tiny little switches or light bulbs if you will represented in some way and it's up to the software
that you and I and others write to use those zeros and ones in ways we want to get the computers to do something more
powerfully questions then on this representation of information which I dare say is ultimately what problem
solving is all about taking in information and producing new via some process in
between any questions out there yeah yeah in back yeah we so a really good question there are
many other file formats out there you allude to MP4 for video and more generally the are these things called
codecs and containers it's not quite as simple when using larger files for instance in more modern formats that a
video is just a sequence of images for instance why if you stored that many images for like a Hollywood movie like
24 or 30 of them per second that's a huge number of images and if you've ever taken phone uh photos on your phone you
might know how many megabytes or larger even individual photographs might be so humans have developed over the years uh
fancier software that uses much more math to represent the same information more minimally just using somehow
shorter patterns of zeros and ones that are most simplistic representation here and they use what might be called
compression if you've ever used a zip file or something else somehow your computer is using fewer zeros and ones
to represent the same amount of information ideally without losing any information and in the world of
multimedia which we'll touch on a little bit in a few weeks there are both lossy and lossless formats out there lossless
means you lose no information whatsoever but more commonly as you're alluding to one is ly compression L OSS Y where
you're actually throwing away some amount of quality you're getting a some amount of pixelation that might not look
perfect to the human but heck it's a lot cheaper and a lot easier to distribute and in the world of multimedia you have
containers like Quicktime and other uh M containers that can combine different formats of video different formats of
audio in one file but there too do designers have discretion so more in a few few weeks too other questions then
on information here as well yeah know Compu used to be very big taking up like a whole room andu is the reason they've
gotten smaller because information what exactly I mean back in
the day you might have heard of the expression a vacuum tube which is like some physically large device um that
might have only stored some zero or one um yes it is the miniaturization of Hardware these days that has allowed us
to store as many and many more zeros and ones much more closely together and as we've built more fancy machines that can
sort of Design This Hardware at an even smaller scale we're just packing more and more into these devices but there
too is a trade-off for instance you might know by using your phone uh or your laptop for quite a while maybe on
your lap starts to get warm and so there are these literal physical side effects of this where now some of our devices
run hot and this is why like a data center in the real world might need more air conditioning than a typical place
because there are these physical AR facts as well and in fact if you'd like to see one of the earliest computers
from decades ago across the river here in now Alon in the new engineering building is the Harvard mark1 computer
uh that will give you a much big a better mental model of just that well if we come back now to this first picture
being computer science or really problem solving I dare say we have more than enough ways now to represent information
input and output so long as we all just agree on something and thankfully those before us have given us things like asky
and unicode not to mention MP4s Word documents and the like but what's inside of this proverbial black box into which
these inputs are going and the outputs are coming well that's where we get this term you might have heard too an
algorithm which is just step-by-step instructions for solving some problem incarnated in the world of computers by
software when you write software AKA programs you are implementing one or more algorithms one or more step uh sets
of instructions for solving some problem and maybe you're using this language or that but at the end of the day no matter
the language you use the computer is going to represent what you type using just zeros and ones so what might be a
representative algorithm nowadays you might use uh your phone quite a bit to make calls or send texts or emails and
therefore you have a whole bunch of contacts in your address book nowadays of course this is very digital but
whether on iOS or Android or the like you might have a whole bunch of names a first name and or last as well as
numbers and emails and the like and you might be in the habit of like scrolling through on your phone all of those names
to find the person you uh want to call uh it's probably sorted alphabetically by first name or last name a through z
or some other symbol and this is frankly quite the same as we used to do you know back in in my day cs50 when we just used
a physical book and this physical book might be a whole bunch of names alphabetically sorted from left to right
corresponding to a whole bunch of numbers so suppose that in this Old Harvard phone book we want want to
search for John Harvard we might of course start quite simply at the beginning here looking at one page at a
time and this is an algorithm this is like literally step by steps uh looking for the solution to this problem in that
sense if John Harvard's in the phone book is this algorithm Page by Page correct would you
say yes like if uh John Harvard's in the phone book obviously I'm eventually going to get to him so that's what we
mean by correct is it efficient is it well-designed would you say no I mean this is going to take forever even just
to get to the J's or the H's depending how this thing sorted all right well let me go a little faster I'll start like
two pages at a time 2 4 6 8 10 12 and so forth sounds faster is faster is it correct okay why is it not correct
yeah exactly if I start an odd number of pages and I'm going two at a time I miss pages in between and if I therefore
conclude when I get to the back of the book there was no John Harvard I might have just aired this would be again one
of these bugs but if I try a little harder I feel like there's a solution we don't have to completely throw out this
algorithm I think we can probably go roughly twice as fast still but what should we do instead to fix this yeah
I'm back nice so I think what many of us most of us if we even use this technology
anymore these days we might go roughly to the middle of the phone book just to kind of get us started and now I'm
looking down I'm looking for Jay assuming first name Jay Harvard and it looks like I'm in the M section so just
to be clear what should I do next okay and presumably it is John Harvard would be to the left of this so
here's an opportunity to figuratively enl literally tear this particular problem in half throw half of the
problem away it's it's actually pretty easy if you just do it that way the hard way is this way but I've now just uh
decreased the size of this problem really in half so if I started with like a thousand pages of phone numbers and
names now I'm down to 500 and already we haven't found John Harvard but that's a big bite out of this problem and I do
think it's correct because if J is to the left of M of course he's definitely not going to be over there and I think
if I repeat this is again dividing and conquering if you will here I might have gone a little too far now I'm in like
the E section so let me tear the problem in half again throw another 250 Pages away and again repeat dividing and
dividing and conquering until finally presumably I end up with just one page of a phone book on which John Harvard's
name either is or is not but because of the algorithm you proposed step by step I know that he's not in anything I
discarded so dramatic as that might have been um uh been made out to be it's actually
just harnessing pretty good human intuition indeed this is what programming is all about too it's not
about learning a completely new world but really just how to harness intuition and ideas that you might already have
and take naturally but learning how to express them now more succinctly more precisely and using things called
programming languages why is an algorithm like that if I found John Harvard better than ultimately just
doing the first one or even the second maybe doubling back to check those even Pages well let's just look at a little
charts here again we don't have to get into the the nuances of numbers but if we've got like a chart here XY plot on
the x-axis here I claim is the size of the problem so measured in the P numbers of pages in the phone book so the
farther you go out here the more pages are in the phone book and here we have time to solve on the y- axis so the
higher you go up the more time it's going to be taking to solve that particular problem so let's just
arbitrarily say that the first algorithm involving like n Pages might be represented graphically like this no
matter the slope it's a straight line because there's presumably a onetoone relationship between numbers of pages
and number of seconds or number of page turns why if the phone company adds another page next year because some new
people move to town that's going to require one additional page for me one to one if though we use the second
algorithm flawed though it was unless we double back a little bit to fix someone being in between that's two going to be
a straight line but it's going to be a different slope because now there's a two: one or a one: two relationship
because I'm going two pages at a time so if the phone company adds another page that's going to take me only or another
two pages that's still only just one more step and you can see the difference if I kind of dra draw this if this is
the phone book in question this number of pages it might take this many seconds on the yellow line to represent or to
solve uh to find someone like John Harvard but of course on the first algorithm the red line
it's literally going to take twice as many steps and what do the ends here Meet n is the go-to variable for
computer scientist or programmer just generically representing a number so if the number of pages in the phone book is
in the number of steps the second algorithm would have taken would be in the worst case n/ two half as many
because you're going twice as fast but the third algorithm actually if you recall your your logarithms looks a
little something like this there's a fundamentally different relationship between the size of the problem and the
amount of time required to solve it that technically is log based two event but it's really the shape that's different
and the implication there is that if for inston Cambridge and Austin two different towns here in Massachusetts
merge next year and there's just one phone book that's twice as big no big deal for that third and final algorithm
why you just tear the problem one more time in half taking one more bite that's it not another thousand bytes just to
get to the solution and put another way you can walk out way way way out here to a much bigger phone book and ultimately
that green line is barely going to have budged so this then is just a way of now formalizing and thinking about what the
performance or quality of these algorithms might be and before we now make one more formalization of the
algorithm itself any questions then on this notion of efficiency or now performance of
ideas yeah many um a lot of phone books over the years and if you or your parents have
any more still somewhere we could definitely use them because they're hard to find other questions but thanks other
questions here too no oh was that a murmur yes over here sorry say
again oh yeah hopefully and then we could uh then we'd have a little something more to use here so now if we
want to formalize further what it is we just did we can go ahead and introduce this a form of code AKA pseudo code
pseudo code is not a specific language it's not like something we're about to start coding in it's just a way of
expressing yourself in English or any human language succinctly correctly toward an end of getting your idea for
an algorithm across so for instance here might be how we could formalize the code the pseudo code for that same algorithm
step one was pick up the phone book as I did step two might be open to the middle of the phone book as you proposed that
we do first step three was probably to look down at the pages I did and step four gets a little more interesting
because I had to quickly make a decision and ask myself a question if person is on page then I should probably just go
ahead and call that person but that probably wasn't the case at least for John Harvard and I opened the M section
and so there's this other question I should now ask else if the person is earlier in the book then I should tear
the problem in half as I did but go left so to speak and then not just open to the middle of the left half of the book
but really just go back to step three repeat myself why because I can just repeat what I just did but with a
smaller problem having taken this big bite but if the person was later in the book as might have happened with a
different person than John Harvard then I should open to the middle of the right half of the book again go back to line
three but again I'm not going to get stuck doing something forever like this cuz I keep shrinking the size of the
problem lastly the only possible scenario that's left if John Harvard is not on the page and
he's not to the left and he's not to the right what should our conclusion be he's not there he's not listed and so
we need to quit in some other form now as an aside it's kind of deliberate that I buried that last question at the end
because this is H what happens all too often in programming whether you're new at it or professional just not
considering all possible cases Corner cases if you will that might not happen that often but if you don't anticipate
them in your own code code pseudo code or otherwise this is when and why programs might crash or you might see
stupid little spinning beach balls or hourglasses or your computer might reboot why it's doing something sort of
unpredictable if a human maybe myself didn't anticipate this like what does this program do if John Harvard's not in
the phone book If I Had omitted lines 12 and 13 I don't know maybe it would behave differently on a Mac or PC
because it's sort of undefined behavior and these are the kinds of omissions that frankly you're invariably going to
make bugs you're going to introduce mistakes you're going to make early on and me too 25 years later but you'll get
better at thinking about those Corner cases and handling anything that can possibly go wrong and as a result your
code will be all the better for it now the problem ultimately with learning how to program especially if you've never
had experience or even if you do but you learned a one language only is that they all look a little cryptic at first
glance but they do share certain alties and in fact we'll use this pseudo code to define those first highlighted in
yellow here are what henceforth we're going to start calling functions lots of different programming languages exist
but most of them have what we might call functions which are actions or verbs that solve some smaller problem that is
to say you might use a whole bunch of functions to solve a bigger problem because each functions tend to do each
function tends to do something very specific or precise these then in English might be translated in code
actual computer code to these things called functions highlighted in yellow now are what we might call conditionals
conditionals are things that you do conditionally based on the answer to some question you can think of them kind
of like Forks in the road do go left or go right or some other direction based on the answer to some question well what
are those questions highlighted now in yellow are what we would call Boolean Expressions named after mathematician
last name bull that simply have yes no answers or if you prefer true or false answers or Heck if you prefer one or
zero answers we just need to distinguish one scenario from another the last thing manifest in this pseudo code is what I
might highlight now and call Loops some kind of cycle some kind of directive that tells us to do something again and
again so that I don't need a thousand line program to search a thousand page phone book I can get away with a 13 line
program but sort of repeat myself inherently in order to solve some problem
until I get to that last step so this then is what we might call pseudo code and indeed there are other
characteristics of programs that we'll touch on before long things like arguments and return values variables
and more but unfortunately in most languages including some we will very deliberately use in this class and that
everyone in the world world these days still uses these programs tend to look like this this for instance is a
distillation of that very first program I wrote in 19 96 in cs50 itself just to print something on the screen and in
fact this version here just tries to print quote unquote hello world which is dare say the most canonical first thing
that most any programmer ever gets a computer to say just because but look at this mess I mean there's a hash symbol
these angled brackets parentheses words like int curly braces quotes parentheses semicolons and backslashes I mean
there's more overhead and more syntax and clutter than there is an actual idea now that not to say that you won't be
able to understand this before long because honestly there's not that many patterns inde programming languages have
typically a much smaller vocabulary than any actual human language but at first it might indeed look quite cryptic but
you can perhaps infer I have no idea what these other lines do yet but hello world is presumably quote unquote what
will be printed on the screen but what we'll do today after a short break and set the stage for next week is introduce
these exact same ideas and just a bit using scratch something that you yourselves might have used when you're
quite younger but without the same vocabulary applied to those ideas and the upside of what we'll soon do using
scratch this graphical programming language from our friends down the road at MIT it'll let us today start to drag
and drop things that look like puzzle pieces that interlock together if it makes logical sense to do so but without
the distraction of hashes parentheses curly braces angled brackets semicolons and things that are quite beside the
point but for now let's go ahead and take a 10-minute break here and when we resume we will start programming so this
on the screen is a language called C something that we'll dive into next week and thankfully this now on the screen is
another language called python that we'll also take a look at in a few weeks before long along with other languages
along the way today though and for this first week week zero so to speak we use scratch because again it'll allow us to
explore some of those programming fundamentals that will be in C and in Python and in JavaScript and other
languages too but in a way where we don't have to worry about the distractions of syntax so the world of
scratch looks like this it's a web-based or downloadable programming environment that has this layout here by default on
the left here we'll soon see is a pet of puzzle pieces programming blocks that represent all of those ideas we just
discussed and by dragging and dropping these puzzle pieces or blocks over this to Big area and connecting them together
if it makes logical sense to do so will start programming in this environment the environment allows you to have
multiple Sprites so to speak multiple characters things like a cat or anything else and those Sprites exist in this
rectangular World up here that you can full screen to make bigger and this here by default is scratch who can move up
down left right and do many more things too and within it scratches world you can think of it as perhaps a familiar uh
coordinate system with x's and y's which is helpful only when it comes time to like position things on the screen right
now scratch is at the default 0 comma 0 where x equals 0 and Y equals 0 if you were to move the cat way up to the top X
would stay zero y would be positive 180 if you move the cat all the way to the bottom X would stay zero but y would now
be negative 180 and if you went left X would become -240 but y would stay zero or to the right X would be 240 and Y
would stay zero so those numbers generally don't so much matter because you can just move relative ly in this
world up down left right but when it comes time to like uh precisely position some of these Sprites or other imagery
it'll be helpful just to have that mental model of up down left and right well let's go ahead and make perhaps the
simplest of programs here I'm going to switch over to the same programming environment now for a tour of the left
hand side so by default selected here are the category in blue motion which has a whole bunch of puzzle pieces or
blocks that relate to motion and whereas scratch as a graphical language categorizes things by the type of things
that these pieces do we'll see that throughout this whole pet we'll have functions and variables and conditionals
and Boolean expressions and more each in a different color and shape so for instance moving 10 steps or turning one
way or the other would be functions categorized here as things like motion under looks in purple you might have
speech bubbles uh that you can create by dragging and dropping these that might say hello or whatever for some number of
seconds or you could switch costumes change the cat to look like a dog or a bird or anything else in between sounds
too you can play sounds like meow or anything you might import or uh record yourself and then there's these things
scratch calls events and the most important of these is the first when green flag clicked because if we look
over to the right of scratch's world here this rectangular region has this green flag and red stop sign up above
one of which is for play one of which is for stop and so that's going to allow us to start and stop our actual programs
when that green flag is initially clicked but you can listen for other types of events when the space bar is
pressed or something else when this Sprite is clicked or something else and here you already see like a programmer's
incarnation of things you and I take for granted like every day now on our phones anytime you tap an icon or drag your
finger or hit a button on the side these are what a programmer would call events things that happen and are often
triggered by us humans and things that a program be it in scratch or python or C or anything else can listen for and
respond to indeed that's why when you tap the phone icon on your phone the phone application starts up because
someone wrote software that's listening for a finger press on that particular icon and so scratch has these same
things too under control in Orange you can see that we can wait for one second or repeat something some number of times
10 by default but we can change anything in these white circles to anything else there's another puzzle piece here
forever which implies some kind of loop where we can do something again and again and even though it's seems a
little tight there's not much room to fit something there scratch is going to have these things grow and Shrink
however we want to fill similarly shaped pieces and here's those conditionals if something is true or false then do this
this next thing and that's how we can put in this little trapezoid like shape some form of Boolean expression a
question with a yes no true false or one zero answer and decide whether to do something or not you can mess uh combine
these things too if something is true do this else do this other thing and you can even tuck one inside of the other if
you want to ask three or four or more questions sensing too is going to be a thing you can ask questions AKA Boolean
expressions like is the Sprite touching the mouse pointer the arrow on the screen so that you can start to interact
with these programs uh what is the distance between a Sprite and a mouse pointer you can do simple calculations
just to figure out maybe if the the enemy is getting close to the cat under operators some lower level stuff like
math but also the ability to pick random numbers which for a game is great because then you can kind of vary the
difficulty or what's happening in a game without the same game playing the same way every time and you can combine ideas
something and something must be true in order to make that kind of decisions before or we can even join two wors
together says apple and banana by default but you can type in or drag and drop whatever you want there to combine
multiple words into full larger sentences and then lastly down here there's in Orange things called
variables in math we've obviously got X and Y and whatnot in programming we'll have have the same ability to sort of
store in these named symbols X or Y values that we care about numbers or letters or words or colors or anything
ultimately but in programming you'll see that it's much more conventional not to just use Simple letters like X and Y and
Z but to actually give variables full words or word uh singular or plural words to describe what they are and then
lastly if this isn't enough colors of blocks for you you can create your own blocks and indeed this is going to be a
programming principle will apply today and with the first problem set whereby once you start to assemble these puzzle
pieces and you realize oh would have been nice if those several pieces could have just been replaced by one had MIT
fought to give me that one puzzle piece you yourself can make your own blocks by connecting these all together giving
them a name and boom a new puzzle piece will exist so let's do the simplest most canonical programs here starting up with
control and I'm going to click and drag and drop this thing here when green flag clicked and then I'm going to grab one
more for instance under looks and under looks I'm going to go ahead and just say something like initially not just hello
but the more canonical hello comma world now you might guess that in this programming environment I can go over
here now and click the green flag and voila hello comma world so that's my first program and obviously much more
userfriendly than typing out the much more cryptic text that we saw on the screen that you too will type out next
week but for now we'll just focus on these ideas and in this case a function so what is it just that just happened
this purple block here is say that's the function and it seems to take some form of input in the white oval specifically
hello comma World well this actually fits the Paradigm that we looked at earlier of just inputs and outputs so if
I may if you consider what this puzzle piece is doing it actually fits this model the input in this case is going to
be hello comma World in white the algorithm is going to be implemented as a function by m called say and the
output of that is going to be some kind of side effect like the cat and the speech bubble are saying hello world so
already even that simple drag and drop mimics exactly this relatively simple mental model so let's take things
further let's go ahead now and make the program a little more interactive so that it says something like hello David
or hello Carter or hello to you specifically and for this I'm going to go under sensing and you might have to
poke around to find these things the first time around but I've done this a few times so I kind of know where things
are and what color there's this function here ask what's your name but that's in white so we can change the question to
anything we want and it's going to wait for the human to type in their answer and this function called ask is a little
different from the say block which just had this side effect of printing a speech bubble to the screen the ask
function is even more powerful in that after it asks the human to type something in this function is going to
hand you back what they typed in in the form of what's called a return value which is stored ultim timately in by
default this thing called answer this little blue oval here called answer is again one of these variables that in
math would be called just X or Y but in programming we we're saying what it does so I'm going to go ahead and do this let
me go ahead and drag and drop this block and I want to ask the question before saying anything but you'll notice that
scratch is smart and it's going to realize I want to insert something in between and it's just going to move
things up and down I'm going to let go and ask the default question what's your name and now if I want to go ahead and
say hello David or Carter let's just do hello comma cuz I obviously don't know when I'm writing the program who's going
to use it so let me now grab another looks block up here uh say something again and now let me go back to sensing
and now grab the return value represented by this other puzzle piece and let me just drag and drop it here
and notice it's the same shape even if it's not quite the same size things will grow or Shrink as needed all right so
let's now zoom out let me go and stop the old versions because I don't want to say hello world anymore let me hit the
green flag and what's my name all right David enter huh all right maybe I just wasn't
paying close enough attention let me try it again green flag da a enter this seems like a
bug what's the bug or mistake might you think uh yeah yeah we kind of want to combine
them in the same text box and it's you know it's technically a bug because this just looks kind of stupid it's just
saying David after I W for my name I'd like it to say maybe hello then David but it's just blowing past the hello and
printing David but let's put our finger on why this is happening you're right for the solution but what's the actual
fundamental problem and back perfect I mean computers are really darn fast these days it is saying hello
all of us are just too slow in this room to even see it because it's then saying David on the screen so fast as well so
there's a coup of solutions here and yours is spot on but just to poke around you'll see the first example of how many
ways in programming be it scratch or C or python or anything else that there are going to be to solve problems and
we'll teach you over the course of the weeks Sometimes some ways are better relatively than others but rarely is
there a Best Way necessarily because again reasonable people will disagree and what we'll try to teach you over the
coming weeks is how to kind of think through those nuances and it's not going to be obvious at first glance but the
more programs you write the more feedback you get the more bugs that you introduce the more you'll get your
footing with exactly this kind of problem solving so let me try this in a couple of ways up here would be one
solution to the problem MIT anticipated this kind of issue especially with first-time programmers and I could just
use puzzle piece that says say the following for two seconds or one second or whatever then do the same with the
next word and it might be kind of a bit of a pause hello 1 second 2 seconds David 1 second 2 seconds but at least it
would look a little more GR atically correct but I can do it a little more elegantly as you propos let me go ahead
and throw away one of these blocks and you can just drag and let go and it'll delete itself let me go down to
operators because this join block here is the right shape and so even if you're not sure what goes where just focus on
the shapes first let me drag this over here and it grew to fill that let me go ahead and say hello comma space and now
it could just say by default hello banana but let me go back to let me go back to S
drag answer and that's going to drag and drop there and so now notice we're sort of stacking or nesting one block on
another so that the output of one becomes the input to another but that's okay here let me go ahead and zoom out
hit stop and hit play all right what's your name da v d enter and voila now it's presumably as we first intended so
thank you thank you no no minus two this time so consider that even with these uh this
additional example it still fits the same mental model but in a little more interesting way here's that new function
ask something and wait and notice that in this case too there's an input Otherwise Known henceforth as an
argument or a parameter programming speak for just an input in the context of a function and if we use our drawing
as before to represent this thing here we'll see that the input now is going to be quote unquote what's your your name
the algorithm is going to be implemented by way of this new puzzle piece the function called ask and the output of
that thing this time is not going to be the cat saying anything yet but rather it's going to be the actual answer so
instead of the visual side effect of the speech bubble appearing now nothing visible is happening yet thanks to this
function it's sort of handing me back like a a scrap of paper with whatever I typed in written on it so I can reuse
daavid one or more times even like I did now what did I then do with that value we consider that with the subsequent
function with the subsequent function we had this say block two combined with a join so we have this variable called
answer we're joining it with that first argument hello so already we see that some functions like join can take not
one but two arguments or inputs and that's fine the output of join is presumably going to be hello David or
hello Carter or whatever the human typed in and that output notice is essentially becoming the input to another function
say just because we've kind of stacked things or nested them on top of one another but graph or but um but
methodically it's really the same idea the input now or two things hello comma and the return value from the previous
ask function the function now is going to be joined the output is going to be hello David but that hello David output
is now going to become the input to another function namely that first block called say and that's then going to have
the side effect of printing out hello David on the screen so again as sort of sophisticated as ours as yours as others
programs are going to get they really do fit this very simple mental model of inputs and outputs and you just have to
learn to recognize the vocabulary and to know what kinds of puzzle pieces or concepts ultimately to apply but you can
ultimately really kind of spice these things up let me go back to my program here that just is using the speech
bubble at the moment scratch as an aside has some pretty fancy Interac features too I click the extensions button in the
bottom left corner and let me go ahead and choose the um text to speech extension this is using a cloud service
so if you have an internet connection it can actually talk to the cloud or a thirdparty service and this one's going
to give me a few new green puzzle pieces namely the ability to speak something from my speakers instead of just saying
it textually so let me go ahead and drag this and now notice I don't have to interlock them if I'm just kind of
playing around and I want to move some things around I just want to use this as like a canvas temporarily let me go
ahead and steal the join from here put it there let me throw away the SE block by just moving it left and letting go
and now let me join this in so I've now changed my program to be a little more interesting so now let me stop the old
version let me start the new what's your name type in David and voila hello banana okay minus to for real all right
so what I accidentally threw away there uh intentionally for instructional purposes was the actual answer that came
back from the ask block that's embarrassing so now if I play this again let's click the green icon what's your
name David and now hello David there we go hello David all right thank you okay so we have these functions then
in place but what more can we do well what about those condition ials and and loops and other constructs how can we
bring these programs to life so it's not just clicking a button and voila something's happening let's go ahead and
make this now even more interactive let me go ahead and throw away most of these pieces and let me just spice things up
with some more audio under sound I'm going to go to play sound meow until done here we go green
flag okay it's a little loud but it did exactly do what it said let's hear it again okay it's kind of an underwhelming
program eventually since you'd like to think the the cat would just meow on its own but I have to keep hitting the
button well this seems like an opportunity for uh doing something again and again so all right well if I wanted
to meow meow meow let me just grab a few of these or you can even right click or control click and you can copy paste
even in code here let me play this now all right so now like it's not really emoting happiness in quite the
same way it might be hungry or upset so you know let's slow it down let me go to control wait 1 second in between which
might be a little uh less worrisome here we go [Music]
play okay so if my goal was to make the C meow three times I dare say this code or algorithm is correct but let's now
critique its design is this welld designed and if not why not what are your thoughts here uh
yeah yeah sure yeah yeah so yeah agreed I could use forever a repeat but let me push a little harder
but why like this works I'm kind of done with the assignment what do I what's bad about it there's too much repti yeah
there's too much repetition right if I wanted to change the sound that the cat is making to like a different variant of
meow or have it bark instead like a dog I could change it from the drop down here apparently but then I'd have to
change it here and then I'd have to change it here and God if this were even longer that just gets tedious quickly
and you're probably increasing the probability that you're going to screw up and you're going to miss one of the
drop downs or something stupid and introduce a bug or if you wanted to change the number of seconds you're
waiting you've got to change it in two maybe even more places again you're just creating risk for yourself and potential
bugs in the program so I do like the repeat or the forever idea so that I don't repeat myself and indeed what I
alluded to being possible copy pasting earlier doesn't mean it's a good thing and in code generally speaking when you
start to copy and paste puzzle pieces or text next week you're probably not not doing something quite well so let me go
ahead and throw away most of these to get rid of the duplication keeping just two of the blocks that I care about let
me grab the repeat block for now let me move this inside of the repeat Block it's going to grow to fit it let me
reconnect all this and change the 10 just to a three and now [Music]
play so better it's the same thing it's still correct but now I've set the stage to let the cat meow for instance four
times by changing one thing 40 times by changing one thing or I could just use the forever block and just walk away and
it will meow forever instead if that's your goal that would be better a better design but still correct but you know
what now that I have a program that's designed to have a cat meow wow like why I mean MIT invented scratch scratch is a
cat why is there no puzzle piece called meow feels like a missed opportunity now to be fair they gave us all the building
blocks with which we could Implement that idea but but a principle of programming and really computer science
is to leverage what we're going to now start calling abstraction we have step-by-step instructions here the
repeat the play and the weight that collectively implements this idea that we humans would call meowing wouldn't it
be nice to abstract away those several puzzle pieces into just one that literally just says what it does meow
well here's where we can make our own blocks let me go over here to scratch under the pink uh block category here
and let me click make a block block and here I see a slightly different interface where I can choose a name for
it and I'm going to call it meow and I'm going to keep it simple that's it no inputs to meow yet I'm just going to
click okay now just going to clean this up a bit here let me drag and drop play sound and weight over here and you know
what I'm just going to drag this way down here way down here because now that I'm done implementing meow I'm going to
literally abstract it away sort of out of sight out of mind because now notice at top left there is a new puzzle piece
called meow and so at this point I'd argue it doesn't really matter how meow is implemented frankly I don't know how
ask or say was implemented by MIT they abstracted those things away for us now I have a brand new puzzle piece that
just says what it is and this is now still correct but arguably better design why because it's just more readable to
me to you it's more maintainable when you look at your code a year from now for the first time because you're sort
of fondly looking back at the very first program you wrote it says what it does the function itself has semantics which
conveys what's going on if you really care about how meow is implemented you could scroll down and start to Tinker
with the underlying implementation details but otherwise you don't need to care anymore now I feel like there's a
even additional opportunity here for abstraction and to sort of factor out some of this functionality it's kind of
lame that I have this repeat block that lets me call the meow function so to speak use the meow function through
three times wouldn't it be nice if I could just call the meow function AKA use the meow function and pass it an
input that tells the puzzle piece how many times I want it to meow well let me go ahead and zoom out and scroll down
let me right click or control click on the pink piece here and choose edit or I could just start from scratch nope pun
intended with a new one and now here rather than just give this thing a name meow let me go ahead and add an input
here and I'm going to go ahead and type in for instance n for number of times to me now and just to make this even more
userfriendly and self-descriptive I'm going to add a label which has no functional impact it's just an aesthetic
and I'm just going to say times just to make it read more like English in this case that tells me what the puzzle piece
does and now I'm going to click okay and now I need to refine this a little bit let me go ahead and grab under control a
repeat block let me move the play sound and weight into the repeat block I don't
want 10 and I also don't want three here what I want now is This n That is my actual variable that scratch is creating
for me that represents whatever input the human programmer provides notice it snaps right in place let me connect this
and now waa I have an even fancier version of meow that is perimeter IED it takes input that affects Its Behavior
accordingly now I'm going to scroll back up because out of sight out of mind I just care that Meo exists now I can
tighten up my code so to speak use even fewer lines to do the same thing by throwing away the the repeat block
reconnecting this new puzzle piece here that takes an input like three and voila now we're really programming right we've
not made any forward progress functionally the thing just meows three times but it's a better design and as
you program more and more these are the kinds of instincts still start to acquire so that one you can start to
take a big assignment a big problem set something for homework even that feels kind of overwhelming at first like oh my
God where do I even begin but if you start to identify what are the sub problems of a big problem then you can
start making progress and I do this to this day where if I have to tackle some programming related project I'm so easy
to like drag my feet or oh it's going to take forever to start until I just start writing down like a to-do list and I
start to modularize the program and say all right well what do I want this thing to do meowing what's that mean I got to
have it say something on the screen all right uh I need to have it say something on the screen some number of times like
literally a mental or written checklist or pseudo code if you will in English on a piece of paper or text file and then
you can decide okay the first thing I need to do for homework to solve this real world problem I just need a meow
function I need to use a bunch of other code too but I need to create a meow function and boom now you have a piece
of the problem solved not unlike we did with the phone book there but in this case we'll have presumably other
problems to solve all right so what more can we do let's add a few more uh pieces to the puzzle here let's actually
interact with the cat now let me go ahead and now when the green flag is clicked let me go ahead and ask a
question using an event here let me go ahead and say if let's see if the cursor I want to do something like uh implement
the notion of petting the cat so if the cursor is petting touching the cat like here something like this it'd be cute if
like the cat meows like you're petting a cat so I'm going to ask the question when the green flag is clicked if let's
see I think I need sensing uh so if touching Mouse pointer this is way too big but again the shape is fine so there
it goes grew to fill and then if it's touching the mouse pointer that is if the cat to whom this script or this
program anytime I attach puzzle pieces MIT calls them a script or like a program if you will uh let me go ahead
then and choose a sound and say play sound meow until done all right so here it is to be clear when the green flag is
clicked ask the question if the cat is touching the mouse pointer then play that sound meow here we go
play huh all right let's try again play huh I'm worried it's not scratches fault Feels Like Mine what's the bug
here why doesn't this work yeah and Beck yeah who just turned yeah the problem is the moment I
click that green flag scratch asks the question is the cat touching the mouse pointer and obviously it's not cuz the
cursor was like up there a moment ago and it's not down there it's fine if I move the cursor down there but too late
the program already asked the question the answer was no or false or zero however you want to think about it so no
sound was played so what might be the solution here be I could move my my cursor quickly but that feels like never
going to work out right other Solutions here yeah and way back the forever Loop so I could indeed
use this forever Loop because if I want my per to just constantly listen to me well let's literally do something
forever or at least forever as long as the program is running until I explicitly hit stop so let me grab that
let me go to control let me grab the forever block let me move the if inside of this forever block reconnect this go
back up here click the green flag and now nothing's happened yet but let me try moving my cursor
now ah so now that's kind of cute so now the cat is actually responding and it's GNA keep doing this again and again and
so now we have this idea of taking these different ideas these different puzzle pieces assembling them into something
more complicated and I could definitely put a a name to this I could create a custom block but for now let's just
consider what kind of more interactivity we can do let me go ahead and do this by again grabbing a when green flag clicked
let me go ahead and click the video sensing and I'm going to rotate the laptop because otherwise we're going to
get a little Inception thing here where the camera is picking up the camera is up there so I'm going to go reveal to
you what's inside the lect turn here while we rotate this and now that we have a nonv video
backdrop I'm going to say this instead of the green flag clicked actually I'm going to say when the video motion is
greater than some arbitrary measurement of motion I'm going to go ahead and play sound meow until done and then I'm going
to get out of the way so here's the cat and let's put him we'll put him on top on top of there just
okay all right and here we go so my hand is moving faster than 50 something or other whatever the unit of
measure is and we thank you we so now we have even more interactive
version but I think if I sort of slowly right I'm not it's completely creepy but I'm not like
exceeding the threshold until finally my hand moves as fast as that and so here actually is an
opportunity to show you something a former student did let me go ahead here in okay got to stop this let me go ahead
and zoom out of this in just a moment uh if someone would be if someone would be comfortable coming up not only Mass but
also on camera on the internet thought we'd play one of your former classmates projects here up on stage would anyone
like to volunteer here and be up on stage who's that yeah come on down what's your name SAR Sahar all right
come on down let me get it set up for you [Applause]
here all right let me go ahead and full screen this here so this is uh wacka by one of your former predecessors it's
going to use the camera focusing on your head which will have to position inside of this rectangle and if you ever played
the like wack-a-mole game and an arcade okay so for those who haven't like these little moles pop up and with a very
fuzzy Hammer you sort of hit down you though if you don't mind are going to use your head to do this
virtually so let's line up your head with this red rectangle if you could we'll do
beginner all right here we go Sahar give it a moment okay come a little
closer and now hit the moles with your head there we go one point one point Point
nice 15 seconds to go there we go oh yep one point 6
seconds oh no there we go quick all right a round of applause for SAR thank you
so beyond having a little bit of fun here the goal was to demonstrate that by using some fairly simple primitive some
basic building blocks but assembling them in a fun way with some music maybe some new costumes or artwork you can
really bring programs to life but at the end of the day the only puzzle pieces really involved were ones like the ones
I just dragged and dropped and a few more because there were clearly lots of moles so the student probably created a
few different Sprites not a single cap but at least four different moles they had like some kind of graphic on the
screen that showed Sahara where to position head there was some kind of timer maybe a variable that every second
was counting down so you can imagine taking what looks like a pretty impressive project at first glance and
perhaps overwhelming to solve yourself but just think about what are the basic building blocks and pluck off one piece
of the puzzle so to speak at a time and so indeed if we rewind a little bit let me go ahead here and introduce a program
that I myself made back in graduate school when scratch was first being developed by MIT let me go ahead and
open here give me just one second something that I called back in the day Oscar time that looks a little something
like this if I full screen it and hit play so you'll notice piece of trash is falling I can click on it and drag and
as I get close and close to the trash can notice it wants to go in it seems and if I let
go one point here comes another I'll do the same two points there's a sneaker falling from
the sky so another Sprite of some sort I can also get just a little a little lazy and just let them fall into
the trash thems if I want to so you can see it it doesn't have to do with my mouse cursor it has to do apparently
with the distance here let's listen a little further I think there's some additional trash is about to make its
appearance presumably there's some kind of like variable that's keeping track of this
score okay let's see what the last the last chorus here [Music]
issap okay and thus it continues and the song actually goes on and on and on and I do not have fond memories of
implementing this and hearing this song for like 10 straight hours but it's a good example to just consider how was
this program composed how did I go about implementing it the first time around and let me go ahead and open up some
programs now that I wrote in advance just so that we could see how these things are assembled honestly the first
thing I probably did was probably to do something a little like this here is just a version of the program where I
set out to solve just one problem first of planting a lamp post in the program right I kind of had a vision of what I
wanted you know it evolved over time certainly but I knew I wanted trash to fall I wanted a cute little Oscar the
Grouch to pop out of the trash can and some other stuff but wow that's a lot to just tackle all at once I'm going to
start easy download a picture of a lamp post and then drag and drop it into the stage as a costume and boom that's
version one it doesn't functionally do anything I mean literally that's the code that I wrote to do this all I did
was use like the backdrops feature and drag and drop and move things around but it got me to version one of my program
then what might version two be well I considered what piece of functionality frankly might be the easiest to pluck
off next and the trash can that seems like a pretty core piece of functionality it just needs to sit there
most of the time so the next thing I probably did was to open up for instance the trash can version here that looks a
little something now like this so this time I'll show you what's inside here there is some code but not much notice
at bottom right I changed the default cat to a picture of a trash can instead but it's the same principle that I can
control and then over here I added this code when the green flag is clicked switch the costume to something I arbitr
called Oscar one so I found a couple of different pictures of a trash can one that looks closed one that looks partly
open and eventually one that has Oscar coming out and I just gave them different names so I said switch to
Oscar one which is the closed one by default then forever do the following if touching the mouse pointer then switch
the costume to Oscar 2 else switched to Oscar 1 that is to say I just wanted to implement this idea of like the can
opening and closing even if it's not exactly what I wanted ultimately I just wanted to make some forward progress so
here when I run this program by clicking play notice what happens nothing yet but if I get closer to the trash can it
indeed pops open because it's forever listening for whether the Sprite the trash can in this casee is touching the
mouse pointer and that's it that was version two if you will and if I went in now and added the lamp post and composed
the program together now we're starting to make progress right now it would look a little something more like the program
I intended ultimately to create what piece did I probably bite off uh after that well I think what I did is I
probably decided let me Implement one of the pieces of trash not the shoe and the newspaper all at once let's just get one
piece of trash working correctly first and so let me go ahead and open this one and again all these examples will be
available on the course's website so you can see all of these examples too it's not terribly long I just implemented in
advance so we could flip through kind of quickly here's what I did here on the right hand side turned my Sprite into a
piece of trash this time instead of a cat instead of a trash can and I also created with Carter's help a second uh
Sprite this one a floor it's literally just a black line because I just wanted initially to have some notion of a floor
so I could detect if the trash is touching the floor now without seeing the code yet just hearing that
description why might I have wanted the second Sprite and this black line for a floor with the trash intending to fall
from the sky what might I been thinking like what problem might I be trying to solve yeah you don't want the first
Sprite to go through it yeah you don't want the first Sprite to start at the top go through and then boom like you
completely lose it like that would not be a very uh useful thing or it would seem to maybe eat up more and more of
the computer's memory if the trash is just endlessly falling and I can't grab it uh it might be a little traumatic if
you try to get it and you can't pull it back out and you can't fix the program and so I just wanted the thing to stop
so how might I implemented this let's look at the code at left here I have a bit of Randomness like I proposed
earlier exists there's this blue function called go to x comma y that lets me move a spray to any position up
down left right I picked a random X location either here or over here -240 to positive 240 and then a yv value of
180 which is the top and this just makes the game more interesting it's kind of lame pretty quickly if the trash always
falls from the same spot here's just a little bit of Randomness like most any game would have that spices things up
and so now if I click the green flag you'll see that it just Falls nothing interesting is going to happen but it
does stop when it touches the black line because notice what we did here I'm forever asking the question if the
distance of the Sprite the trash is to the floor is greater than zero that's fine change the Y location to NE by neg3
so move it down three pixels down three pixels until the distance to the floor is not greater than zero it is zero or
even negative at which point it should just stop moving moving Al together there's other ways we could have
implemented this but this felt like a nice clean way that logically just made it make sense okay now I got some trash
falling I got a trash can that opens and closes I have a lamp post now I'm you know a good three steps into the program
we're making progress if we consider one or two final pieces something like the dragging of the trash let me go ahead
and open up this version too uh dragging the trash requires a different type of question let me zoom in here here's the
piece of trash I only need one Sprite no floor here because I just want the human to move it
up down left right and the human's not going to physically be able to move it outside of the world and if we zoom in
on this code the way we've solved this is as follows we're using that and conjunction that we glimpsed earlier
because when the green flag is clicked we're forever asking this question or really these questions plural if the
mouse is down and the cat or sorry the trash is touching the mouse pointer that's equivalent logically to clicking
on the trash go ahead and move the trash to the mouse pointer so again it takes this very familiar idea that you and I
take for granted every day on Macs and PCs of clicking and dragging and dropping how is that implemented well
mac o Mac OS or windows are probably asking a question oh for every icon is the mouse down and is the icon touching
the mouse if so go to the location of the mouse forever while that Mouse button is clicked down so how does this
work in reality now let me go ahead and click on the play nothing happens at first but if I click on it I can move it
up down left right it doesn't move thereafter so I now need to kind of combine this idea of dragging with
falling but I bet I could just start to use just one single program right now I'm using separate ones to show
different ideas but now that's another bite out of the problem and if we do one last one something like the scorekeeping
is interesting cuz recall that every time we dragged a piece of trash into the can Oscar popped out and told us the
current score so let me go ahead and find this one Oscar variables and let me zoom in on this one
and this one is longer because we combined all of these elements so this is the kind of thing that if you looked
at at first glance like I have no idea how I would have implemented this from nothing from scratch literally but again
if you Vision take your vision and componentize it into these smaller bite-size problems you could take these
baby steps so to speak and then solve everything collectively so what's new here here is this bottom one forever do
the following if the trash is touching Oscar the other Sprite that we've now added to the program change the score by
one this is an orange and indeed if we poke around we'll see that orange is a variable like an X or a y but with a
better name changing it means to add one or if it's negative subtract one and then go ahead and have the trash go to
pick random what what is this all about well let me let me show you what it's doing and then we can infer backwards
let me go ahead and hit play all right it's falling I'm clicking and dragging it I'm moving it over and I'm Letting Go
all right let me do it once more letting go let me stop why do I have this function at the end called go to X and Y
randomly like what problem is this solving here yeah in way back yeah yeah exactly even though the human
perceives this is like a lot of trash falling from the sky it's actually the same piece of trash just kind of being
magically moved back to the top as though it's a new one and there too you have this idea of reusable code if you
were constantly copying and pasting your pieces of trash and creating 20 pieces of trash 30 pieces of trash just because
you want the game to have that many levels probably doing something wrong reuse the code that you wrote reuse the
Sprites that you wrote and that would give you not just correctness but also a better design well let's take a look at
one final set of building blocks that we can compose ultimately into something particularly interactive as follows let
me go ahead and zoom out here and let me propose that we Implement something like um like some kind of maze based game and
let me go ahead here so I want to implement some maze-based game that looks at first glance like this let me
hit play it's not a very fun game yet but here's a little Harvard Shield a couple of black lines this time vertical
instead of horizontal but notice you can't quite see my hand here but I'm using my arrow keys to go down to go up
to go left to go right but if I keep going right right right right right right right it's not going anywhere and
left left left left left left left left left left left left it eventually stops so before we look at the code how might
this be working what kinds of scripts collections of puzzle pieces might collectively help us implement this what
do you think perfect yeah there's probably some question being asked if touching the
black line and it happens to be a couple of Sprites Each of which is just literally a vertical black line we're
probably asking a question like are you touching it or is the distance to it zero or close to zero and if so we just
ignore the up down left or rather we ignore the left or the right arrow at that point so that works but otherwise
if we're not touching a wall what are we probably doing instead forever here how is the moving working presumably yeah
and back are you might are you scratching okay sure let's go sorry say a little
louder exactly it's continually forever looking or listening for the arrow keys up down left right and if the up arrow
is pressed we're probably changing the Y by a positive value uh if the down arrow is pressed We're Going Down by Y and
left and right accordingly so let's actually take a quick look if I zoom out here and take a look at the code that
implements this there's a lot going on at first glance but let's see first of all let me drag some stuff out of the
way because it's kind of overwhelming at first glance especially if you for instance were poking around online as
for problem set zero just to get inspiration most projects out there are going to look overwhelming at first
glance until you start to wrap your mind around what's going on but in this case we've implemented some abstractions from
the get-go to sort of explain to ourselves and to anyone else looking at the code what's going on this is that
program with the two black lines and the Harvard Shield going up down left and right it initially puts the shield in
the middle 0 comma 0 it then forever listens for keyboard as I think you were describing and it feels for the walls as
I think you were describing now how is that implemented don't know yet these are custom blocks we created as
abstractions to kind of hide those implementation details because honestly that's all I need to know right now but
as aspiring programmers if we're curious now let's scroll down to the actual implementation of listening for keyboard
this is the one on the left and it is a little long but it's a lot of similar structure we're doing the following if
the up arrow is pressed then change by y by one go up if the down arrow is pressed then change by by negative one
go down right arrow left arrow and that's it so it just assembles all of those ideas combines it into one new
block just cuz it's kind of overwhelming let's just implement it once and tuck it away and if we scr scroll now over to
the feel for walls function this now is asking the question as hypothesize if I'm touching the left wall change my x
value by one sort of move away from it a little bit if I'm touching the right wall then move X by negative one to move
a little bit away from it so it kind of bounces off the wall just in case it slightly went over we keep the crest
within those two walls all right so then a couple of more pieces here to introduce what if we want to actually
add some kind of adversary or opponent to this game well let me go ahead to um maybe this one here where the adversary
in this game might for instance be designed to be bouncing to stand in your way if this is like a maze and you're
trying to get the Harvard shield from the bottom to the top or vice versa uhoh Yale is in the way and it seems to be
automatically bouncing back and forth here well let me ask someone else I hypothesize how is this working this is
an idea you have this is an idea you see let's reverse engineer in your head how it
works how might this be working yeah and back yeah so if the Yale symbol is touching the left wall or the right wall
we somehow have it bounce and indeed we'll see there's a puzzle piece that can do exactly that technically off the
edge as we'll see but there's another way we can do this and let's look at the code the way we ourselves can Implement
exactly that idea bounce is just with a little bit of logic so here's what this version of the program's doing it's
moving Gale by default to 0 just to arbitrarily put it somewhere pointing it Direction 90° which means just
horizontally essentially and then it's forever doing this if touching the left wall or touching the right wall here's
our translation of Bounce we're just turning 180° and the nice thing about that is we don't have to worry if we're
going from right to left or left to right 18 180° is going to work on both of the walls and that's it after we do
that we just move one step one pixel at a time but we're doing it forever so something is happening continually and
the Yale icon is bouncing back and forth well one final piece here what if now we want a more uh uh another adversary a
more advanced adversary down the road for instance to go and follow us wherever we are such that this time we
want the other Sprite to not just bounce back and forth but literally follow us no matter where we go how might this be
implemented on the screen I bet it's another forever block but what's inside yeah forever point at the
location of the Harvard shield and go one step toward it this is just going to go on forever if I just give up at least
in this version notice it's B it's sort of twitching back and forth because it goes one pixel then one pixel then one
pixel it's sort of in a frantic State here we haven't finished the game yet but if we see inside we'll see exactly
that it didn't take much to implement this simple idea go to a random position just to make it kind of fair initially
then forever Point towards Harvard which is what we call the Harvard Crest spray move one step suppose we now wanted to
make a more advanced level what's a minor change I could logically make to this code just to make MIT even better
at this all right change the number of steps to two so let's try that so now
they got twice as fast let me go ahead and just get this out of the way oops let me make it a fair fight green flag
all right I unfortunately am still moving one pixel at a time so this isn't going to end well it caught up to me and
if we're really aggressive and do something like 20 steps at a time click the green flag Jesus okay so that's how
you might then make your levels progressively harder and harder so it's not an accident that we chose these
particular examples here involving these particular schools because we have one more demonstration we thought we'd
introduce today if we could get one other volunteer to come up and play what was called by one of your predecessors
Ivy's hardest game let's see who in the middle do you want to come on up what's your
name say again come a little closer actually and say sorry hard to hear here all right a round of applause here if we
could too okay sorry what was your name Celeste ceste Celeste Celeste come on over nice
to meet you too so here we have on this other screen Ivy's hardest game written by a former cs50 student I think you'll
see that it combines these same principles the maze is clearly a more advanced the goal at hand is to
initially move the Harvard Crest to the Sprite all the way on the right so that you catch up to him in this case but
you'll see that there's different levels and different in uh levels of sophistication so if you're up for it
you can use just these arrow keys up down left right you'll be controlling the harbard Sprite and if we could raise
the volume just a little bit we'll make this our final example here we go clicking the green flag
[Music] [Applause] [Music]
[Applause] [Music] [Music]
[Music] [Music] [Music]
[Music] [Music] [Music]
[Music] all right that's it for cs50 Welcome to the class we'll see you next time
[Music] [Music] all right this is cs50 and this is week
one the one in which you learn a new language which is something we technically said last week at least if
you had never played with this graphical language known as scratch before which itself was a programming language but
today as promised we transition to something a little more traditional a little more text based not puzzle piece
or block based known as C this is an older language it's been around for decades but it's a language that
underlies so many of today's more modern languages among them something called python that we'll also come to in a few
weeks time indeed at the end of the semester the goal is free to feel that you've not learned scratch you've not
learned C or even python for that matter but fundamentally that you've learned how to program unfortunately when you
learn how to program with a more traditional language like this there's just so much distraction last week I
described all of the syntax all of the weird punctuation that you see in this like the hash symbol these angled
brackets parentheses curly braces backs slash and and more well today we're not going to reveal what all of those little
particulars mean but by next week will this no longer look like the proverbial Greek to you a language that presumably
you've never actually seen or typed before but to do that we'll explore some of the very same topics as last week so
weall that by a scratch and presumably VI a problem set one we took a look at things called functions that are actions
or verbs and related to functions where arguments like inputs and related to some functions where return values like
outputs then we talked a bit about conditionals Forks in the road so to speak Boolean Expressions which are just
yes no questions or true false questions Loops which let you do things again and again variables like in math that let
you store values temporarily and then even other topics still so if you were comfortable on the heels of problems at
zero in last week realize that all of these topics are going to be remain with us so really today is just about
acquiring all the more of a mental model for how you translate those ideas into presumably a very cryptic new syn a new
syntax frankly that's actually more simple in some ways than your own human language be it English or something else
because there's far fewer vocabulary words there's actually far less syntax that you might have in say a typical
human language but you need to be with these computer languages all the more precise so that you're most uh
ultimately correct and ultimately we'll see too your code is successful along a few other lines as well so if you think
about like the last time you kind of wandered around not really knowing what you were doing or encountered something
new might not have been that long ago entering Harvard Yard for the very first time or old campus or the like be it in
Cambridge or New Haven you know you didn't really need to know how to do everything as a first year you didn't
need to know who everyone was where everything was how Harvard or Yale or anything else for that matter worked you
sort of got by data Day by just focusing on those things that matter and anything you didn't really understand you sort of
turned a blind eye to until it's important and that's indeed what we're going to do today and really for the
next several weeks we'll focus on details that are initially important and try to wave our hands so to speak at
details that yeah eventually we'll get to might be interesting but for now they might be distractions and by
distractions I really mean some of that syntax to which I alluded earlier so by the end of today and really by the end
of problem set one your first Fay presumably into this language called C you'll have written some code and you'll
be asking yourself We'll be asking yourselves just how good is that code well first and foremost per last week be
it in scratch or phone book form like code ultimately needs to be correct to be Well Done Right you want the problem
to be solved correctly so that one sort of goes without saying and along the way this term will provide you with tools
and techniques so you don't have to just sit there sort of endlessly trying an input checking the output trying another
input checking the output there's a lot of automation tools in the real world and in this class and others like it
that'll help facilitate you answering that question for yourself is my code correct according to our specifications
or the like but then something that's going to take more time and you're probably not going to feel 100%
comfortable with the first week the first weeks is just how welld designed your code is it's one thing to sort of
speak English or write English but it's another thing or any language for that matter but it's another thing to speak
it or write it well and we spent all these years in middle school high school presumably writing papers and other
documents getting grades and feedback on them as to how well formulated your arguments were how well structured your
paper was and the like and there's that same idea in programming it doesn't matter necessarily that you've just
solved the program uh a problem correctly if your code is a complete visual mess or if it's crazy long it's
going to be really hard for someone else to wrap their mind around what your code is doing and indeed to be confident if
it is correct and honestly you the next morning the next year uh the uh next time you look at that code might have no
idea what you yourself were even thinking but you will if you focus too on designing good code getting your
algorithms efficient getting your code nice and clean and even making sure your code looks pretty which would describe
as a matter of style so in the sort of written human world you know having punctuation in the right place
capitalization and the like the sort of way you write an essay but not necessarily send a text message relates
to style for instance and so good style and code is going to have a few of these characteristics that are pretty easily
taught and remembered but you just have to start to get in the habit of writing code in a certain way so these three
axes so to speak correctness design and style are really the overarching goals when writing code that ultimately is
going to look like this so this program we conjectured last week does what if you run it on a Mac or PC or
somewhere else presumably what does it do yeah it just prints hello world and
honestly that's kind of atrocious that you need to hit your keyboard keys this many time with this cryptic syntax just
to get a program to say hello world so a spoiler in a few weeks time when we introduce other more modern languages
like python you can distill this same logic into literally one line of code and so we're getting there ultimately
but it's it's helpful to understand what what it is that's going on here CU even though this is a pretty cryptic syntax
there's nothing after this week and really next week that you shouldn't be able to understand even about something
that right now looks a little something like this so how do you write code well I've given us sort of the answer to a
problem how do you print hello world on the screen so what do I do with this code well we're in the habit of
typically writing things with like Microsoft Word or Google documents and yeah I could open up word or Google Docs
or Pages or the like and just literally transcribe that character for character save it and boom I've got a program but
the problem per last week is that computers only understand or speak what other language so to
speak yeah so binary zeros and ones and so this obviously is not zeros and on so it doesn't matter if I put it in a word
doc gooogle doc Pages file or the like the computer's not going to understand it until I somehow translate it to zeros
and ones and honestly none of those tolls that I rattled off are really appropriate for programming why well
they come with features like bold facing and italics and sort of fluffy aesthetic stuff that has no functional impact on
what you're trying to do with your code and they don't have the ability it would seem to convert that code ultimately to
zeros and ones but tools that do have this capability might be called integrated development environments or
idees or more simply text editors a text editor is a tool that a programmer uh uses perhaps every day to write their
code and it's a simple program here for instance a very popular one called Visual Studio code or VSS code and at
the top here you see that I've actually created in advance before class A very simple empty file called hello. C why
well C indicates by convention that this is going to be a file in which there is C code it's not docx which would mean in
this file is a Microsoft Word document or pages is a Pages file this is do c which means in this file is going to be
text in the language called C this number one here is just sort of an automatic line number that's going to
help me keep track of how long or short this program is and the cursor is just blinking there waiting for me to start
typing some code well let me go ahead and type out exactly the same code for me it comes pretty comfortably from
memory so I'm going to go ahead and include something called standard io. more on that later I'm going to sort of
magically type int main void whatever that means we'll come back to that later one of these curly braces and then a
sibling there that closes the same then I'm going to hit tab to indent a few spaces and then I'm going to type not
print but print F then hello comma world back SL n close quote close parenthesis semicolon and I dare say this was
essentially the very first program I wrote some 25 years ago I wrote it to say hi cs50 now it just says the more
canonical conventional hello world but that's it that's my very first program and all I need to now do is maybe hit
command s or contr S to save the file and voila I am a programmer the catch though is like okay how do I run this
like on your Mac or PC how do you run a program well usually double click an icon on your phone you tap an icon in
this environment that we're using and that many programmers dare say most programmers use you don't have
immediately a nice pretty icon to double click on that's very user friendly but it's not very necessary especially when
you get more comfortable with programming you're going to want to type commands because it's just faster than
pointing and clicking a mouse and you're going to want to automate things which is a lot easier if it's all command or
text based as opposed to Mouse and and mus muscular movements and so here I have my program lives in this file
called hello.c I need to now convert it though to zeros and ones well how do I go about doing this and how am I going
to get from those uh this so-called code or source code as it's conventionally called to this these zeros and ones that
we'll now start calling machine code the zeros and ones from last week can be used not only to represent numbers and
letters colors uh audio video and more it can also represent instructions to a computer like print or play a sound or
delete a file or save a file all the sort of basics of a computer somehow can be represented by other patterns of
zeros and ones and just like last week it depends on the context in which these numbers are stored sometimes they're
interpreted as numbers like in a spreadsheet sometimes they're interpreted as colors sometimes they're
interpreted as instructions commands to your computer to do very low-level operations like print something on the
screen so fortunately like last week's definition of like computer science of problem solving is a nice mental model
for exactly the goal at hand I have some input AKA source code I want to Output ultimately machine code those zeros and
ones I certainly don't want to do this kind of process by hand so hopefully there's an algorithm implemented by some
special program that does exactly that and those of you who do have some prior experience this program might be called
a a compiler so a few of you have indeed programmed before not all languages use compilers see in fact is a language that
does use a compiler and so I just need to find myself on my computer somewhere presumably a so-called compiler a
program whose purpose in life is to convert one language to another and source code written textually in C like
we saw a moment ago is source code the machine code is the corresponding zeros and ones so let me go back to the same
programming environment called Visual Studio code or VSS code this is typically a program you or any
programmer on the internet can download onto their own Mac or PC and be on their way with whatever computer you're own
writing some code a downside though of that approach is that all of us have slightly different versions of Macs or
PCS we have slightly different versions of operating systems they may or may not be up to date it's just sort of a
technical support nightmare to create a uniform environment especially for like an introductory class where everyone
should ideally be on the same page so we can get you up and running quickly and so I'm actually using a a cloud-based
version of vs code something that you only need a browser to access and then you can be on any computer today or
tomorrow by the end of the semester we're going to get you out of the cloud so to speak as best we can and get you
onto your own Mac or PC so that after this class especially if it's the only CS class you ever take you feel like you
can continue programming in any number of languages even with cs50 behind you but for now wonderfully the browser
version of es code should pretty much be identical to what the eventual downloadable vers vers of the same would
be and you'll see in problem set one how to access this and how to get going yourself with your first programs but I
haven't mentioned this bottom part of the screen this bottom part of the screen and this is an area where we have
what's called a terminal window so this is sort of old school technology that allows you with a keyboard to interact
with a computer wherever it may be on your lap in your pocket or even in this case in the cloud so on the top hand
portion of this screen is my code my text editor like tabed Windows like in many programs where I can just create
files and write code the bottom of the screen here my so-called terminal window gives me the ability to run commands on
a server that currently I have exclusive access to so because I logged into VSS code with my account online I have my
own sort of virtual server if you will in the cloud otherwise known as in this context a container this has its own
operating system for me its own hard drive if you will where I can save and create file of my own separate from
yours and vice versa and it's at this very simple prompt which is conventionally but not always
abbreviated by a dollar sign has nothing to do with currency it just means type your commands here this is where I'm
going to be able to type commands like compile my source code into machine code so it's a command line interface or
CLI on top of an operating system that you might not have ever used or seen but it's very popular called Linux odds are
almost all of us in this room are using Mac Os or Windows right now but we're all going to start using an operating
system called Linux which is in a family of operating systems that offer not only this command line interface but are used
not just for programming but for serving websites and developing applications and the like and it's indeed uh a familiar
and very powerful interface as we'll see so how do I go about making this file hello.c into a program there's no double
there's no icon to double click but there is a command I can type make hello at this dollar sign prompt go ahead and
hit enter and nothing appears to happen but that's a good thing and as we'll see in programming almost always if you
don't see anything go wrong that means everything went right so this is going to be a rarity at first but this is a
good thing that it just seems to do nothing but now there is in the folder in my account in this on the cloud a
file called hello and it's a bit of a weird command but you'll get familiar with it before long dot just means go
into my current folder SL Hello means run the program called hello in this current folder so/ hello
and then enter and voila now I'm actually not just programming but running my actual code so what have I
just done let me go ahead and do this I'm going to go ahead and open up the sidebar of this program and you'll see
in problem set one how to do this and this might look a little different based on your own configuration even the color
scheme I'm using might ultimately look different from yours cuz it's support it's nice colorful theme so you can have
different colors and uh brightnesses depending on your mood or the time of day what I've opened here though is what
is called in vs code Explorer and this is just all of the files in my cloud account and there's not many right now
there's only two one is the file called hello.c and it's highlighted because I've got it open right there and the
other is a file called hello which is brand new and was created when I ran that command and what's now worth noting
is that now things are getting a little more like Mac OS and windows like on the left hand side you have a guey a
graphical user interface but on the bottom here again you have a CLI command line interface these are just different
ways to interact with computers and you'll get comfortable with both and honestly you're certainly familiar and
comfortable with goys already so it's the command line one with which we'll spend some time now suppose that I just
wanted to do something more than compile this program suppose I wanted to go ahead and remove it like uhuh no I made
a mistake I want to say hello cs50 not Hello World I could just just hover up here like in any software and I could
rightclick and I could poke around and there delete permanently so most of us might have that instinct on a Mac or PC
you right click or control click and you poke around but in a command line interface let me do this instead the
command for removing or deleting a file in the world of Linux this other operating system is just to type RM for
remove and then hello enter it's a somewhat cryptic confirmation message but this just means are you sure I'm
going to go ahead and type why for yes and now when I hit enter Watch What Happens at top left in the Explorer the
goey the graphical interface voila it disappears right not terribly exciting but this just means this is a graphical
version of what we're seeing here and in fact if you want to never use the guey again I'll go ahead and close it with a
keyboard shortcut here you can forever just type LS for list and hit enter and you will see in the command line
interface all of the files in your current folder so anything you can with the mouse you can do with this command
line interface and indeed we'll see many more things that you can do as well but the inventors of this and it's uh this
operating system it's his predecessors were very succinct like the command is RM for remove the command is LS for list
it's very tur why cuz ah it's just faster to type so before we Forge ahead with making something more interesting
than just hello world let me pause here to see if there's questions on source code or machine code or compiler or this
command line interface yeah really good question and let me
recap if I were to make changes to the program run it and then maybe make other changes and try to rerun it would those
changes be reflected even though I've rewarded slightly well let's do this I already removed the old version so let
me go ahead and point out that if I do/ hello now I'm going to see some kind of error because I just deleted the file no
such file or directory so it's not terribly user friendly but it's saying what the problem is is let me go ahead
and remake it by typing make hello now if I type LS I'll see not one but two files again and one of them is even
green with a little asterisk to indicate that it's executable it's sort of the textual version of something you could
double click in our human world so now of course if I run hello we're back where I started hello world but now
suppose I change it to hello comma cs50 like I did years ago let me go ahead and save the file with command s or controls
down here now let me run /hello again and voila huh so let me ask someone else to answer that question what's the
missing step why did it not say hello cs50 yeah yeah so you didn't I didn't compile
it again so sort of newbie mistake you're going to make this mistake and many others before long but now let me
go ahead and remake hello enter it's going to seemingly make uh the same program but this time when I run it it's
hello cs50 all right any other questions on some of these building blocks and we'll
come back to all the crazy syntax I typed before long but for now we're focusing on just the output
yeah uh when I keep running make it creates a new version of the machine code so it keeps changing the hello
program in the hello file and that's it there's no make file per se ah good question no if I open up that
directory you'll see that there's just the one and it doesn't matter how many times I run make hello through 3 4 5
it's just keeps overwriting the original so it's kind of like just saving in the world of Google docs or Microsoft Word
or the like but there's an additional step today we have to then convert my words to the computers the zeros and
ones yeah in front ah what happens if I run hello. C so let me go ahead and do/ hello.c which
is a mistake you'll invariably make early on permission denied so what does that mean this is where the error
messages mean something to the people who design the operating system but it's a little cryptic it's not that you don't
have access to the file it means that it's not executable this is not something you have permission to run but
you do have permission to read or write it that is change it ah really good question so if I have
named my file hello. C or more generally something. c one of the things that make does is it automatically picks the file
name for me and we'll discuss a bit we'll discuss this a bit more next week make it itself is kind of the first of
White Lies today itself is not a compiler it's a program that knows how to find and use a compiler on the system
and automatically create the program if I use as we'll discuss next week the actual compiler myself I have to type a
much longer sequence of commands to specify explicitly what do I want the name of my program to be make is a nice
program especially in week one because it just automates all of that for us and so here we have now a program that very
simply prints something on the screen so let's now put this this into the context of where we left off last time in the
context of scratch and inputs and outputs so we discussed last time of course functions and arguments functions
again are those actions and verbs like say or ask or the like and the arguments were the inputs to those functions
generally in those little white ovals that in scratch you could type words or numbers into we'll see in all of the
languages we're going to see this term have that same capability and let's just start to translate one of these things
to another so for instance let's put this same program in C in the context of scratch this is what hello world looked
like last week in the form of one function this week of course it looks like prints and then the parentheses
notice are kind of deliberately designed in the world of scratch to resemble that same shape even though this is a white
oval you kind of get that um it's uh it's kind of evoking that same idea with the parenthesis technically the function
in C it's not called say it's not even called print it's called print f F the F stands for formatted but we'll see what
that means in a moment but print f is the closest analogous function for say in the world of C notice if though you
want to print something like hello world or hello cs50 in C you don't just write the words as we did last week you also
had to add what if you notice already what's missing from this version yeah so the double quotes on the left and the
right so that's necessary in C whenever you have a a string of words and I'm us using that word deliberately whenever
you have multiple words like this this is known as a string as we'll see and you have to put it in double quotes not
single quotes you have to put it in double quotes there's one other stupid thing that we need to have in my C code
in order to get this function to do something ultimately which is what semicolon so just like in our human
world you eventually got into the habit of using at least in formal writing periods semicolon is generally what you
use to finish your thought in the world of programming with C all right so we have that function in place now what
does this really fit into in terms of the mental model while functions take arguments and it turns out functions can
have different types of outputs and we've actually seen both already last week one type of output from a function
can be something called a side effect and it generally refers to something visual like something appearing on the
screen or a sound playing from your computer it's sort of a side effect of the function doing its thing and indeed
last week we saw this in the context of passing in something like hello world as input to the save function and we saw on
the screen hello world but it was kind of a one-off it's it's one and done you can't actually do anything with that
visual output other than consume it visually with your human eyes but sometimes recall last week we had
functions like the ask block that actually returned me some value remember the ask what's your name it handed me
back whatever answer the human typed in it didn't just arbitrarily display it on the screen the cat didn't necessarily
say it on the screen it was stored instead in that special variable that was uh called answer because some
functions have not side effects but return values they hand you back an output that you can use and reuse unlike
the side effect which again displays and that's it you can't sort of catch it and hold on to it so in the context of last
week we had the ask block and that had this special answer return value in C we're going to see in just a moment we
could translate this as follows the closest match I can propose for the ask block is a function that we're going to
start calling get string string is again a word a set of words like a phrase or a sentence in programming it two is a
function in so far as it takes input and pretty much this isn't always true but very often when you have a word in C
followed by an open parenthesis and a closed parenthesis it's most likely the name of a function and we're going to
see that there's some exceptions to that but for now this indeed looks like a function because it matches that pattern
if I want to ask the question what's your name question mark and I'm even going to deliberately put a space there
just to kind of move the cursor a little bit over so that the human isn't typing literally after the question mark so
that's just a nitpicky aesthetic this is perhaps the closest analog to just asking that question but because the ask
block returns a value the analog here for get string is that it to returns a value it doesn't just print the human's
input it hands it back to you in the form of a variable AKA a return value that I can then use and reuse now
ideally it would be as simple as this literally saying answer on the left equals and this is where things kind
start to diverge from math and sort of our human world this equal sign henceforth is not the equal sign it is
the assignment operator to assign a value means to store a value in some variable and you read these things
weirdly right to left so here is a function called get string I claim that it's going to return to you whatever the
human types in is their name it's going to get stored over here on the left because of this so-called assignment
operator that yes is an equal sign but it doesn't mean equality in this context it makes things equal but it does so by
copying the value on the right into the thing on the left unfortunately we're not quite done yet with c and this is
where again it gets a little Annoying at first where I scratch just let us express ressor ideas without so much
syntax in C when you have a variable you don't just give it a name like you did in scratch you also have to tell the
computer in advance what type of value it is storing string is one such type of value int for integer is going to be
another and there's even more than that that we'll see today and Beyond and this is partly an answer to the question that
came up one or more times last week which was how does a computer distinguish this pattern of zeros and
ones from this like is this a letter a number a color a piece of video and I just claimed last week that it totally
depends on the program it depends on the context and that's true but within those programs it often depends on what the
human programmer said the type of the value is if this specifies it's a string which means interpret the following
zeros and ones that are stored in my program as words or letters more generally if it said int for integer it
would be implying by the programmer treat the following zeros and ones in my program as a number an integer not a
string so here's where this week unlike with scratch which just kind of figures out what you mean with see in a lot of
languages you have to be this pedantic and tell it what you mean there's still one stupid thing missing from my code
here what's still missing here yeah and we still need the stupid semicolon and I'm sort of imputing it here because
honestly these are the kinds of stupid mistakes you're going to make today tomorrow this weekend next week a few
weeks from now until you start to notice this and recognize it as well as you do English or whatever your uh spoken
language is Yeah question good question suppose I mix apples and oranges so to speak and I try to put a string in an
INT or an INT in a string the compiler is going to complain so when I run that make Command as I did earlier it's not
going to be nice and blissfully quiet and just give me another prompt it's going to yell at me with honestly a very
cryptic looking error message until we get the muscle memory for reading it other questions
ah what happened to the back slash n so we'll come back to that in just a moment if we may because I have deliberately
omitted it here but we did have it earlier and we'll see the different behavior in a sec other
questions yeah not at all nitpicky these are the kinds of things that just matter and it's going to take time to recognize
and develop this muscle memory everything I've typed here except for the W at the moment is lowercase and the
W is capitalized just because it's English everything else is lowercase and this kind of varies by language and also
context so in many languages the convention is to use all lowercase letters for your variable names other
languages might use some capitalis as well but we'll talk about that before long but this is the kind of thing that
matters and is hard to see at first especially when a little s doesn't look that different you know when it's on
your tiny laptop screen from a capital S but you'll start to develop these instincts all right so besides this
particular block let's go ahead and consider how we can go about implementing this now in code so let me
switch back to VSS code here this was the program I had earlier and let me go ahead and undo my cs50 change and this
time just rerun it rerun make on hello with the original version with the back slash n enter nothing bad seems to have
happened so/ hello enter hello world now if you're curious this is a good instinct to start to acquire what
happens if I get rid of this well I'm probably not going to break things too badly so let's try let me go ahead now
and do make hello still compile so it's not a really bad mistake so let me go ahead and run/
hello what's the difference here yeah what do you see that's different yeah the dollar sign my
so-called prompt stayed on the same line why well we can presumably infer now that the back sln is some fancy notation
for saying create a new line move the cursor so to speak to the next line notice that the cursor will move to the
next line in my terminal window if I keep hitting it it just automatically by nature of hitting enter does it but it'd
be kind of stupid if when you run a program in this world simple as it is if like the next command is now weirdly
spaced in the middle of the terminal with the Dollar on it just looks sloppy right that's it's really just an
aesthetic argument and notice that it's not acceptable or correct to do this to hit enter there let me go ahead and save
that though and see what happens let me go ahead now and run uh make hello enter oh my God like four errors this is like
what 10 lines of Errors for like a oneline program and this is where again you'll start to develop the instincts
for just reading this stuff these kinds of tools like the compiler tool we're using were not designed necessarily with
user friendliness in mind that's changed over the decades but certainly early on it's really just meant to be correct and
precise with its errors so what did I do here missing terminating close quote character long story short when you have
a string in C your double quotes just have to be on the same line just because now there's the slight white lie there's
ways around this but the best way around it is to you this use this so-called escape sequence to escape something
means generally to put a backslash and then a special symbol like in for new line and this is just the agreed upon
way that humans decades ago decided okay you don't just hit your uh Enter key you instead put back /n and that tells the
computer to move the cursor to the new line so again kind of but once you know it like that's it it's just another uh
word in our vocabulary so now let me transition to making my program a little more interactive instead of just saying
hello world let me change it like last week to say hello David or whoever's interacting with the program so I'm
going to do string answer gets get string quote unquote what's your name I'm not going to bother with a new line
here I could this is now just a judgment call I I deliberately want the human to type their name on the same line just
because and how do I now print this well last week recall we used say and then we used the other block called join so the
idea here is the same but the syntax this week is going to be a little different it's going to be printf which
prints something on the screen I'm going to go ahead and say hello comma and let me just go with this initially with the
back sln semicolon let me go ahead and re compile my code whoops huh damn doesn't work still and look at all these
errors like there's more errors than code I wrote but what's going on here well this
is actually something a mistake you'll see somewhat often at least initially and let's start to glean what's going on
here so here if I look at the very first line of output after the dollar sign so even though it uh jumped down the screen
pretty fast I wrote make hello at the dollar sign prompt and then here's the first error on hello.c line five
technically character five but generally line is enough to get you going there's an error use of Undeclared identifier
string did you mean standard in so I didn't and this is not an obvious solution at first but you'll start to
recognize these patterns in error messages it turns out that if I want to use string I actually have to do this I
have to include another Library up here another line of code rather called cs50.h we'll come back to what this
means in just a moment but if I now retroactive ly say all right what does standard IO do for us up here before I
added that new line what is standard IO doing well if you think back to scratch there were a few examples with like the
camera and with the speech to uh the text to voice remember I had to poke around in like the extensions button and
then I had to load it into scratch it didn't come natively with scratch C is quite like that some functions come with
the language but in for the most part if you want to use a function an action or verb like printf you have to load that
extension so to speak that more traditionally is called a library so there is a standard IO Library stdo
standard IO where IO just means input and output which means just like in mit's World there was an extension for
doing text to voice or for using your camera in C there's an extension AKA a library for doing standard input and
output and so if you want to use any functions related to standard input and output like keybo text from a keyboard
you have to include standard io. and you have to then can you use print def same goes here get string it turns out is a
function that cs50 wrote some time ago and on as we'll see over the coming weeks it just makes it way easier to get
input from a user C is very good with printf at printing output on the screen C makes it really annoying and hard as
we see in a few weeks to just get input from the user so we wrote a function called get string but the only way you
can use that is to load the extension AKA load the library called cs50 and we'll come back in time like why is it h
why is it a hash symbol but for now standard IO is a library that gives you access to printf and input and output
related stuff cs50 is a second library that provides you with access to spe functions that don't come with C that uh
include something like get string so with that said we've now kind of teased apart at a high level what lines two and
now one are doing let me go ahead and rerun make hello now it worked so all those crazy error messages were resolved
by just one fix so key takeaway is not to get overwhelmed by the sheer number of Errors let me now do/ hello and if I
type in my name what am I going to see what do you think yeah hello answer because the
computer is going to take me literally and it turns out that if you just write hello comma answer all in the double
quotes you're really just passing English as the input to the print de function you're not actually passing in
the variable and unfortunately in C it's not quite as easy to plug things in to other things that you've typed remember
in scratch there was not just the sa block but the join block which was kind of pretty it does you go you can combine
apples and oranges or what was it apple and banana then we changed it to hello and then the answer that the human typed
in in C the syntax is going to be a little different you tell the computer inside of your double quotes that you
want to have a placeholder there a so-called format code percent s means hey computer put a string here
eventually then outside of your quotes you just add a comma and then you type in whatever variable you want the
computer to plug in at that percent s location for you so percent s is format code which serves as a placeholder and
now the print F function was designed by humans years ago to figure out how to do the apple and banana thing of joining
two words together it's not nearly as user friendly as it is in scratch but it's a very common Paradigm so let me
try and rerun this now make hello no errors that's good/ hello what's my name David if I type enter now now it's hello
David and the print F here's the f in printf it formats it's input for you by using these placeholders for things like
strings represented Again by percent s so a quick question then if I focus here on line seven for just a moment and even
zoom in here how many inputs is print F taking as a function a moment ago I'd admit
that it was taking one input hello world quote unquote how many inputs might you infer print f is taking
now two and it's implied by this comma here which is separating the first one quote unquote hello percent s from the
second one answer and then just as a quick safety check here why is it not three because there's obviously two
commas here why is it not actually three arguments or inputs exactly the comma in the to the
left is actually part of my English grammar that's all so same syntax and again here's where again programming can
just be confusing on because we're using the same special punctuation to mean different things it just depends on the
context and so now is actually a good time to point out all of the somewhat pretty colors that have been popping up
on the screen here even though I wasn't going to like a format menu I wasn't bold facing things I certainly wasn't
changing things to red or blue or whatnot that's because a text editor like vs code syntax highlights for you
this is a feature of so many different programming environments nowadays VSS code does it as well if your text editor
understands the language that you're programming in c in this case it highlights in different colors the
different types of ideas in your code so for instance string and answer here are in black but get string a function is in
this uh sort of nasty Brown yellow here right now but that's just how it's displays on the screen the string though
here in red is kind of jumping out at me and that's marginally useful the percent s is in blue that's kind of nice because
it's jumping out at me and so it's just using different colors to make different things on the screen pop so you can
focus on how these ideas interrelate and honestly when you might make a mistake for instance let me accidentally leave
off this quote here and now all of a sudden everything notice if I delete the quote the colors start to get a little
arai but if I go back there and put it back now everything's back in place what's another feature of this text
editor notice when my cursor is next to this parenthesis which demarcates the end of the inputs to the function notice
that highlighted in green here is the opening parenthesis why it's just a visually useful thing especially when
you start writing more and more code just to make sure your parentheses are lining up and that's true for these
curly braces over here on the left and the right we'll come back to those in a moment if I put my cursor there you can
see that these things correspond to one another so it's nothing in your code fundamentally it's just the editor
trying to help you the human program and you can even see it though it's a little subtle see these four dots here and
these four dots here that's my indentation I'm fingered vs code to indent by four spaces which is a very
common convention anytime I hit the Tab Key this too can help you make sure once we have more interesting and longer
programs that everything lines up nice and neatly all right any questions then on
printf or more yeah short answer yes printf can handle more than one type of variable or value
percent s is one we're going to see percent I is another for plugging in an integer you can have multiple I's
multiple S's and even other symbols too we'll come back to that in just a little bit printf can take uh many more
arguments than just these two this is just meant to be representative yeah over here can you
declare variables within the printf no the variables the only variable I'm using right now is answer and it's got
to be done outside the context of print F in this case good question we'll see more of that before long uh yeah in back
how do we download the cs50 library so uh we will show you in problem set one exactly how to do that it's
automatically done for you in our version of VSS code in the cloud if ultimately you program on your own Mac
or PC either initially or later on it's also installable online but if you want to ask that um via uh online or
afterward we can point you in the right direction but pet one will itself yeah string is the type of the variable
or the more properly the data type of the variable int is another keyword I alluded to earlier haven't used it yet
int for integer is going to be another type or data type of variable
yeah ah good question could I go ahead and just plug in this function kind of like we did in scratch getting rid of
the variable Al together and just do this which recall is reminiscent of what I did in Scratch by plopping block on
top of block on block am I answering that right can I put string in front of get
string no you only put the word string in front of a variable that you want to make string and even though I'm
apparently answering the wrong question let me go ahead and zoom out save this do make hello again seems to compile
okay if I run/ Hello type in David waa that too works and so actually let's go down this rabbit hole for just a moment
clearly it's still correct at least based on my limited testing is this better designed or Worse
design let's open that question like we did last week yeah yeah I kind of agree with that um reasonable people could
disagree but I I do agree that this seems harder to read because like I have to I start reading here but wait a
minute get string is going to get used first and then it's going to give me back a value so yeah it just feels like
it was nicer to read top to bottom I would say your thoughts yeah and so this is useful if I
only want to print out the person's name once if I want to use it later in a longer program I'm out of luck and so I
haven't saved it in a variable so I think long story short we could sort of debate this all day long but in this
case like if you can make a reasonable argument one way or the other like that's a pretty solid ground to stand on
but invariably reasonable people are going to disagree um whether first-time programmers or many years after that so
let's frame this one last example in the context of the same process of taking inputs and outputs the functions we've
been talking about all take inputs otherwise now known as arguments or parameters pretty much synonymous that's
just the fancy word for for an input to a function and some functions have either side effects like we saw printing
something saying something on the screen sort of visually or audibly or they return a value which is a reusable value
like name or answer in this case if we look then at what we did last time in the world of scratch last week the input
was what's your name the function was ask and the return value was answer and now let's take a look at this block
which is honestly an more userfriendly version of what we just did with the percent s last week we said say then
join then hello and answer but the interesting takeaway there was not how to say hello anything it was the fact
that in Scratch 2 the output of one function like the green join could become the input to another function the
purple say the syntax in C is admittedly pretty different but the idea is essentially the same here though we have
hello a placeholder but we have to in this world of C tell printf what we want to plug in for that placeholder it's
just different but that's the way to do it when we get to Python and other languages later in the term there's
actually easier ways to do this but this is a very common Paradigm particularly when you want to format your data in
some way all right let's then take a step back to where we began which was with that whole program which had the
include and it had int main void and all of this other cryptic syntax this scratch piece last week week was kind of
like the go-to whenever you want to have a main part of your program it's not the only way to start a scratch program you
could listen for clicks or other things not just the green flag but this was probably the most popular place to start
a program in scratch in C the closest analog is to literally write this out so just like
last week if you were in the habit of dragging and dropping when green flag clicked as a c programmer the first
thing you would do was after creating an empty file like I did with hello.c you'd probably type int main void open curly
brace Co curly brace and then you can put all of your code inside of those curly braces so just like scratch had
this sort of magnetic nature to it where the puzzle pieces would snap together C is a text based language tends to use
these curly braces one of them opened the other one closed and anything inside of those braces so to speak is part of
this puzzle piece AKA main so what was a top them we went down this Rabbit Hole a moment ago with these
things called header files even though I didn't call them by this name but indeed when we have a whole program in scratch
super easy just have the one green flag clicked and then say hello world there's no special syntax after all it's meant
to be very user friendly and graphical in C though you technically can't just put int main void print F hello world
you also need this because again you need to tell the compiler to load the library code that someone else will
wrote so that the compiler knows what printf even is you have to load the cs50 library whenever you want to use
get string or other functions like get int as we'll soon see otherwise the compiler won't know what get string is
you just have to do it this way the specific file name I'm mentioning here standard i.h
cs50.h is what C programmers called a call a header file we'll see eventually what's inside of those files but long
story short it's like a menu of all of the available functions so in cs50.h there's a menu mentioning get string get
int and a bunch of other stuff and in as standard i.h there's a menu of functions among which are printf and that menu is
what prepares the compiler to know how to implement those same functions all right let me pause here
question a not quite a library provides all of the functionality we're talking about a header file is the very specific
mechanism via which you include it and we'll discuss this more next week for now they're essentially the same but
we'll discuss nuances between the two next week yeah the library would be standard
iio the library would be cs50 the corresponding header file is standard i.h
cs50.h indeed other questions yeah indeed I that two is on the menu we'll come back to that but the word
word string incredibly common in the world of programming it's not a cs50 idea but in C there's technically no
such data type as string by default we have sort of conjured it up to simplify the first few weeks that's a training
wheel that will very deliberately in a few weeks take away and we'll see why we've even using get string and string
because C otherwise makes things uh quite uh quite more challenging early on which then gets besides the point for us
yeah yes early on you will have to use whatever is prescribed by the
specification that will include cs50's functions long story short you referred I think a moment ago to a another
function called scan F we won't talk about for a few weeks long story short in C it's pretty easy and possible to
get input from a user the catch is that it's really easy to do it dangerously and C because it's an older uh lower
level language so to speak that gives you pretty much all uh ultimate control over your computer's Hardware it's very
easy to make mistakes and indeed um that's too why we use the library so your code won't crash
unintendedly all right so with this in mind we have this now mapping between the scratch version and the other let me
just give you a quick tour of some of the other placeholders and data types that will students start seeing as we
assemble more interesting programs in the world of Linux here is a non-exhaustive list of commands with
which you'll get familiar over the next few weeks by playing with problem sets we've only seen two of these so far are
uh LS for list RM for others but I mention them now just so that it doesn't feel too foreign when uh you see them on
screen or uh online in a problem set um CP is going to stand for copy make dur is going to stand for make directory MV
is going to stand for move or rename uh RM dur is going to be remove directory and CD is going to be for change
directory and let me show you this last one here first only because it's something you'll use so commonly if I go
back to my code here on the screen I'm going to go ahead and reopen the little gooey on the left hand side the
so-called Explorer revealing that I've got two files hello and hello.c so nothing has changed since there suppose
now that you know it's a few weeks into class and I want to start organizing the code I'm writing so that I have a folder
for this week or next week or maybe a folder for problem set one problem set two I can do this in a few ways in the
guy I can go up here and do what most of you would do instinctively on a PC you look for like a folder icon you click it
and then you name a folder like pet one enter voila you've got a folder called pet one I can confirm as much with my
command line interface by typing what command how can I list what's in my folder yeah so LS for list and now I see
Hello and it's green with an asteris because that's my executable my runnable program hello.c which is my source code
and now P at one with a slash at the end which just implies that it's indeed a folder all right I didn't really want to
do it that way I'd like to do it more uh Advanced so let me go ahead and right click on P at one delete permanently I
get a scary irreversible error message but there's nothing in it so that's fine now I've deleted it using the guey but
now let me go ahead and start doing the same thing from the command line and if you're wondering how things keep
disappearing if you hit contrl l in your terminal window or explicitly type clear it will delete everything you previously
typed just to kind of clean things up in practice you don't need to be doing this often I'm doing it just to keep our
focus on my latest commands if I do what was the command to make a new directory yeah so make dur make
directory let me create pet one enter and notice at left there's my pet one if I want to get a little overzealous
plannned for next week here's my pet 2 directory suppose now I want to open those folders want a Mac or PC or in
this gooey I could double click on it like this and you'd see this little arrow is moving it's not doing anything
because there's nothing in there but that's fine but suppose again I want to get more comfortable with my command
line notice if I type LS now I see all four same things let me change directories with CD with CD space pet
one enter and now notice two things will have happened one my prompt has changed slightly to remind me where I am just to
keep me Saye so that I don't forget what folder I'm actually in so here is just a visual reminder of what folder I'm
currently in if I type LS now what should I see after hitting enter nothing because I've only created
empty folders so far and indeed I see nothing if I wanted to create a folder called Mario for a program that might be
called Mario this week I can do that now if I type LS there's Mario now if I do CD Mario notice my prompts going to
change to be a little more precise now I'm in piece at one/ Mario and notice what's happening at top left nothing
nothing now cuz these folders are collapsed but if I click the Little Triangle there I see Mario nothing's
going on in there CU there's no files yet but suppose now I want to create a file called
mario.c I could go up here I could click the little plus icon and use the goey or I can just type code mario.c voila that
creates a new tab for me I'm not going to write any code in here yet but I am going to save the file and now at top
left you'll see that mario.c appears so at some point you can eventually just close explore CU again it's not
providing you with any new information it's may be more user friendly but there's nothing you can't do at the
command line that you could do at the guy all right but now I'm kind of stuck how do I get out of this folder in my
Mac or PC World I'd probably click the back button or something like that or just close it and start all over in the
terminal window I can do CD dot dot dot dot is a nickname if you will for The Parent Directory that is the previous
directory so if I hit enter now no notice I'm going to close the Mario folder AKA directory and now I'm back in
peace at one or if I want to be fancy let me go back into Mario temporarily if I type LS there's mario.c just to orient
us if I want to do multiple things at a time I could do CD slash uh CD do dot do dot which goes to my parent to my
grandparent all in one breath and voila now I'm back in my default folder if you will and one last little trick of the
trade if I'm in P at one/ Mario like I was a moment ago and you're just tired of all the navigation if you just type
CD and hit enter it'll whisk you away back to your default folder and you don't have to worry about getting there
manually recall a bit ago though that I was running hello as this do/ hello if dot dot refers to my parent perhaps
infer here syntactically what does a single dot mean instead it means this directory your
current directory why is that necessary it just makes super explicit to the computer that I
want the program called hello that's installed here not in some random other folder on my hard drive so to speak I
want the one that's right here instead all right so besides these commands there's going to be others that we
encounter over time those are kind of the basics that allows you to sort of lean yourself off of a gooey graphical
user interface and start using more comfortably with practice and time a command line interface instead well what
about those other types now back in the world of c those commands were not c those are just commands specific to a
command line interface like in Linux which again we're using in the cloud it's an alternative to Mac OS and
windows back in the world of C now we've seen strings which are words I mentioned int or integer but there's others as
well in the world of C we've seen string we will see int if you want a bigger integer there's something literally
called a long if you want a single character there's something called a char
if you want a Boolean value true or false there is a bull and if you want a floating point value a fancy way of
saying a real number something with a decimal point in it that is what C and other languages call a float and if you
want even more numbers after the decimal point that is more Precision you can use something called a double that is to say
here's again an example in programming where it's up to you now to provide the computer with hints essentially that it
will rely on to know that what is this pattern of zeros and ones is it a number a letter is it a a sound an image a
color or the like these are the types of data types that provide exactly those hints what are the functions that come
in the menu that is the cs50 library we talked about standard IO and that's just one function so far printf in the cs50
library you can see that that follows a pattern the cs50 library exists largely for the first few weeks of the class to
make our lives easier when you got when you just want to get user input so if you want to get a string like a word or
words from the human you use get string if you want to get an integer from the user you're going to use get int when
you want to get any of those other data types for the most part you use getor something else and they're indeed all
lowercase by convention what about printf if we have the ability now to store different types of data and we
have functions with which to get different types of data how might you go about printing different types of data
well we've seen percent s for strength percent I for integer percent C for Char percent f for a float or a double those
real numbers I described earlier and then percent Li for a long integer so here's the first example of like
inconsistencies in an ideal world it would just be percent L and we'd move on it's percent Li i instead in this
case that's printf and some of its format codes um what more might we do well in C as we'll see no pun intended
there's a whole bunch of operators and indeed computers one of the first things they did was a lot of math and
calculation so there's a lot of operators like these computers and in turn C really good at addition
subtraction multiplication division and even the percent sign which is the remainder operator there's a special
symbol in C and other languages just for getting the remainder when you divide one number by another um there are other
features in the world of C like variables as we've seen and there's also what is sort of playfully called
syntactic sugar that makes it easier over time to write fewer characters but express your thoughts the same so just
as a single example of this as a single example consider this use of a variable last week here in scratch is how you
might set a variable called counter to zero in C it's going to be similar if you want the variable to be called
counter you literally write the word counter or whatever you want it to be called you then use the assignment
operator AKA equal sign and you assign it whatever its initial value should be here on the right so again the zero is
going to get copied from right to left into the variable because of that single equal sign but this isn't sufficient in
C what else is missing on the right hand side instinctively now even if you've never programmed in this before yeah in
front a semicolon at the end and one other thing I think is probably missing again a data type so what would you if
we can uh keep going back and forth here what data type seems appropriate intuitively for counter int for integer
so indeed we need to tell the computer when creating a variable what type of data we want and we need to finish our
thought with the semicolon so there might be a counterpart there what about in scratch if we wanted to Inc increment
that counter variable we had this very user friendly puzzle piece last time that was change counter by one or add
one to counter in C here's where things get a little more interesting and pretty commonly done you
might do this counter equals counter plus one with a semicolon and this is where again it's important to note the
equal sign it's not equality otherwise this makes no sense counter cannot equal counter plus one right like that just
doesn't work if we're talking about integers here that's because the equal sign is assignment so it can certainly
be the case that you calculate counter plus one whatever that is then you up at the value of counter from right to left
to be that new value this as we'll see is a very common thing to do in programming just to kind of count upward
for whatever reason you can write this more succinctly this code here is what we'll call syntactic Sugar sort of a
fancy way of saying the same thing with fewer words or fewer characters on the screen this also adds one or whatever
number you type over here to the variable on the left and there's one other form of syntactic Sugar We're
going to start seeing two and it's even more tur than this that two will increment counter by one by literally
changing its value by one or if you change it to minus minus subtracting one from it you can't do that with two and
three and four but you can do it by default with just plus plus or minus minus adding or subtracting one
yeah uh so when you are changing a variable that already has been created as we did with the code that looked like
this you no longer need to remind the computer what the data type is thankfully the computer's uh uh at least
as smart is that it will remember the type of the data that you intended other questions or comments on
this all right that's quite a lot why don't we go ahead here take a a 10-minute break and we'll be back we'll
start writing some code all right so we are back we've just looked at some of the basics of
compiling even if it doesn't quite feel that basic but now let's actually start Focus really on writing more and more
code more and more interesting code kind of like we dove into scratch uh last week so here I have vs code open I've
closed the guey I'm going to focus more on my terminal window and my code editors many different ways I can create
new files but I want to create something called a calculator so again within this environment of vs code I can literally
write the code command which is vs code specific and it just creates a new file for me automatically or I could do that
in the guey I'm going to go ahead and create this file called calculator. C and I'm going to go ahead and include
some familiar things so I'm just going to go ahead and proactively include cs50.h standard i.h I'm going to go
ahead from memory and do the int void main more on that next week why it's in why it's void and so forth and now let
me just Implement a very simple calculator we saw like some uh mathematical operators like plus and the
like so let's actually use this so let me go ahead and first give myself a variable called X sort of like uh grade
school math or algebra let me go ahead then and get an INT which is new but I mentioned this exists and then let me
just ask the user for whatever their x value is the thing in the quotes is just the English or the string that I'm
printing on the screen so I could say anything I want I'm just going to say x colon to prompt the user accordingly now
I'm going to go ahead and get another variable called y I'm going to get int again and now I'm going to prompt the
user for why and I'm just very niply using a space just to like move the cursor so it doesn't look too messy on
the screen and then lastly let me go ahead and just print out the sum of X and Y in an Ideal World I would just say
something like print FX plus y but that is not valid in C the first argument recall in print F has to be a string in
double quotes So if I want to print out the value of an integer I need to put something in quotes here maybe followed
by a new line if I want to move the cursor as as well so again we only glimpsed it briefly but what do I
replace these question marks with if I want a placeholder for an integer yeah so percent I right just
like percent s was string percent I is integer so I change this to percent I and now if I want to add X and Y for
instance super simple calculator doesn't do much of anything other than addition of two integers I think this works and
again it looks definitely cryptic at first glance like it would be nice if programming weren't this cryptic other
languages will clean this up for us but again if you focus on the basics printf takes one input first which is a format
string with English or whatever language some placeholders maybe then it takes potentially more arguments after the
comma like the value of X+ y all right let me go ahead now and make calculator which again compiles my source code in C
pictured above and converts it into corresponding machine code or zeros and ones no error messages so that's that's
already good now I do/ calculator let's do 1 + 1 and enter voila now I have the makings of a
calculator now let's start to Tinker with this a little bit what if I instead had done this int Z gets x + y and then
plug in Z here if I rerun make calculator enter rerun do/ calulator type in 1 + 1 still equals 2 and let me
claim that it will work for other values as well which of these versions is better designed if both seem to be
correct at very cursory glance is this version better or is the previous one without the Z okay so this one's
arguably better because I've now got a reusable variable called Z that I can not only print but Heck if my program's
longer I can use it elsewhere counters yeah debatable like before because it depends on my intent and
honestly I think a pretty good argument can be made for the first version because because if I have no intention
of as you note using that letter uh that variable again you know what maybe I might as well do this just because it's
one less thing to think about it's one less distraction it's one less line of code to have to understand it's just a
little tighter so here again I think it it does depend on your intention but this feels pretty reasonable and I think
as someone noted earlier when I did the same thing with get string that yeah maybe kind of crossed the line because
get string and the what's your name inside of it it was just so much longer but X Plus y
it's not that hard to wrap our mind around what's going on inside of the printf argument so again these are the
kinds of thoughts that hopefully you'll acquire the Instinct for um not necessarily reaching the same answer as
someone else but again the thought process is what matters here all right so how might I enhance this program a
little bit let's just talk about style for just a moment so X and Y at least in this case are pretty reasonable variable
names why because like that's the go-to variable names in math when you're adding two things together so X and Y
seem pretty reasonable I could have done something like well maybe my first variable should be called
first number and my next variable should be called second number and then down here I would have to change this to
first number plus second number like like this isn't really adding anything semantically to help my comprehension
but that would be one other direction we could have taken things so if you have very simple ideas that are
conventionally expressed with common variable names like X and Y totally fine here here what if I want to annotate
this program and remind myself what it is it does well I can add and see what are called comments with a slash slash
to forward slashes you can write a note to yourself like prompt user forx and then down here I could do something like
prompt user for why just to remind myself what I'm doing there and down here perform addition now in this case
not sure these comments are really adding all that much because in the time it took me to write and eventually read
these comments I could have just read the three lines of code but as our programs get more sophisticated and you
start to learn more syntax that honestly you might forget the next day the next week the next month might be useful to
have these sort of notes to self that remind you of what your code is doing or maybe even how it is doing that thing
with these early programs not really necessary doesn't really add all that much to our comprehension but it is a
mechanism you have in place that can help you actually uh remind yourself or remind someone else what it is that's
going on well let me go ahead and rerun this again in this current version make calculator and here too you might think
I'm typing Crazy Fast not really I'm hitting tab a lot so it turns out that Linux the operating system we're using
here in the cloud but actually Windows and Mac OS nowadays support this too supports autocomplete so if you only
have one program that starts with C you don't have to finish writing calculator you can just hit Tab and the computer
will finish your thought for you the other thing you can do is if you hit up and keep going up you'll scroll through
your entire history of commands so there too I've been saving some key strokes by hitting up quickly rather than retyping
the same darn thing again and again so again just another little convenience to make programming and interacting with a
command line interface even faster all right let me go ahead and just make sure it's compiled in the current form the
comments have no functional impact these green things are just notes to self let me run calculator with maybe how about
this instead of 1+ 1 how about uh one billion uh oops let's I got 1 million one billion and another 1
billion and that answer is two billion all right so that seems correct let's run this program one more time how about
two billion plus another 2 billion did you know that so apparently it's not so correct
and clearly running 1 plus one was not the most robust testing of my code here what might have gone wrong what might
have gone wrong yeah yeah the computer probably ran out of space with bits so it turns out with
these data types we've been talking about string and int and also float and Char and those other things they all use
a specific and most importantly finite number of bits to represent them it can vary by computer newer computers use
more bits older computers tended to use fewer bit um it's not necessarily standardized for all of these data types
but in this case in this uh environment it is using 32 bits for an integer that's a lot with 32 bits You Can Count
pretty high this is 64 light bulbs on the stage and could count even higher an INT is only using half of these or we
have two integers here on the stage now if you think back to last week we talked about eight bits at one point and if you
have eight bits eight zeros and ones you can count as high as 256 just a good number to generally remember as trivia 8
Bits gives you 256 permutations of zeros and ones 32 gives you roughly how many if anyone knows it's 2 to the 32 power
so it's roughly 4 billion 2 to the 32 if you don't know that it's it's fine most uh programmers they eventually remember
these kinds of heuristics so it's roughly 4 billion so that feels like enough 2 billion plus 2 billion is
exactly 4 billion and that actually should fit in a 32bit integer the catch is that my Mac
your PC and the like also like to support negative numbers and if you want to support both positive and negative
numbers that technically means with 32-bit integers you can count as high as roughly 2 billion positive or 2 billion
negative in the other direction that's still four billion give or take but it's only half as many in One Direction or
the other so how could I go about implementing a correct calculator here what might the solution
be yes so not just Li which was for long integer I have to make one more change which is to the data type itself so let
me go back up here and change X from an INT to a long AKA long integer and then let me change y as well and then let me
change the format code per the little cheat sheet we had up a few minutes ago to Li let me recompile the calculator
seems to work okay let's reun it now let's do 1+ one that should obviously be the same now let's do two
billion and another two billion and cross our fingers this time now we're counting as high as four billion and we
can go way higher than 4 billion but we're only kicking the can down the street a bit even though we're now using
with a long 64 bits which is as long as this stage now that's still a finite value it might be a really big value but
it's still finite and we'll come back at the end of today to these kinds of fundamental limitations because arguably
now my calculator is correct for like millon ions billions of possible inputs but not all and that's problematic if
you actually want to use my calculator for any possible uh inputs not just ones that are roughly less than say two
billion as in this case are any questions then on that but it's really just a precursor for all the problems
that we're going to have to eventually deal with later on good question yes if we were still
still using Z we would also have to change it to a long otherwise we'd be ignoring 32 of the bits that had been
added together via the Longs good question all right so how about we spice things up with maybe not just addition
here how about um something with some conditions let's start to ask some actual questions so a moment ago recall
that we had uh recall that we had uh just the Declaration of variables now let's look back at something in scratch
that looked a little something like this a bunch of puzzles pieces asking questions by way of these conditionals
and then these Boolean Expressions here in green maybe saying something like X is less than y in C this actually Maps
pretty cleanly it's much cleaner from left to right than it was with print F and join uh here we have just code that
looks like this if a space two parentheses and then X less than y and then we have something like print F
there in the middle so here it's actually kind of a nice mapping notice that just as the yellow puzzle piece in
scratch is kind of hugging the p purple puzzle piece that's effectively the role that these curly braces are playing
they're sort of encapsulating all of the code on the inside the parentheses represent the Boolean expression that
needs to be asked and answered to decide whether or not to do this thing and here's an exception to what I alluded to
earlier usually when you see a word and then a parenthesis something and then close parenthesis I claim that's usually
a function and I'm still feel pretty good about that claim but there are exceptions and the word if is not a fun
function it's just a programming construct it's a feature of the C language that similarly uses parentheses
just for different purposes for a Boolean expression how about something like this last week if you wanted to
make have a two-way fork in the road go this way or that way you can have if and else in C that would look a little
something like this and if we add in the printfs it now looks quite like the same but it adds of course the word Els and
then a couple of more curly braces as an aside in C it's not strictly necessary to have curly braces if you have only
one line of code indented underneath for best practice though do so anyway because it makes super clear to you um
and ultimately anyone else reading your code that you intend for just that one or more line of code to execute how
about this from last week here was a three-way fork in the road if x is less than y else if x is greater than or
equal to greater than y else if x equals y now here's where you have some disparities between scratch and C
scratch uses an equal sign for equality to compare two values C uses a single equal sign for assignment from right to
left minor difference between the two worlds in C we could implement the same code like this the addition being just
this additional else if and if we add in the print FS it looks a little something now like this this is correct both in
the scratch world and in the SeaWorld but could someone make a claim that this is not again welld designed exactly we
don't need the last if we need the Els at least but we don't need the at last if because at least in the world of
comparing integers it's either going to be less than greater than or equal to there is no other case so you can save a
you know a few seconds if you will of your program running a blink of the eye by only asking two questions and then
inferring what the answer to the third must be just by nature of your own human logic here now why is that a good thing
if for instance X and Y happen to equal each other I type in one and one for both values either in scratch or in the
C world in the case of this version you're sort of stupidly asking three questions all of which are going to get
asked even though the answer is no no yes that is true uh false false true that seems to be unnecessary because if
we instead optimize this code get rid of the unnecessary if and just do as you propos logically else print that X is
equal to Y now if x and D equals y because they're both one or some other value now you're only going to ask two
questions so 2/3 as many questions and then you're going to get your same correct result so again A Minor Detail
but again the kinds of things you should be thinking about not only as you write your code uh to be correct but also
write it to be welld designed as well all right so why don't we go ahead and translate this into the context of an
actual program here I'll create a blank window here and let's do something with like points like points on my own very
first cs50 problem Set uh let me go ahead and run code of points. C that's just going to give me a new text file
and then up here I'm going to do my usual include cs50.h include standard i.h in main void
so a lot of boiler plate so to speak in these early programs and now let me just let's see let's ask the user how many
points did they lose on their most recent cs50 P set to sort of evoke uh my photograph of my own very first pet last
week where I lost a couple of points myself so int Point equals get int then I'll ask a question in English like how
many points did you lose question mark space and then once I have this answer let's now ask some questions of it so if
point is less than two borrowing the syntax syntax that we saw on the screen a moment ago let's go ahead and print
out something explanatory like you lost fewer points than me back sln all right else if points greater than two which is
again how many I lost I'm going to go ahead and print out you lost more points than me back sln else if wait a minute
else seems to be sufficient logically here I'm just going to go ahead and print out something like uh you lost the
same number of points as me back sln so really just a straightforward application of those that simple idea
but to like a concrete scenario here so let me go ahead and save this uh let me go ahead and run make points enter no
errors that's good run points and then how many points did you lose how about it's one point all right you lost fewer
points than me how about zero points even better how about three points and so forth so again we have the ability to
express in C now pretty basic idea from last week in reality which is this notion of conditionals and asking
questions there's something subtle here though that's maybe not super welld designed that someone might call a magic
number this is sort of programming speak for something I've done here there's a bit of redundancy unrelated to the if
and the else if and the Els but is there something I typed twice just to ask perhaps for the
obvious exactly I've I've hardcoded so to speak manually typed out the number two in two locations in this case that
did not come from the user where so this is apparently once I compile this this is it you're always comparing yourself
to me in like 1996 which For Better or For Worse is all the program can do but this is an example two of a magic number
in the sense like wait where did that two come from and why is it in two places it feels like we are setting the
stage for just a higher probability of screwing up down the road because the longer this code gets suppose I'm
comparing against two points elsewhere two three four five places am I going to keep typing the number two like yeah
that's fine it's correct it's going to work but honestly eventually you're going to screw up and you're going to
miss one of the twos you're going to change it to a three because maybe I did worse the next year or one I did better
and you don't want these numbers to get out of sync so what would be like a logical Improvement to this design
rather than hardcoding the same number sort of magically in two or more places yeah why don't I make a variable
that I can use in there so for instance I could create a variable like this another integer called mine and I'm just
going to initialize it to two and then I'm going to change change mentions of two to this and mine is a pretty
reasonable name for a variable in so far as it uh refers to exactly whose points are in question um there's a risk here
though minor though it is I could accidentally change mine at some point maybe I forget what mine represents and
I do some addition or subtraction so there's a way to tell the computer don't trust me because I'm going to screw up
eventually by making a variable constant too so a constant in a programming language this did not exist in scratch
is just an additional hint to the computer that essentially enables you to program more defensively if you don't
trust yourself necessarily to not screw up later or honestly in practice if you know that number should never change
make it constant and never think about it again this tells the compiler to make sure that even you later in your code
cannot change the number two and another convention in C and other languages when you have a constant it's often common to
just capitalize the variable kind of like like you're yelling but it really just visually makes it stand out so it's
kind of like a nice rule of thumb that helps you realize oh that must be a constant capitalization alone does not
make it constant the word const does but the capitalization is just a visual reminder that this is somewhere somehow
a constant so just a minor refinement but again we're sort of getting better at programming just by sort of um
instilling these kinds of heuristics questions then on conditionals in C or these constants
yeah yeah why do you not use a semicolon and lik lines 913 no good like just because like this is the way the
language was designed and it's confusing early on generally speaking when you're using conditionals and eventually we'll
see Loops there's no semicolons involved for now assume that semicolons usually finish your thought after a function
that's not 100% reliable of theistic but will get you most of the way there and just because left hand was not
talking to right hand when some of these languages were designed all right so let's do something else how about this
if I have the ability to ask something conditionally is this thing true or is this other thing could I write a very
simple program that does something basic like tells me if a number of the human types is even or odd well let me just
get the framework for that in place let me go ahead and write code of a parody As a fancy way of saying even or odd and
let me go ahead and include cs50.h include standard i.h int main void again more on those down the road
but for now I'm going to go ahead and get a number n from the user uh by calling get int and asking them for
whatever n is and then now I'm going to introduce some pseudo code so here's the first example of a program honestly that
I'm not really sure how to proceed so let me just resort to some pseudo code using comments eventually I'll get rid
of this and write actual code but if n is even then print actually let me just print that let me just go ahead and say
print F quote unquote even because I know how to use print F uh else all right I know how to print F odd
so let me just say print F quote unquote odd so here I've sort of taken a bite out of the problem if you will and let
me go ahead and put in my little placeholders I want to do some kind of condition so if question marks now let
me go ahead and fill in the blanks here else I'll put this here so I think I'm okay now I'm getting closer to solving
this but I still have this question mark here how using syntax we've seen might I determine if n is even or odd what do
you think nice there's this little uh operator we I mentioned by name earlier the remainder operator that will let you
do exactly that if you divide any number by two that mathematical here is is going to tell you if it's even or odd
based on whether there's a remainder of zero or one and that's nice because the alternative would seem to be doing
something stupid like if Nal equals z or Nal equals uh if n equal 2 or Nal 4 or right you would your code would be
infinitely long if you had to ask all possible questions but if I do n uh divided by two and look at the remainder
it's a little cryptic but this will indeed do the trick so the percent sign is the remainder operator it does
numerator divided by denominator and returns not the result of that but rather the remainder of that so if you
divide anything by two it's going to be a zero or one remainder and if indeed two divides into n evenly giving you
zero then you're going to print even else it's got to be odd but there is something odd pun intended in this
highlighted line what is another new piece of syntax apparently besides the percent
sign what's a little off there yeah yeah so that's not a typo and I even caught myself verbally saying it a
moment ago just because it's so ingrained what must this mean here
yeah yeah if something's equivalent to the other so now this is the equality operator it's not assignment from right
to left and this one too is an example of like literally humans not really planning ahead perhaps uh left hand not
talking to right hand and that someone decided let's use the equal sign for assignment and then some number of
minutes or days later people are like damn how do we now compare for equality well let's just use two and if you think
this is a little weird in some languages like JavaScript there's a third version where you use three equal signs so again
it's humans that design these languages so if you're ever frustrated by them confused by them admittedly it might
just not have been the best design but we just kind of have to live with it ever since so let me go ahead and zoom
out here let me go ahead and make parody here so make parody and again parody is just the name of my file parody. c/
parity type in a number like two that's indeed even four that's indeed even three that's indeed odd and so forth if
we continue testing presumably we'll get the same kinds of answers how about something else let me go ahead now and
let me start copying and pasting some of this code because admittedly it's getting a little tedious to keep typing
out all of that boiler plate at the top let me create a program called agree. C that's reminiscent of like any of those
forms you have to agree to online with a checkbox or typing in yes or no or the like so let me throw away all the guts
of this main program and now ask something like this let me go ahead and prompt user to agree to something I'm
going to go ahead and say how about get string do you agree whatever the question might be and I want the human
to type why or no y or n for yes or no respectively so if it's only a single character actually I can actually get by
with just get Char not used it before but it was on our menu of functions from the cs50 library and if I want to get
the user's response the return value should be a Char also on the left so now we've seen strings ins and now chars if
we only care about a single letter and now let's go ahead whether check whether uh user agreed so how about if C equals
equals quote unquote y then let me go ahead and inside of my curly braces print out agreed or some such sentence
like that else if they did not type c or you know what let's be explicit here just so they can't type Z or B or some
random letter else if C equals equals quote unquote n for no then let me go ahead and print out not agreed or
something like that and I'm just going to ignore the user if they don't cooperate in the type Z or B or
something that's not y or n all right let me go ahead now and compile this code make
agree SL agree all right do I agree yes let's go with the default okay so that seems to work no I don't agree this time
that seems to work how about my caps lock key is on or I'm just uh really yelling capital Y it ignores me capital
N it ignores me so obviously a bug at least if I want to tolerate uppercase and lower case which is kind of
reasonable so what would be the possible solutions here do you think how do I solve this and tolerate both up
capital and lowercase maybe what's the simplest most naive implementation yeah so why not just ask
two questions or you know what even more simplistic based only on what we've seen before let me if you will let me just
kind of copy and paste some of this code change this to an else whoops not in caps else if quote unquote capital Y and
then I bet I could do the same thing with n but here too just like with scratch as soon as you start to find
yourself copy pasting you're probably doing something wrong and what you said verbally if I may was actually better
because you're implying that I could just say something like or c equal equals capital y or down here calal
capital N the catch is you can't use the word or in C it's actually two vertical bars so you can express one question or
another you only will need one of the answers to be yes or true and you use two vertical Bars by contrast just so
you've seen it if you wanted to check if something is equal to something and something else you could use two Amper
Sands this logically would make no sense here though certainly what the human type can't both be lowercase and
uppercase that just makes no sense so in this case we do want or but that allows me to tighten my code up I don't have to
start copying and pasting whole branches I can now ask two questions at once questions then on this variation
really good question can you convert the input to all lowercase absolutely you could we don't have the capability yet
it turns out that's going to require to be easy another library that we could do it ourselves knowing a little bit about
asky or Unicode from last week but yes that would be an alternative but more on that a different time other
questions good question unfortunately you have to be explicit in see you can't just say this even though that's kind of
how you might think about it you have to ask a complete question using the equality sign twice in this
case let me ask a question now too it's not a typo I deliberately used single quotes around all of my single letters
here why might that be previously we used double quotes for anything that looked like
text yeah correct string is double quotes for multiple characters or even one
technically but yes and single quotes for for single characters because my data type is different I chose the rout
of just using a single Char in fact this program won't work with ye or n o That's not supported at the moment more on that
another time I had to use single quotes because that's how C does it if you're dealing with single characters AKA chars
use single quotes if it's a string even if it's one single character in a string as though you're starting to write out a
longer word or sentence that would be double quotes and we'll see why this is before long too but again just sort of
things to keep in mind whenever writing code in this particular language yeah down
here so short answer if I'm understanding correctly even we this would be incorrect and this would be
even more incorrect but if you don't mind let me Kick the Can a couple of weeks on this as to why this doesn't
work the right way the most Pleasant way to do this would indeed be to do something like this but even this is a
slippery slope because what if the user does something weird like they capitalize just the W you could imagine
this getting messy quickly I like your idea earlier about just forcing everything to lower case just to
standardize things unfortunately you cannot compare strings for equality like this for again reasons will come to
before long so for today we're keeping it simple even though arguably it's not nearly as user friendly to only tolerate
individual letters and there's a question over here uh the on the US English keyboard
it's shift and then the backslash key above return but depending on your keyboard it will
vary all right so let's actually now uh look back at something we did a little bit last week let me go ahead and open a
file called meow. C because recall that's what we had scratch do initially let me include not the cs50 library this
time but just standard i.h because I only want printf for this demo let me go ahead now and just print out
meow and then if I want the cat to meow three times like it did last week meow meow meow save it make meow meow voila
program is written correct I claim it ran it compiled okay but again this was the beginning of our conversation last
week of not being particularly welld designed and if someone wants to maybe point out the now obvious like why is
this not welld designed necessarily yeah it's just repetition right again I literally resorted to copy
paste like that should be the signal that you're probably doing something wrong or at best just lazy of you in
this case so the solution as you might glean from last week is probably going to be one of those things called Loops
so let's just take a look at some of the Syntax for loops and see but again no new IDE IDE it's just some new syntax
that'll Tak some getting used to in scratch if you wanted to meow forever with something like this there's not a
forever keyword in C so this one's a little weird to look at but this is the best we can do it turns out there is a
keyword called while in C and that kind of has the right Comm semantics because it's like while I do something again and
again that's the best I can do but just like an if condition or an else if condition those took a expression in
parenthesis a while loop also takes a Boolean expression in parentheses so I have to ask a question now if I want to
do something forever I could kind of stupidly just say while two is greater than one while three is greater than two
or just something completely arbitrary but that should rub you it the wrong way cuz like why two versus one why three
like just if you want true just say true so it turns out in C there are special keywords true and false that are
literally true and false respectively I could also put the number one for true and the number zero for false but most
people would just say true to be explicit so it's a little hackish if you will but very conventional there's no
forever keyword in C if I want to then print meow forever I'm going to just use something like print F here so again not
perfect translation from one to the other but absolutely possible in C what about this this is a little more common
if you want to do something a finite number of times like repeat three there's a few different ways we can do
this in C here's one I would approach and here's where C like a lot of text based languages you kind of have to whip
out that toolkit of all of the basic building blocks and think about all right how can I build a little machine
in software that does something some number of times well let me give myself a variable called counter set it equal
to zero let me create a loop whose Boolean expression is is counter less than three
the idea being here why don't I just kind of count 1 2 three so how do I implement this physicality in code I
give myself a variable set it to zero zero fingers up now I ask the question is counter less than three if so go
ahead and print out meow and just intuitively even if you've never seen C code or any code before scratch what
more do I need to do I've left room here for one more line of logic yeah we have to increase counter so I need code like
I showed earlier like counter equals counter plus one and so here's where like programming sometimes becomes a bit
more like Plumbing like you can't just say what you mean like you couldn't scratch you have to build a little sort
of software machine that initializes a value does something increments it checks it and so it's kind of like this
software-based machine but together that's just using some familiar building blocks but this is pretty common just
like in scratch you might have used Loops a bunch of times pretty common in C so can we tighten this code up this is
correct but here are some new here are some conventions that are popular you don't if you're going to count just say
I a convention in programming with at least languages like C is just use I as an integer if all its purpose is is to
count from like zero on up counter is not wrong it's not bad it's just uh like it's it's more verbose than you need to
be just call it I you don't need more semantics than that all right what else can I do here there's another
opportunity to tighten up this code do you recall yeah yeah that syntactic sugar that does
nothing new but it does it more succinctly I can change this to either the uh intermediate format or the even
tighter format of just i++ now this is pretty canonical like this is how many people most people would Implement
something three times using a loop in C using a while loop that is turns out that it's so common in C and other
languages to do something finitely many times there's a couple of ways to do it in this model to be clear the logic
though is that we start by initializing the variable like I've highlighted here we then ask the question is I less than
zero if so everything that's indented inside the curly braces gets executed namely meow then the update then the
computer is going to to recheck the condition to make sure that I hasn't gotten so big that it's greater than
three but if not it then does this again and it does this again and then it repeats constantly checking the
condition and executing what's in the block checking the condition and executing what's in the block after
three times of that the condition is going to be false or a no answer and that's it for the code it just proceeds
to whatever is down here just like with scratch it jumps to the next blocks down below all right what's another way
though to do this well I've deliberately been counting from zero and that's a programming convention right we started
last week with all the light bulbs off which was zero so it's pretty reasonable to start counting at zeros just like you
would here like no fingers are up this is zero fingers on your hand but if you prefer you could start counting at I
equals 1 but then you don't want to do it while I is less than 3 you want to do I is less than or equal to 3 on most
keyboards there's no symbol for less than or equal to or greater than or equal to so in C you use two characters
less than and then an equal sign with no spaces in between that just means less than or equal to we could change it to
set I to two and make this condition be less than or equal to four we could make this be um
uh 10 and less than or equal to 12 but again just stick with the basics start at zero and count on up would be the
convention or if you prefer to countdown that's fine too set I to three and then do this so long as I is greater than
zero but you have to decrement instead of increment so again we could do this all day long there's like literally an
infinite number of ways to implement this idea and that's why I keep emphasizing convention call the variable
I for something like this initialize it to zero for something like this and just generally count up unless you really
prefer to count down again just certain human conventions all right how about another way to do this this is what's
called a for Loop in C also very common it's not quite as straightforward in that it doesn't really read top to
bottom in the exactly the same way this kind of has a lot more logic tucked into its first line but it does exactly the
same thing what happens here is notice that inside the parentheses next to the word for there's two semicolons which is
another weird use of syntax they're not at the end of the line now they're in the middle of the parentheses but that's
what the humans chose years ago the first thing before the uh semicolons initializes your variable in I equals z
the next thing is the condition that's going to constantly get checked every cycle through this Loop and the last
thing is going to be what you do after each Loop which in this case is going to be count up so again if I rewind we
initialize I to zero we then ask the question is I less than three if so execute what's inside of the
loop then the computer asks does this it does the update incrementing I by one and then it's not going to blindly meow
again it's going to check again the condition is I less than three then it's going to meow if so then it might go
ahead and increment I and check the condition again so again this does not read quite in the same simple Fashion
top to bottom you kind of read it left to right and then jump around but again the
initialization the constant Boolean expression being checked and the update after each time does the exact same
thing as what we saw a moment ago in this while loop format which one is better eh they're the same I think most
people would probably eventually use a for Loop once comfortable but just because is really the answer there all
right any questions then on Loops as we translated them to see yeah uh for Loop and while loop can both
be used to do exactly the same thing there are subtle differences with issues of scope which we'll discuss before long
where when you create a variable in a for Loop notice that it was again inside of those parentheses which technically
means it's only going to exist in these four lines of Code by contrast with the while loop I declared my variable
outside of the loop that variable is going to continue to Exist Elsewhere in my program so that's one of the minor
differences there good question but you'll see some others over time all right so we claim then that it's better
in some form to do this with Loop so let's actually jump back to the code let me go ahead and now reimplement meowing
with a four Loop for instance so how about four in I gets zero I less than three whoops I less than three i++ then
inside my curly braces let me go ahead and print out with print F meow with a new line and a semicolon so I did it
pretty quickly just cuz I've long acquired the muscle memory but if I now make meow no errors there run. meow and
I see meow meow meow well let's do now what we did last week which was to begin to make our own custom functions if you
will by using our own Inc so here's where the synex gets a little funky but we'll explain over time why what each of
these keywords is doing if I want to create a function called meow because the authors of C did not create a
function called meow decades ago I need to give it a name like meow I need to specify if it takes any inputs for now
I'm going to say no and I'm going to explicitly Say No by writing the special word
void it's also necessary when implementing a function in C which was not necessary in scratch to specify what
its return type is but for now I'm just going to say that meow is the name of the function it takes no no inputs and
that's what the me void in parenthesis means and it does not return anything like get uh like ask did or like get
string or get int does meow's purpose in life is just to have side effects visual Side Effects by printing something on
the screen so what is meow going to do I'm going to have it quite simply say print F quote
unquote uh meow back sln and now just like in scratch I can now just call a brand new function called meow and
here's where too if you really don't like the curly braces technically speaking you can get rid of them when
there's only one line of code inside your Loop but again stylistically I would encourage you to preserve them to
make super clear to yourself and others what it is that's going on let me go ahead and save this and do make meow
whoops darn all right what did I do something stupid yeah so zero does not belong
there I meant to hit parenthe uh parenthesis so let me rerun make meow okay fixed my mistake all right it's
still working okay but recall what I did in scratch kind of out of sight out of mind and just to make a point let me
just kind of highlight this and move it way down in the file because again like now that meow exists it's an abstraction
I just know a meow function exists I want to be able to use it so let me scroll back up my main function is the
same let me go ahead and make meow again and now just by moving that function I've created all these lines of errors
and let's look at the first again the rule of thumb here it's a little small but it says meow. C and bolt which is
the name of the file where the bug is five is the line number and 20 is the character so line number is no enough
alone uh let's see oh this is what happens when I scrolled up too far sorry this is the error we're now looking at
line seven I was looking at the old error message uh from earlier before I fixed the zero meow see line seven all
right apparently C does not know what the meow function is implicit Declaration of function meowo is invalid
in c99 well what does that mean Declaration of function means your creation of a function like I'm
declaring that meow exists but I haven't apparently defined it yet and then c99 is the version of C from the year 1999
which we generally use here it's one of the more recent versions so why is that the case can you infer from the mere
fact that I just moved meow to the bottom of the file which was fine in scratch but now is bad why is
that yeah C is just kind of old school it reads your code top to bottom and if it does not know what meow is when you
first try to use it it just freaks out and prints out these error messages so the solution is quite simply don't do
that just leave it where it was but you could imagine this getting a little Annoying over time if only because main
is by name the main part of your program and honestly it would just be nice honestly if if main were always at the
top of your code because if you want to understand what a file is doing it makes sense to just read it top to bottom well
there is a solution to this you can put functions in different orders with main at the top so long as you and this is
perhaps the only time copy paste is appropriate so long as you leave a little breadcrumb for the compiler at
the very top of your file that literally repeats the return value the name and the arguments to that function semicolon
this is so to speak declaring your function and the real fancy way is this is a prototype it's like what is this
thing going to look like but the semicolon means I'm not going to deal with this yet I'm going to actually
Define the function or implement it down below here this is kind of a stupid detail more recent languages get away uh
get rid of this need you can put your functions in any order but again if you just think about the basics of
programming languages like this one here and as you noted it must just be reading your code top to bottom so annoying yes
but explained yes too so let me go ahead and make meow once more time/ meow still working okay and let me make one final
enhancement to this meow program here let me go ahead now and say something like this let me go ahead and say all
right wouldn't it be nice if my meow function could do something for me some number of times so suppose I want to do
this this meow function fun at the moment is going to meow three times but suppose I want to meow n times where n
is just some number provided by the user well just like in scratch custom functions can take inputs I just
presently am saying void but if I change this to intn thereby telling the compiler hey
meow still doesn't return something but it does take something as input it takes an integer and I want to call it n so
this is another way of declaring a variable but a way of declaring a variable that gets handed into as input
the function so now if I tighten up main here now I can actually do something really cool just like in scratch which
is this if I now look at this code let me zoom in here now my main program is really well written in the sense that it
just says what it does meow three times this works though because I Define meow is now taking an input an integer called
n and then using n in my now familiar for Loop there's one change you might have caught my one mistake I
also have to remind myself up here to make that change too again this is one of the only redundancies or copy paste
that's sort of reasonable but there I have now a better version so let me go ahead and rerun this uh make meow do/
meow voila so again no change in correctness but now again we're sort of modularizing our code and heck what you
could do now and this is just a tease a feature down the road those header files we talked about early those libraries
this is the kind of modularization we're talking about we the staff wrote a function called get string get int and
so forth we put it in a file called cs50.c and we put little breadcrumbs specifically these things called
prototypes in cs50.h so that when you all as aspiring programmers include cs50.h you are sort
of secretly telling the compiler at the very top of your code what the menu of available functions is why because in
cs50.h is lines like these obviously not for meow but for get string get int and so forth and in standard i.h is the same
lines of code for things like printf so that's all that's going on there it's just a way of telling the computer in
advance what functions to expect are any questions then on these here correct so if you don't mind I want
to continue to wave my hand at that detail for today indeed int main void is a little weird cuz like what would the
input domain be we have no mechanism for providing input yet and what does it mean for main to return anything like
who is it returning to for another day if we may they're going to come into play but that for now today is just
something you should take at face value as necessary copy paste to begin programs so meow is a function that
takes an input the number of times to meow but it didn't actually have a return value hence the void but what
what if we actually want to create our own function that not only takes zero or more inputs as arguments but also
returns some value maybe an INT maybe a float maybe something else Al together we'll turns out to see we can do that as
well let me go ahead and create a new file here called discount and let's Implement a quick program via which we
can discount some regular price by some percentage as though there's a sale going on in a store let me go ahead and
include our usual uh cs50.h followed by standard IO at the top let me give myself in main void as before and inside
of main let's go ahead and do something simple let's give ourselves a float called regular representing like the
regular price of something in a store let's go ahead and get a float from the user asking them what that regular price
is then next let's go ahead and declare a second variable also a float called sale ultimately representing the sale
price after some percentage discount off and let's go ahead and simply calculate whatever regular is and say 15% off is a
pretty good discount so let's go ahead and discount regular Whatever It Is by 15% which is equivalent of course to
multiplying it with the asterisk by 0.85 of course if we're taking off 15% we multiply the regular price by 085 now
let's go ahead and print out the results here let me go ahead and say print F sale price colon let me go ahead and use
percent F but more specifically percent. 2f CU at least in US currency we typically show sense to two decimal
places followed by a new line and then let me go ahead and plug in the value of sale all right let's go down here and do
make discount enter so far so good/ discount and the regular price is maybe $100 so the sale price should be $85 so
our arithmetic seems to be correct here but let's fast forward now in time suppose that we find ourselves
discounting a lot of prices in an application maybe a website like Amazon where they're offering some kind of
percentage discount and' be nice to have a reusable function that just does this arithmetic Force simple though it may be
so let's go ahead and modify discount this time to give ourselves our own function called discount for instance
that takes an input like the regular price that you want to Discount and then it also returns a value it doesn't just
print it out it returns a value namely a float that represents what the sale price is so let me go down below Main
and go ahead and Define a function that's going to return a float because we're dealing with dollar amount still
uh the function is going to be called discount and it's going to take one input
like the price that we want to Discount in here I'm going to do something very simple I'm going to say float sale
equals whatever that price is times 085 and then I'm going to go ahead and return sale now for that matter I can
actually tighten this up a bit if I'm only declaring a variable to store a value that I'm then returning with this
keyword return I actually don't even need that variable so I can delete the second line and I can actually just go
ahead and get rid of that variable alt together and immediately return turn whatever the arithmetic result is of
taking the price input the argument that's being passed in times 85 so very simple function that simply does the
discounting for me as always let me go ahead and copy paste the almost the only time it's okay to copy paste the
Prototype of that function to the top of the file so that when compiling this code uh main has already seen the word
discount before and now let me go into the code here and instead of doing the math myself in main let me presume that
we have some function already in our toolkit called discount that lets me discount the regular price and return
that value and then down here my code doesn't need to change I'm still going to print out sale the variable in which
I'm storing that result but notice what I've done here I've sort of abstracted the way of the notion of taking a
discount by creating my own function that takes a float called price or anything else as input it does a little
bit of math simple though it is here and then it returns a value but notice that discount is not printing that value it's
literally using this other keyword called return so that I can hand back that value just like get string hands
back a value just like get in hands back in integer without printing it for you so that I up here on line nine can go
ahead and store that value in a variable if I want and then actually print it out let me go ahead now and recompile this
code with make uh discount let me go ahead and do do/ discount and let's again do
$100 sale price is going to be uh 85 5 as well now it turns out that functions don't have to take just zero or one
argument as input they can actually take two or three or more so in fact suppose we wanted to now enhance this version of
my program and take in as input to the discount function not just the price that I want to discount but also the
percentage off thereby allowing us to support not just 15% off but any number of percentage points off well let me go
up here and declare an Inay and call it percent off and let me ask the user for how many percentage points they want to
take off so I'm going to say percent off inside of the propt here get that int called percent off and now in addition
to passing in regular as an input that the discount function I'm also going to pass in percent off but I need to tell
the computer that it is taking now two arguments and the way I do this is just with a comma down here in the function's
own definition here is going to be a percentage argument a second argument per the comma and I'm going to use that
percentage in a slightly uh familiar way I don't want to just do percentage like this because of course that's going to
increase the size of the total price I actually need to do a little bit of real world math where if this is a percentage
off like the number 15 for 15 percentage points I need to do like 100 minus that many percentage points thereby giving me
100- 15 85 and then I need to divide that by 100 in order now to give myself 85 five times the price that was passed
in but if I go ahead now and save this run make discount one last time I notice that I've actually got an error here
what have I done wrong well I need to change that prototype too and again this is admittedly an annoying aspect of C
that you have to maintain consistency here but that's fine I'm just going to go up here change this to int percentage
spelling incorrectly and now let me retry compilation make discount crossing my fingers this time worked okay/
discount and while $100 and percent off say 15 points and voila
$85 now it's worth noting that I've deliberately returned the results of my math from this function I haven't just
done the math on the original variable that's being passed in in fact if we take a look at this second version where
discount is now taking a price argument and a percentage argument notice that I'm not doing something like this I'm
not just saying price equals price time 100 - percentage divided by 100 and leaving it that the problem there is
that this variable price is going to be scoped to that discount function and we'll encounter this again before long
but this notion of scope just refers to where in which a variable actually lives or exists or is accessible so it turns
out if I change price in the context of this discount function that's not going to have a lasting effect if I actually
want to get the result back to the function that use the discount function namely main I actually do need to take
this approach of actually returning the value explicitly so that ultimately I'm handing back the discounted price all
right well let's go ahead and maybe how about let's just use these Primitives in just a few different ways how about
little game of uh yester year Super Mario Brothers and in the original Super Mario Brothers and in bunches of Varian
so you have like these uh sidescrolling worlds that look like this where there's some coins in the sky hidden behind
these question marks so let's just use this as a visual to consider how and see could I start to make something semi-
graphical like not actual colors or fanciness that feels like too much too soon just something like printing out
some question marks well if I go back over here let me create that actual file that I alluded to earlier so let me code
up mario.c let me go ahead and include standard i.h in main void again which
we'll continue to copy paste for today and then let me just go ahead and do something simple like one two 3 4 and a
new line all right this is what we might call asky Art which just means Graphics but really just implemented with your
keyboard and if I make Mario and do/ Mario it's not nearly as engaging visually as this but it's the beginning
of this kind of map for a game well if I wanted to now print out of those things dynamically let me go back to my code
here and instead of printing out four all at once I could do something like four in I get zero I less than four i++
and then inside here I could just print out one of them at a time let me save that make Mario and at the risk of
disappointing so close but I made a mistake just stupid aesthetic the The Prompt is not on the
new line how could I move it yeah I need an escape character the back slash n
but should I put it here okay no because that's going to put it after everyone and it's going to make
this thing vertical instead of horizontal so logically just like in scratch put it at the end of the loop so
something out here and just print out for instance only quote unquote new line and now if I do make Mario again/ Mario
okay we're back in business but a little better designed in that now I'm not repeating myself multiple times I'm
doing this again and again but let's do one other thing here with Mario let me go ahead and ask the user how many
question marks or coins to print the catch here is that there's another type of loop that's helpful for this and it's
called a do while loop generally a do while loop is similar to a while loop but it checks the condition last instead
of first recall earlier on the slide we had while open parenthesis closed parenthesis and I kept claiming that we
check whether I is less than whatever it was three in advance again and again a Doh Loop just inverts the logic so that
you can actually do something like this at the top of this program I'm going to go ahead now and give myself a variable
n like this of type integer and then I'm going to do literally the following with the keyword do
n equals get int and I'm going to ask the user for the width like the number of dollar signs to print and I'm going
to do this while n is less than say one so this is a little cryptic but the Salient differences are the while the
Boolean expression is now at the bottom of my block of code not at the top now why is this well the difference here if
I make Mario is whoops uh I need to add cs50.h because I'm now using get int if I now
compile this version of Mario and do/ Mario do while loop is helpful when you want to do something no matter what
first and then check some condition or some Boolean expression to see if maybe in this case the user cooperated it
would make no sense if the user typed in say zero because like there's no work to be done it' be really weird if they said
Nega 100 because that makes no sense logically so with this simple construct here on I am doing the following while n
is less than one the implication is that as soon as n equals 1 or as bigger than one I'm going to break out of this Loop
and I've got myself a variable called n containing essentially a positive value one through two billion or so and I can
now use this for instance here change the four to an N so now my program is completely Dynamic let me go ahead and
do make Mario do/ Mario again and I'll do four still works I'll do 40 still works and
the difference here with the do while is if something like this involves getting user input well there's no question to
ask like the user hasn't given you anything yet so you have to do something first then check and break out of the
loop if the human has for instance cooperated in this case all right well why don't we escalate to something more
like this in the same game where your underground is Mario and this is like a two-dimensional uh wall that's popping
up here it looks like a 3X3 for instance for the sake of discussion and it's like made out of bricks so I'll use maybe
hash symbols this time well it turns out that we can Nest that is combine some of these same ideas as follows let me go
ahead now and change back to this code and I'm going to keep the do while loop from before and I'm going to ask though
this question what's the size of this Square I'm going to assume it's like x n byn so uh 3x3 4x4 whatever so I'm just
going to ask for the size of the square of bricks and now how do I do this well I'm going to go ahead for instance and
print out how about four in I gets Zer I less than N I ++ let me just keep it simple and print out something like this
just a single hash symbol that is a brick and a new line after it all right let's make Mario Run Mario of three okay
that's close to being it I've got a column all right but I I need it to be wider so the solution last time was to
get rid of the new line and then maybe put the new line here out after the loop all right so let's do make Mario do/
Mario and uh type in three and huh all right so I kind of need to combine these two ideas somehow so how might we solve
this problem I want to print like rows and columns not row or
column how do I do this yeah Loop yeah add another loop in the for Loop right if you use one Loop
conceptually to kind of count the rows from top to bottom and then within each row you then sort of typewriter style
old school typewriter do like character character character character horizontally I think we could do exactly
what we want to achieve here so how about this let me get rid of this line and get rid of this line for now and let
me just give myself another loop on the inside and since I'm already using I another reasonable convention here would
be to say something like J so J also gets zero J is less than n j++ and now what's going to happen let me go ahead
and print out just one of these things at a time and let me save and write let me run this let me see if it how close
we are make Mario three okay three that's clearly wrong but I see nine things there on the screen so we're
close what's the one fix I need now to sort of move the old school typewriter head down to the next row when a
appropriate what do you think yeah I need one of these back slash ends and probably let me add some
comments now to help everyone visualize what I've done for each row for each column how about print a brick just to
kind of explain the logic and so I add that because now move to next row I could do something like this with a back
slash n so here's where the the comments really my pseudo code actually kind of illuminates the situation a bit let me
go ahead and recompile Mario Mario 3 now we're talking it's not a perfect square just because these hash symbols are a
little taller than they are wide but that's just a font detail here now I've done something that's quite more akin to
something like this all right so let me pause here and see if there are any
questions again the code's getting a little more complicated but we're just building like more complicated programs
like in scratch like familiar puzzle pieces some variables Some Loops some conditionals it's all the same as before
yeah can you multiply strings in C no uh but ask that same question again in a few weeks when we get to Python and the
answer will be yes other questions yeah in C you must specify the return type the name of the function and the inputs
or arguments to the function in that order and if none of them are applicable you write the word void uh so same
question as earlier let me kick that can a week or so and we'll come back to that and we'll see why but for now just take
on faith that you need to do that with Maine because Maine is a little special similar to the when green flag is
clicked it too was a little special as well yeah yes if you want to get out of a
loop early you could do this so let let me answer this question this way an alternative to a do while loop would be
to do something like this uh how about while true so do the following forever let me go ahead and get an INT from the
user for the size of this thing if n is greater than zero that is a positive integer then go ahead and use a new
keyword called break this is identical to what we just did it's just a little longer it's like a couple extra lines a
lot of them are blank and so it's just an alternative but a do while does the same thing but a little tighter if