hi I'm Kerry Ann welcome to crash course
computer science last episode we
discussed how writing programs in native
machine code and having some contend
with so many low-level details was a
huge impediment to writing complex
programs to abstract away many of these
low-level details programming languages
were developed that let programmers
concentrate on solving a problem with
computation and less on Missy gritty
Hardware details so today we're going to
continue that discussion and introduce
some fundamental building blocks that
almost all programming languages provide
[Music]
just like spoken languages programming
languages have statements these are
individual complete thoughts like I once
he or it is raining by using different
words we can change the meaning for
example I want t to I want unicorns but
we can't change I want to eat I want
rain but doesn't make grammatical sense
the set of rules that govern the
structure and composition of statements
in a language is called syntax the
English language has syntax and so do
all programming languages a equals five
is a programming language statement in
this case the statement says a variable
named a has the number five stored in it
this is called an assignment statement
because we're assigning a value to a
variable to express more complex things
we need a series of statements like a is
5 B is 10 C equals a plus B this program
tells the computer to set variable a
equal to 5 variable B to 10 and finally
to add a and B together and put that
result which is 15 into you guessed it
variable C now we can call variables
whatever we want instead of a B and C it
could be apples pears and fruits the
computer doesn't care as well as
variables are uniquely named but it's
probably best practice to name the
things that make sense in case someone
else is trying to understand your code a
program which is a list of instructions
is a bit like a recipe boil water add
noodles wait 10 minutes drain and enjoy
in the same way the program starts at
the first statement runs down one at a
time until it hits the end
so far we've added two numbers together
boring let's make a video game instead
of course it's way too early to think
about coding the entire game so instead
we'll use our examples write little
snippets of code that cover some
programming fundamentals imagine we're
building an old-school arcade game a
graceful faster capture bugs would get
into the Harvard mark 1 and crash the
computer on every level the number of
bugs increases grace has to catch them
before they wear out any relays in the
machine fortunately she has a few extra
relays for repairs
to get started we'll need to keep track
of a bunch of values that important to
gameplay like what level the player is
on the score the number of bugs
remaining as well as the number of spare
relays in Gracie's inventory so we must
initialize our variable that is set
there initial value level equals one
score equals zero bugs equals five spare
relays equals 4 and player name equals
Andre to create an interactive game we
need to control the flow of the program
you aren't just running
top to bottom to do this we use control
flow statements there are several times
but if statements are the most common
you can think of them as if X is true
then do Y an english-language example is
if I am tired then get T so if I am
tired is a true statement then I will go
get T if I am tired is false then I'll
not go get T and in state when is like a
fork in the road which path you take is
conditional whether the expression is
true or false so these expressions are
called conditional statements in most
programming languages an if statement
looks something like if expressions then
some code then end the if statement for
example if level is one then we set the
score to zero because the player is just
starting we also set the number of bugs
to one to keep it easy for now notice
the lines of code that are conditional
on the if statement I messed it between
the if and end it of course we can
change the conditional expression to
whatever we want to test like if score
greater than 10 or is bugs less than 1
and if statements can be combined with
an else statement which acts as a catch
or if the expressions false if the level
is not 1 the code inside the else block
will be executed instead and the number
of bugs that grace has the battle is set
to 3 times the level number so on level
2 it would be 6 bugs and on level 3
there's 9 and so on score is are
modified in the else block so grace gets
to keep any points earned here are some
examples of if-then-else statements from
some popular programming languages you
can see the syntax varies a little but
the underlying structure is roughly the
same if statements are executed once a
conditional path is chosen and the
program moves on to repeat some stain as
many times we need to create a
conditional loop one way is a while
statement also called a while loop as
you might have guessed this leaves a
piece of code while our conditions true
regardless of the programming language
they look something like this in our
game let's say at certain points a
friendly colleague restocks Grace of
relays pray to animate him replenishing
our stock back up to a maximum for we
can use a while loop let's walk through
this code first we'll assume that grace
only has one tube left when her
colleague enters when we enter the while
loop the first thing the computer does
is test its conditional is relays less
than 4 well relays is currently 1 so yes
now we enter the loop then we hit the
line of code relays equals relays plus 1
this is a bit confusing because the
variable is using itself as an
assignment statement so let's unpack it
you always start by
hang out the right side of the equal
sign first so what does relays plus one
come out to be well relays is currently
the value 1 so 1 plus 1 equals 2 then
this result gets saved back into the
variable relays writing over the old
value so now relay stores a value 2
we've hit the end of the while loop
which does the program back up just as
before we test the conditionals to see
if we're going to enter the loop is
relays less than 4 well yes relays now
equals 2 so we enter the loop again 2
plus 1 equals 3 so 3 is saved in two
relays loop again is 3 less than 4 yes
it is into the loop again 3 plus 1
equals 4 so we save 4 into relays loop
again is 4 less than 4 no so the
condition is now false unless we exit
the loop and move on to any remaining
code that's how a while loop works
there's also the common for loop instead
of being a condition controlled loops
that can repeat forever until the
conditions force R for loop is count
controlled it repeats a specific number
of times they look something like this
now let's put in some real values this
example loops 10 times because we've
specified that variable I start for the
value 1 and goes up to 10 unique thing
about a for loop is that each time it
hits next it has one time when I equals
10 the computer knows it's been looped
10 times and the loop exits we can set
the number to whatever we want 10 22 or
a billion it's up to us let's say we
want to give the player a bonus at the
end of each level the number of vacuum
relays they have leftover as the game
gets harder it takes more skill to have
onions relays so we want the bonus to
grow up exponentially based on the level
we need to write a piece of code that
calculates exponents that is multiplying
a number by itself a specific number of
times a loop is perfect for this first
let's initialize a new variable called
bonus and set it to 1 then we create a
for loop starting at 1 and looping up to
the level number inside that loop we
multiply bonus times the number of
relays and save that new value back into
bonus for example let's say relays
equals 2 and level equals 3 so the for
loop will look 3 times which means bonus
is going to get multiplied by relays by
relays by relays or in this case times 2
times 2 times 2 which is a bonus of 8
that's 2 to the third power this
exponent code is useful and we might
want to use it in other parts of our
code it'd be annoying to copy and paste
this everywhere and have to update the
variable names each time
also if we found a bug we'd have to hunt
around an update every place we used it
it also makes code more confusing to
look at less is more
what we want is a way to package up our
experiment code so that we can use it
get the result and not have to see the
internal complexity we once again moving
up a new level of abstraction to
compartmentalize and hide complexity
programming languages can package pieces
of code into named functions also called
methods or subroutines in different
programming languages these functions
can then be used by any other part of
that program just by calling its name
let's turn our exponent code into a
function first we should name it we can
call it anything we want like happy
unicorn but since our code calculates
exponents let's call it exponent also
instead of using specific variable names
like relays and levels we specify
generic variable names like base and X
whose initial values are going to be
passed into our functions from some
other part of the program the rest of
our code is the same as before now
tucked into our function and with new
variable names finally we need to send
the result of our exponent code back to
the part of the program that requested
it so this we use and statement and
specify the value in result be returned
so our full function code looks like
this now we can use this function
anywhere in our program simply by
calling its name and passing in two
numbers for example if we want to
calculate 2 to the 44th power we can
just call exponent 2 comma 44 and like
18 trillion comes back behind the scenes
2 and 44 gets saved in two variables
base and X inside the function it does
all of its loops as necessary and then
the function returns with the results
let's use our newly minted function to
calculate a score bonus first we
initialize bonus to 0 then we check if
the player has any remaining relays with
an if statement if they do we call our
exponent function passing in relays and
level which calculates relays for the
power of level and returns the result
which we save into Boehner this bonus
calculating code might be useful later
so let's wrap it up as a function - yes
a function that calls a function and
then wait for it we can use this
function in an even more complex
function let's write one that gets
called every time the player finishes a
level we'll call it level finished
it means to know the number of relays
left what level it was and the current
school those values have to get past it
inside our function will calculate the
bonus using our calculus function and
add that to the running score also if
the current score is higher than the
game's high school we save the new high
score and the players name finally we
return the current score now we're
getting pretty fancy functions recording
functions according functions when we
call a single line of code like this the
complexity is hidden we don't see all of
the internal loops and variables we just
see the result come back as if by magic
a total score of 53 but it's not magic
is the power of abstraction if you
understand this example then you
understand the power of functions and
the entire essence of modern programming
it's not feasible to write for example a
web browser as one gigantically long
list of statements it would be millions
of lines long and impossible to
comprehend
so instead software consists of
thousands of smaller functions each
responsible for different features in
modern programming it's uncommon to see
functions longer than around 100 lines
of code because by then there's probably
something that should be pulled out made
into its own function modular lysing
programs into functions not only allows
a single programmer to write an entire
app but also allows teams of people to
work efficiently on even bigger programs
different programmers can work on
different functions and if everyone
makes sure their code works correctly
then when everything is put together the
whole program should work too and in the
real world
programmers aren't wasting time writing
things like exponents modern programming
languages come with huge bundles of
pre-written functions called libraries
these are written by expert Cody made
efficient and rigorously tested and then
given to everyone there are libraries
for almost everything including
networking graphics and sound topics
we'll discuss in future episodes but
before we get to those we need to talk
about algorithms intrigued you should be
I'll see you next week
crash course computer science is
produced in association with PBS Digital
Studios at their channel you can check
out a playlist of shows like physics
girls deep looks at PBS space time this
episode was filmed at the channel space
you have a go studio in Indian
Indiana and it was made with the help of
all these nice people and our wonderful
graphics team is thought cafe that's
where we're going to have to halt and
catch fire see you next week
[Music]