0% found this document useful (0 votes)
43 views

CS50-Intro To Programming

This document provides an introduction to programming concepts like pseudocode, loops, conditions, and parallel execution using the visual programming language Scratch. It explains programming basics like compiling, variables, and control flow through examples and compares programming in Scratch to other languages like C.

Uploaded by

Hasmutia Hassan
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

CS50-Intro To Programming

This document provides an introduction to programming concepts like pseudocode, loops, conditions, and parallel execution using the visual programming language Scratch. It explains programming basics like compiling, variables, and control flow through examples and compares programming in Scratch to other languages like C.

Uploaded by

Hasmutia Hassan
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 10

Announcements and Demos (0:00-10:00)

This is CS50.

Check out what is possible in the programming language called


Scratch that we will begin the course with! Scratch will enable you to wrap
your mind around the fundamental constructs of programming while making
a cool game or animation.
Be sure to check out the second annual CS50 Puzzle Day this

Saturday! Thanks to Facebook for sponsoring!


CS50 is all about getting you through CS50. We want you to make it

to the final days and gain that practical skill set to take with you to
engineering sciences, applied math, natural sciences, or really any
discipline.
As you make your way through the semester, try to keep the following

snippet in mind:
what ultimately matters in this course is not so much where you end up
relative to your classmates but where you, in Week 11, end up relative to
yourself in Week 0
Know that you are not at a disadvantage at all for being one of those

less comfortable or somewhere in between. We have specially designed


several different tracks through this course and well help you fit into one of
them.

Avail yourself of CS50 Discuss, our online discussion forum.

Office Hours begin on Monday! Theyll be held Mondays through


Thursdays, 8 p.m. to 11 p.m. in Annenberg Hall.

Sometime this weekend, please visit cs50.net/section to give us your


sectioning preferences.

The first Walkthrough is today at 3 p.m. in Harvard Hall 104! Zamyla


Chan will be your fearless leader for Walkthroughs this semester.

Intro to Programming (10:00-63:00)

Lets begin our foray into programming with pseudocode.


Pseudocode is not a programming language, per se, but rather a way of
expressing ourselves somewhat precisely, and somewhat algorithmically
without having to worry about real syntax.

Putting on Socks

Lets see if we can write an algorithm for putting on socks in the


morning. David will follow our instructions exactly and Joseph will write
them down:

1.

bend down

2.

pick up your sock

Here we have a bit of ambiguity. Which sock? Before long, well need
to express ourselves more precisely so the computer knows exactly what
were trying to accomplish.

Now, we want to find a matching sock. This is instinctive for a human


(who can scan them all quickly with his eyes), but not so for a computer. In
order to find a matching sock, we have to iterate or loop through all of the
socks and compare them to the one we have. Something like this:

1.

bend down

2.

pick up your sock

3.

find matching pair

4. for each sock


5.

pick it up...

6.

if it's the same shape/size

7.

take it

8.

identify right and left


Notice that Joseph has already started following one programming

convention: indentation. When you construct a loop, the chunk of code that
gets executed with each iteration of the loop is usually indented. Likewise
with the code that meets a certain condition (e.g.

take it

in the example

above).
1.

bend down

2.

pick up your sock

3.

find matching pair

4. for each sock


5.

pick it up...

6.

if it's the same shape/size

7.

take it

8.

identify right and left

9.

lift up right leg

10.

find open end of sock

11.

touch toes

12.

put on sock

Now that weve taken care of one foot, we need to make a design
decision to take care of the second foot. Should we write another loop?
Perhaps. Since we only have two cases to handle, we could simply copy

and paste the steps above. However, anytime you find yourself copying and
pasting code, you should probably consider using a loop instead.
Our program is buggy! What happens if theres no matching sock?

What if there is only one sock? What if David already has socks on? We
havent handled these so-called corner cases, which could cause problems
going forward. Generally, when you make assumptions while writing
programs (e.g. of course there will be enough disk space!), you risk
introducing bugs.

Lets take a look at a short program in C:

#include <stdio.h>

int main(void)

printf("hello, world!");

The syntax is fairly cryptic, but you can probably guess what this
program does: it writes hello, world! to the screen.

Whether you have a Mac or a PC, you can use software applications
to write programs like this. On a Mac, you can use a program called
Terminal to execute programs like this. The Terminal interface is
reminiscent of computers from the past which didnt have graphical user
interfaces (GUIs).

After we open up a text editor, we insert the lines of code above and
save the file as hello.c. This file now represents our source code. As weve
already learned, computers cant understand anything but binary, so we

need to translate this source code into binary. This same code in binary is
called object code. To do this translation, we run the following from the
command line:

clang hello.c

Although nothing seems to have happened, we can actually now see


that a file named a.out has been created in our home
directory.a.out contains the 0s and 1s of our converted program. Now that
it has been converted, we can execute it like so: ./a.out

It worked! Unfortunately, its not very pretty. It seems to have


printed hello,

world!

followed by something like air:~

jharvard.

That last bit,

however, is actually printed at the beginning of every line of our Terminal


window. It designates the computers name, the current directory, and the
username. So it seems that our program worked, but it would have been
prettier if we could have hit Enter afterhello,

world!.

We can do this by

inserting whats called a linebreak. We represent a linebreak in code with


a \n like so:

#include <stdio.h>

int main(void)

printf("hello, world!\n");

Now if we rerun our program, we getthe same thing. Oops, we


forgot to re-translate our source code to object code. The process of
translating source code to object code is called compiling. We need to
recompile our program. If we do so and then rerun it, we get our pretty
output as wed hoped for.

What does a.out actually contain? If we try to examine it using a text


editor, we get junk. This is because the text editor is misinterpreting the 0s
and 1s as ASCII characters. Somewhere amidst the junk, you can actually
see the words hello, world!

To look at the actual 0s and 1s that

a.out

contains, we can execute

the following command:

xxd -b a.out

Back in the day (when David was like 34 or so), a programmer would
have had to physically punch holes in cards to represent his or her
program. Luckily, we now have CPUs that can interpret the 0s and 1s
directly.

Scratch

To start working with Scratch, youll need to download the program


from MITs website.

Once you install Scratch and open it, take note of the following layout:

On far left, notice the palette of puzzle pieces, which represent


programming statements. Programs will be composed by putting puzzle
pieces together in a particular order.

At bottom right are sprites, or characters that will carry out your
instructions.

At top right is the stage, where the program will be carried out.

To the left of the stage is the scripts area, where puzzle pieces
must be dragged and strung together.

If we open up Dancing

cookies.sb,

we see that the cookies are sprites

and in the scripts area, there are two long chains of puzzle pieces joined
together, each with a when green flag clicked piece at the top. Recall that

to start the animation, we clicked a green flag, which suggests that both of
these scripts start running as soon as we do so.

We can recreate our very simple C program in Scratch using the say
block. Hello1.sb is equivalent to hello.c, only a little more colorful.

Before we go any farther, lets talk about some computer science


jargon: a statement is an action that we give to the computer to perform. In
the context of Scratch, statements begin with verbs like say, play, and
wait.

So far weve only made use of statements, which are direct


imperatives given to the computer. But if we want to introduce logic into our
program, well need boolean expressions and conditions. Boolean
expressions are those that have only two possible values: true or false, yes
or no, on or off, 1 or 0. No matter how you say it, its a simple variable. In
Scratch, boolean expressions are represented as hexagons and are written
as yes-or-no questions such as touching mouse-pointer?, mouse down?
or comparisons such as less-than, equal-to, or greater-than.

Hello2.sb

is slightly more complicated. The cat will say O hai, world!

for 1 second, wait 1 second, say it again for 1 second, wait 1 second, and
say it again for 1 second. This seems a little wasteful and, in fact, we could
implement this more cleanly using the repeat block.

Hello4.sb

and Hello5.sb make use of conditions and boolean

expressions. In the first, the condition 1 < 2 always evaluates to true, so the
cat meows every time we click the green flag. In the second, however, the
condition says, pick a random number between 1 and 10 and if that
number is less than 6, have the cat meow. Thus, the cat will meow
approximately half the time we click the green flag.

In Hello6.sb, we implement a loop which causes the cat to meow


indefinitely. Infinite loops arent necessarily bad: consider the case of the
clock on your computer which is constantly updating the time.

In Hello7.sb, we combine a loop and a condition so that the cat will


meow only if the mouse pointer is touching it or, in other words, if we are
petting it. In Hello8.sb, we add an extra condition (using the

keyword)

else

so that the cat will meow indefinitely, but will roar if we touch it with the
mouse pointer.

Hello9.sb

executes two scripts in parallel (as Dancing

cookies.sb

the logic of one of these scripts, we see that if a variable named

did). In

muted

is 0,

we play the sound. Variables are another useful programming construct.


They allow us to store information about the state of a program. Recall that
0 is equivalent to false, so this makes sense: if the script is not muted, it
should play sound. The second script actually sets the variable

muted:

to 1 if

its currently 0 or to 0 if its currently 1. This variable setting occurs when we


press the space bar. Note that variables in programs should have
descriptive names, as with muted here.

Boolean expressions arent new to you. Consider on HarvardCourses


when you search for courses and check a checkbox for course > 4.5.
Somewhere in the code, that translates to a boolean variable that signifies
either course > 4.5 or not.

Arrays are essentially collections of related variables. In the


game FruitcraftRPG.sb, for example, an array is used to store the different
types of fruit which have been collected. An array is one of many different
types of data structures which are essentially buckets in which we can store
information of interest to our program.

Check out Scratch

Scratch Revolution.sb.sb)

and btwalsh.sb for more

examples of what you can do with Scratch! Realize that they didnt
implement these complex games all in one sitting. Rather, they broke them
down into bitesize pieces. In the case of Scratch Scratch Revolution,
maybe the student first implemented support for the left arrow key only.
Then maybe the student implemented the green arrow that flies from the

bottom of the screen. He or she might have then introduced


some pseudorandomness, i.e. picking a number between 0 and 5 as we did
earlier. We say pseudorandom instead of random because a computer
cant actually be random.

Now is a good time to introduce the concept of threads. In the context


of your computer, threads are what allow you to have multiple software
applications open at once. Your computer isnt actually doing multiple
things at once (unless it has a multicore processor); rather, its switching
back and forth between tasks faster than you can perceive.

Threading refers to the notion of multiple threads of code executing


simultaneously. In Threads.sb, we achieve multithreading, at least in
appearance. In terms of programming, we have two different scripts
associated with two different sprites, a cat and a bird. For the cat, we begin
by placing him in a given spot on the stage and orienting him in a random
direction. Then we begin a loop whereby if he touches the bird, then the
game ends; otherwise, we orient him toward the bird and advance him one
step. For the bird, we move him around the stage three steps at a time.
Effectively, then, the cat is chasing the bird until he catches him. If we
increase the number of steps that the cat takes compared to the bird, the
cat will catch the bird all the more quickly.

Events are another method of communicating between


sprites. Events.sb leverages events to play the game of Marco Polo. Thus
far, our sprites havent really been communicating with each other. But in
this game of Marco Polo, one sprite is saying Marco, and the other is
listening for him to say it so that she can say Polo in response. The
second sprite is listening for the event which the first sprite broadcasts.

The objective of Problem Set 0 is for you to have fun playing around
with Scratch (or BYOB in the case of the Hacker Edition). Make something
interesting, interactive, artistic, fun. Dont feel like you need to implement

Scratch Scratch Revolution, but hopefully youll be proud of what you make,
enough to show it off to your friends and family once youve uploaded it to
MITs website.

We leave you with Raining


you might implement it!

Men.sb.

While you enjoy it, think about how

You might also like