[go: up one dir, main page]

0% found this document useful (0 votes)
35 views37 pages

The Little Introduction To Programming (1)

Programming is a creative and problem-solving process that involves writing instructions for computers to create software. A program consists of components like statements or lines of code, which are organized using programming languages that define their syntax. Understanding data types and variables is crucial, as they allow programs to handle user input and perform actions based on that data.

Uploaded by

Robin Blake
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views37 pages

The Little Introduction To Programming (1)

Programming is a creative and problem-solving process that involves writing instructions for computers to create software. A program consists of components like statements or lines of code, which are organized using programming languages that define their syntax. Understanding data types and variables is crucial, as they allow programs to handle user input and perform actions based on that data.

Uploaded by

Robin Blake
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Introduction In

Programming is the process of writing instructions for computers to produce software for users.
W
It's the combining of minute details to form a cohesive whole. More than anything, it is a creative
and problem-solving activity. The problem solving aspect of programming will become self-evident

as we move forward. For now, I'd like to talk about the creative side.

At a high level, it's obvious that creating software requires creativity. You are building something

for people to use. It must therefore be clever without being complex. It must be intuitive and
elegant. What isn't obvious to most people is that creativity plays an equally important role at the

micro level of building software. Every instruction that you type requires consideration. In this
respect, I've always likened programming to writing a book or painting a picture. Ultimately you
have a ᴀ밄nished product, but it's the sentences and the strokes, and how they are combined, which
P
is where the book, painting or program truly comes to life.

I sincerely believe that programming is a beautiful thing. However, I warn you that learning to

program isn't trivial. You should be able to learn the basics with relative ease. Unfortunately, going
from these basics to being able to write a useful program isn't easy. In fact, it can be quite
frustrating. I tell you this so that you know what to expect, not to discourage you. How far you take

this journey is up to you, this is but a start.

What's a Program
I
You already know what a program is. You use an email program, surf the web in a browser and
interact with various websites every day. You text, take pictures, and check the weather on your
phone. A program is the output, or goal, of programming.

Much like a book is made up of chapters, paragraphs, sentences, phrases, words and ᴀ밄nally
punctuation and letters, so too is a program broken down into smaller and smaller components.
For now, the most important is a statement. A statement is analogous to a sentence in a book. On

its own, it has structure and purpose, but without the context of the other statements around it, it
isn't that meaningful.
A statement is more casually (and commonly) known as a line of code. That's because statements
tend to be written on individual lines. As such, programs are read from top to bottom, left to right.
You might be wondering what code (also called source code) is. That happens to be a broad term
In
which can refer to the whole of the program or the smallest part. Therefore, a line of code is

simply a line of your program. W

I think this would be a good time to introduce our ᴀ밄rst little program. There are more concepts

and terms to learn, but it will be useful to have something to visualize.

deck = ["2 of Hearts", "3 of Hearts", "4 of Hearts", "5 of Hearts"]


shuffled_deck = shuffle(deck)
first = shuffled_deck.first
print first

Although it's rather short, there's a lot going on here. We won't go into any of this in great detail. P

For now what's important is that our program is made up of four lines of code and that the
program is read from top to bottom. The purpose of this program is to pick a random card from a

partial deck.

The ᴀ밄rst line collects a limited number of cards into a container, our deck. Next, we shuᴀ甇e the

deck. Finally, we pick the ᴀ밄rst card (which at this point could have any value) and print it out on the
screen. You might be tempted to analyze this deeper. For example, maybe you are curious about

the meaning of the square brackets [] in the ᴀ밄rst line of code. Or maybe you're wondering about

the implication of the equal sign = . Those are all things we'll eventually cover. For now, this is a
I
program made up of four lines of code which create a deck, shuᴀ甇es it, picks the ᴀ밄rst card and

prints it.

There are a lot of ways to write this program. The approach shown above is similar to how it works

in the real-world, which makes it easy to understand. This is where creativity, at a micro level,
comes into play. A good programmer wants to write code which is understandable to other

programmers (and to his or her future self), which is correct (or bug free), and which performs

eᴀ甇ciently. Balancing these three aspects of programming is fundamental. But there's no shortcut
to mastering this, one must learn through experience.
Programming Languages

We have an idea of what a simple program looks like: a collection of lines of code. But that's still In

quite vague, so let's peel away the layers.


W
When you write a program you do so using a programming language. A programming language

deᴀ밄nes the syntax that you use to write your program. In our above example, we used square

brackets [] to group together our cards. A diᴀ洅erent programming language might insist that you

use parenthesis () . We used print to output the picked card, while another language might use

echo . You could say that diᴀ洅erent programming languages are like diᴀ洅erent spoken and written

languages. The same book written in diᴀ洅erent languages tells the same story; much like a
program written in diᴀ洅erent programming languages would have the same purpose. However,

programming languages tend to be more similar than dissimilar and a more accurate comparison

might be to dialects.
P
Programming languages deᴀ밄ne more than just the syntax, but for now, that's all we'll concern

ourselves with. Thankfully even though some languages are vastly diᴀ洅erent than others, most
share a lot of common ground, so that once you know your ᴀ밄rst language, other languages are

much easier to pick up.

The processor in your computer, or smartphone, doesn't know anything about a deck, card or
even about printing something on the screen. These processors speak a basic language and
require detailed instructions on what to do and how to do it. Writing our above sample in this low-
level language might require 50 or more individual statements, none of which is obvious to read

or write. This means that on the one hand, you have programming languages that humans can I

understand, on the other you have languages that computers understand. What's needed is a
translation process to go from the code that we write, to the code that a computer reads. This

process is known as compiling your code. A compiler takes your high-level program as input and
outputs a low-level program which your computer will understand.

Even as your knowledge progresses, you'll probably never have to know the details of assembly or
compilers. They are both advanced topics which an increasingly rare number of programmers
focus on. Why bring it up at all then? First, because learning to program is more than learning the

correct sequence of statements to write down. It's also about understanding, even at a high level,
the metamorphosis of your code from what you write to what ends up actually being executed.
Secondly, and more importantly, it introduces the important topic of abstraction.

We've already seen that the code we'll write and the code that the CPU will execute aren't the In

same thing. The details of assembly are abstracted away from us by the compiler. This is only one
W
of many layers of abstraction. These layers of abstraction help programmers deal with the ever-
increasing complexity of programming. It's abstraction that makes it possible for us to write a few

understandable lines of code to shuᴀ甇e a deck, without having to worry about the various building
blocks which others have provided for us; like, how does shuffle randomly mix up our deck? But

abstractions aren't perfect, and ignorance isn't always bliss. Sometimes a lower level concept will
break through the abstraction. Sometimes we'll need to get our hands dirty to achieve what we

want.

The point is that while we'll focus on writing programs using modern techniques, know that

there's en entire foundation which makes it all possible. Sometimes, those underlying elements
P
will become visible, say by means of a cryptic error message. Also, rather than sugar-coating what
programming is, you now hopefully have a more meaningful sense of it beyond simply being a list

of written statements for the computer to follow.

In This Chapter

This chapter served to introduce some basic concepts of programming. If it seemed


overwhelming, don't worry. Most of what we talked about is rather broad and it isn't until we start

ᴀ밄lling in the pieces that the picture will sharpen. Having said that, let's recap what we have
I
learned.

First, a program is made up of sub-components, which themselves are made up of sub-


components. The most interesting, for now, is the statement or line of code. This tends to
represent a cohesive instruction; for example, add two numbers, shuᴀ甇e these values, or print this
value to the screen.

Secondly, there are many programming languages, which deᴀ밄ne the syntax and rules that we'll
follow, but most share common ground. Our focus will be on learning this common ground.

Finally, in order to be executed, our program leverages building blocks written by other
programmers and gets transformed into assembly, which is the language understood by a
computer. As new programmers, this is a fairly minor detail that we can safely ignore. However,
professional programmers who completely ignore their foundation do so at their own peril.
In

I
Learning the Basics
In the previous chapter we broke a program down into the vague concept of lines of code. In this

chapter, we'll start to explore some of the more frequent parts which go into making a line of
code.

Before jumping directly into a list of terms with an accompanying description and small code

samples, let's ခ肀rst try to think about a program's components abstractly.

Consider the scenario of registering a user on a website. A basic implementation might ask for an
email and password. What might the code to register this user look like? First we'll collect the two

provided pieces of information: the email and password. Next we'll probably want our program to
verify this data: is the password long enough and is the email valid? If either of these things aren't
true, we'll display an error message. Otherwise, we can save the information so that it can be used

at a later point.

What about withdrawing money from your bank? First you enter your card and security pin. Again,

the program collects this information and veriခ肀es it. If it's invalid, it'll display an error and repeat
until the information provided is valid. Once valid, you provide a third piece of information, the
amount you wish to withdraw. If the amount is too large, it'll once again display an error.

Otherwise, the amount if subtracted from your account balance (a forth piece of information

which, sadly, isn't supplied by you, but stored in the bank's system) and the requested funds made
available.

Neither of these descriptions tell us how to actually write programs. However, they both expose 3

core aspects of programming. First, both deal with data or values. The ခ肀rst deals with an email
and password, the second with an account number (retrieved from the card), your pin, your
withdrawal amount and your account balance. Second, they both apply conditional logic. If the
password is too short, or the withdrawal amount too large, display an error; otherwise, proceed to
the next step. Finally, they both perform actions. For our account withdrawal, this is a simple

subtraction of the withdrawn amount from our account balance. For the user registration, it's the
process of saving the new user information for later use.

In other words, programs:


Deal with data from various sources (user input, ခ肀le, the internet, ...),
Determine a course of action based on this data, and
Perform the appropriate action

This isn't too di肠ကerent than how we perform many day to day tasks. As you approach a traက䂠c light,
you collect data about your environment. At its simplest, you care about the color of the traက䂠c
light. If it's red or yellow, you stop. If it's green, you go. In reality, there are considerably more data

points that you consider: the condition of the road, your current speed, what the cars and
pedestrians around you are doing, how anxious you are to get home and so on and so forth. Our
brain's ability to quickly consider all of these things and make such a absolute stop-or-go decision
is impressive. A program isn't any di肠ကerent, except that every condition has to be explicitly

expressed. There's no intuition, only the deခ肀ned rules that we, as programmers, speciခ肀ed.

Dealing With Data - Types

The ခ肀rst thing we need to do is understand the basics of how a program deals with data. If you
think about it, data can be broken into types. For example the make and model of your car is a

string. Your age is a number. Whether you ခ肀nd this book is interesting or not is either true or false

(known as a boolean). Strings, numbers and booleans represent the three types we'll concern
ourselves with for now. However there are certainly other, more complex types. An address, for

example, can be broken down into smaller components (street number, street name, city and
country) but it often makes sense to think of an address as a single cohesive type.

In a program, telling what type of data we are dealing with isn't diက䂠cult:

"A string is enclosed in quotes"


3.1415
true

Above we have a string, followed by a number, followed by a boolean. Anything enclosed in


quotes is a string. While neither a number nor a boolean is enclosed in strings, it's always clear

which is which. What about a string that looks like a number or a boolean, for example:

"false"
"9001"

These are still strings, because they are enclosed in quotes. However our programming language

allows us to convert the ခ肀rst to a boolean and the second to a number. At this point, this isn't

important but it's explained in case you were wondering what happens if a number is enclosed in
quotes.

Why is the type of data so important? The type is what deခ肀nes what we can and can't do with the

data. For example, adding two numbers together or even two strings together make sense:

4 + 8
"Hello " + "World"

The ခ肀rst line will result in 12 while the second line will result in "Hello World" . However, it

doesn't make sense to divide one string by another or to make a number lowercase.

There's one ခ肀nal value worth considering: null . null should be thought of as no-value, which is

deခ肀nitely di肠ကerent than an empty string or 0

We'll revisit types in throughout the book. What's important for now is that you can tell a string
from a number from a boolean and that you understand that what you can do with one type of
data isn't necessarily valid for another type.

Dealing With Data - Variables

Much of the data that your program will make use of isn't going to be known ahead of time. Data
can come from many sources, such as user inputs or by reading it from ခ肀les stored on the

computer. In our user registration example, we know that we'll be dealing with an email and
password, but we don't know exactly what those values will be.

In a program we need a way to label our data, which is where variables come in. Variables, which
are very important, basically just hold data. Consider these two examples:

email = "leto@dune.gov"
password = "ghanima"

The above code introduces two variables: email and password . A variable and its value are

interchangeable. Just like we could add two strings together, so too can we add two variables
which hold strings:

joined = email + password

This introduces a 3rd variable named joined - which likely serves no purpose other than to show

that variables and their values are interchangeable. The value of joined is

leto@dune.govghanima

To understand the role that variables play, you need to remember that not all data is known
ahead of time. Rather than creating a variable named email with a speciခ肀c value, we'd be much

more likely to do:

email = get_the_value_entered_by_the_user

Exactly how get_the_value_entered_by_the_user works or what it does isn't important. What is

important is that the email's value isn't determined by us when we program, but rather

determined as the program is running.

In the next couple of sections, you'll see how important, yet simple, variables are. It's hard to grasp
them until we've introduced a few more concepts. What might be obvious already though is that
properly naming your variables is crucial to making your code readable. Although you don't know

the exact value held by email , if we printed it out, you probably wouldn't be surprised. However,

if we named our variable a or the or even string your guess about the contents would be as

good as mine.

Finally, in most languages, variable names are case-sensitive. Name , name and NAME are all

di肠ကerent variables. It's good practice to avoid relying on case to di肠ကerentiate variables. When code
contains both an address and an Address variable, it isn't obvious which should be used or how

they di肠ကer.
Determining A Course Of Action

In chapter 1 we learned that a program is read from top to bottom. The reality is more complex.

When we described our two examples, we saw how a program needs to execute di肠ကerent code
based on various conditions. This aspect of programming is known as control ☈☈ow, because it
controls which part of code will be executed.

The simplest control ☈☈ow is an if condition:

if password.length < 8
print "invalid password"

Building on top of this, we have an if/else condition:

if withdraw_amount > account_balance


print "Amount too large"
else
account_balance = account_balance ‐ withdraw_amount
print "Withdrawal request accepted"

Finally we have an if/else if/else :

if withdraw_amount < 0
print "Nice try, but you can't withdraw a negative amount"
else if withdraw_amount > account_balance
print "Amount too large"
else
account_balance = account_balance ‐ withdraw_amount
print "Withdrawal request accepted

You can have as many else if sections as you want, but only the ခ肀rst valid condition, going from

top to bottom, will be executed.


The other common type of control ☈☈ow are loops. These execute the same piece of code multiple
times. That might seem silly, and indeed, our ခ肀rst example is silly:

for i in [1..10]
print i

The above would print 12345678910 .

One thing that loops are very handy for is to iterate (or loop) over a collection of values. Earlier we
talked about three data types: string, numbers and booleans. We've always seen these as
individual values. However, it often makes sense to have a collection of values. In fact, the very

ခ肀rst example we saw, back in chapter 1, had a collection of playing cards:

deck = ["2 of Hearts", "3 of Hearts", "4 of Hearts", "5 of Hearts"]

The square brackets [] means collection. With the knowledge we've gained, we know that the

above is a collection of strings, represented by the deck variable. Collections and loops go hand-

in-hand:

for card in deck


if card is "Joker"
print "Please remove the jokers from the deck!"

Notice in the above that we introduce a variable named card as part of our loop. The word

variable was aptly chosen as the value of card varies with each iteration of our loop.

This example is similar to how we'd check for jokers in the real world. It's true that our eyes and
brain might be able to look at multiple cards at once, but it isn't a stretch to imagine scanning each
card one at a time, and taking a certain action if we spot a joker.

Finally, you'll often need conditions based on more than a single fact. For example, we might want
to display the above message if the card is "Joker" or the card is "Fool". This is am or condition and
will be true if one or the other part is true. The sister to an or condition is the and condition, which
will be true only when both parts are true. In some languages the words "or" and "and" are used,
but in most "or" is represented by || and "and" by && .

Control ☈☈ow can get more complicated, but it almost always comes down to taking an action
based on some condition, or looping over code. Often, these two concepts are combined, say by
looping over code until a certain condition is met. For now, it's suက䂠cient that you understand that
given a condition, it's possible to control what, if any, part of code is executed.

Performing Actions

We know how to manage data, and how to make decisions based on that data, now it's time to
take action. If you go back through the examples in this chapter, you'll notice that we've already
taken a number of actions. For example, we've printed messages to the user and subtracted one
amount from another. Let's break it down further.

Programming languages contain a number of operators. The most basic are + , ‐ , / and * . These

operators, amongst others, represent the simplest actions we can take: add, subtract, divide or
multiply two values. Another important operator is the assignment operator, which assigns a
value to a variable. We've seen this plenty of times already, it's the equal sign = . If we go back to

an earlier example, we'll ခ肀nd this speciခ肀c line:

account_balance = account_balance ‐ withdraw_amount

It's fair to say that this line involves two actions: subtract the two numbers, then assign the results
into the account_balance variable. You might be wondering how the order is determined. Just

like in mathematic operators, programming operators have an order of precedence and can be
controlled with parenthesis () . Thankfully, this order is pretty intuitive. The above is the same as

doing:

account_balance = (account_balance ‐ withdraw_amount)

We could do the following, but it wouldn't make much sense:


(account_balance = account_balance) ‐ withdraw_amount

This would assign the value of account_balance into account_balance (e肠ကectively a

meaningless operation) and subtract withdraw_amount but not store that result anywhere.

Some operators are frequently used with control ☈☈ow. We already saw how the greater than >

operator can be used to check if one value is greater than another. The other common
comparison operators are >= , < , <= and != , or greater than or equal, less than, less than or

equal and not equal. The last and probably most-used comparison operator is the equal operator,
or == . In most programming languages it's represented by a double-equal sign to distinguish it

from the assignment operator. The result of comparison operators is a boolean value: true or
false.

In a previous example we used is to check for equality. This was done because we hadn't

covered operators yet. In most languages, you'd write:

if card == "Joker"

The assignment = and equality == operators might seem similar, but they really have little

relation. The ခ肀rst makes the left-hand variable equal to the right hand value. The second results in
true of the two values are equal, or false otherwise.

Custom Actions: Functions

The last, and most advanced topic we'll cover in this chapter are functions. Much like a variable
can be thought of as giving a label to a value, a function gives a label to a group of lines of code.
Functions are powerful and important. They also serve a number of purposes. First, they help us
organize our code. Rather than having a long series of code, we can break it down into functions
with meaningful names. Secondly, they help us reuse code. You'll commonly have a task that you'll
want to execute over the course of your program.

In its simplest form, a function looks like:


function sayHello()
print "Hello"

Our new function, named sayHello can be executed by adding parenthesis to the name:

sayHello()

Functions can also be passed in variables. For a function these variables are called parameters :

function sayHello(name)
print "Hello " + name

Finally, functions can return a value:

function hasJoker(deck)
for card in deck
if card == "Joker"
return true
return false

The return keyword is powerful as it exits the function immediately. The value returned is no

di肠ကerent than any other value we've seen so far. It can be assigned to a variable, compared via an
operator as well as other things we haven't looked at.

Our hasJoker function can be used like so:

if hasJoker(deck) == true
print "Please remove the jokers from the deck!"

As a side note, conditions work by evaluating boolean values (true/false). There's no di肠ကerence

between true == true and just true . Similarly, there's no di肠ကerence between true == false
and just false . Therefore, the above, while more clear, can be rewritten :

if hasJoker(deck)
print "Please remove the jokers from the deck!"

In order to make hasJoker more reusable, we might change it like so:

function hasCard(deck, card)


for c in deck
if c == card
return true
return false

Which can be invoked like so:

exists = hasCard(deck, "2 of Hearts")

Notice that we had to change the name of card variable created in our for loop so that it wouldn't

be confused with the card parameter. Depending on the language that you were using, you'd

either get error or some weird behavior. Also, c isn't the best variable name, but given that it has

a very short existence, it's probably ok.

Like variable names, function names are also case-sensitive.

In This Chapter

This chapter introduced the concept of data types and variables, control ☈☈ow via if/else and

loops, as well as operators and functions. Everything was broken down into small chunks, making
it hard to see how they all ခ肀t together to form a program, but our last few examples, which were

more complex, started to give us some insight on how it all ခ肀ts together.

If it feels like a lot of things are still shrouded in mystery, it's because they are. How do the email
and password variables actually get populated with what the user entered in his or her browser,

and how do we get an account_balance based on the account_number on the card? These are

good questions with complicated answers. But understanding the topics we've covered so far is
the ခ肀rst step.
Da
Ar
Data Structures
Up until now, whenever we wanted to group values together, we've used the term collection. For

example, our deck variable held a collection of cards. However, to be accurate, our deck is actually

an array, which is just one of many collections. An alternative word for collection is data structure.

In this chapter we are going to look at a few data structures, including arrays, in order to properly
Q
understand them. There are countless data structures but it isn't important to know them all. What is
important is to understand the common ones, and to understand why so many exist. So far we've

only needed arrays, so it can be hard to imagine problems where arrays aren't ideal or even
su†‐cient.

Data structures are important as they provide the mechanism for deတတning what we can do with our

data. Other aspects, such as the type system (strings, numbers, booleans, ...), deal with what our

data is. Also, data structures can have certain performance characteristics, for example retrieving the Se
value of an array at a speciတတed index will always be the same no matter how small or large the index

is. Put simply though, data structures communicate a lot about the code. They deတတne a common

terminology so that when a programmer sees code using an array he or she can automatically infer

both how the data can be manipulated and how those manipulations will perform.
Ha

Arrays

We've already seen arrays enough to know quite a bit about them. Ultimately an array allows the
values within it to be accessed by an index. Given the following code, we'd expect the value sun to

be displayed:

In
landscape = ["hills", "clouds", "sun", "birds"]
alert(landscape[2])

In most languages, the တတrst element of an array starts at index 0 because the index represents the
o set from the start. We can also write a value at a speciတတc index:
landscape[3] = "seagulls"

Da
Ar

Another important characteristic of arrays is that the order of elements is preserved. In the following
example, where we start with a blank array and add two items, we know for sure that the 2nd item

will be cat :

pets = []
Q
pets.push("dog")
pets.push("cat")
alert(pet[1]) # will display cat

This might seem obvious, but we'll soon see data structures which don't make such guarantees. The

real power of array ordering is that you can control the order yourself. Initially the values in an array
are arranged based on how they were inserted. However, you can rearrange the order to suit your
Se
needs - say by sorting them from most awesome pet to least awesome pet (thus making cat the တတrst

item in the array!)

Sadly, there's some ambiguity over what an array actually is. In many languages, an array is တတxed-
sized. That is, we can only create an array by specifying a size (the number of elements to hold) and

cannot expand the array beyond this size. If we need more room, we must create a larger array and Ha

copy over the values ourself. This is the traditional and proper meaning of array. Arrays which don't
require that we specify an initial size and can grow as needed, are often called dynamic arrays. This is

one of the few cases where data structure terminology is ambiguous.

We won't worry about တတxed-sized arrays. In fact, for day-to-day programming, တတxed-sized arrays,
although often used, feel like a relic from the past. New languages tend to favor dynamic arrays (and

simply call them arrays.). Whatever type of array we are talking about, the important point is that
In
they are ordered and accessed by indexed.

Queues and Stacks

Queues and stacks aren't data structures that you'll use often, but we'll learn them to understand
how data structures di er from one and other, and why so many exist in the တတrst place.
Both are very well named, and to understand how they work, you must simply think of a real life
queue and stack. Imagine a line of people waiting at the checkout counter. The behavior of this line is

simple: you get into the queue, then move closer to the front and then get out of the queue. In Da
Ar

computer science terms, a queue is also known as a FIFO, or တတrst-in တတrst-out. That is, the တတrst person

to enter the queue will be the တတrst person to leave the queue.

A stack on the other had is like a stack of chips in a poker game. Chips get added and removed from

the top of the pile. A stack is known as a LIFO, or last-in တတrst out. Because the most recently added
Q
chips are the ones that get used up the soonest.

Knowing this, we can implement a queue with just two functions: enqueue and dequeue . Similarly, a

stack can be implemented with: push and pop . The names of the functions don't matter as much as

what they do, but these names are commonly used.

Both queues and stacks can be, and often are, built using arrays. For example, if we were to build a

queue using the arrays that your browser supports, we can use the push function to add, or queue,

values and the shift function to dequeue values: Se

queue = []
queue.push("Custom 1")
queue.push("Custom 2")
queue.push("Custom 3") Ha

queue.shift() #returns Customer 1


queue.shift() #returns Customer 2
queue.shift() #returns Customer 3

For stacks, we can use unshift to push values at the front and again use shift to pop values from

the front:
In

stack = []
stack.unshift("Chip 1")
stack.unshift("Chip 2")
stack.unshift("Chip 3")
stack.shift() #returns Chip 3
stack.shift() #returns Chip 2
stack.shift() #returns Chip 1

Da
Ar
At this point, it wouldn't be unreasonable for you to wonder whether stacks and queues really serve

a purpose. It just seems like we are limiting the functionality available to arrays! But we've only

looked at the simplest implementation. A queue for example can be enhanced to handle priorioty

(often called a priority queue). Items get enqueued normally but also include an additional piece of
information: their priority. Items are then dequeued တတrst based on priority, then in the order they

were enqueued. Another enhancement has to do with an empty queue or stack. Our above code Q

simply returns an undeတတned value if we shift when our collection is empty. Many implementations

can be made to wait (or block) until sometimes else adds items to the queue.

Queues and stacks serve speciတတc but not entirely uncommon goals. However, they aren't something

we need to master. We introduced them to show how data structures deတတne what we can do with
our data. It isn't just about being able to do more or less, but also about doing things di erently

(such as waiting until a value is present before we shift .)


Se

Sets

Arrays are great if you want to preserve the order of values, or if you want to randomly access values

by index. However, as we've already seen, to check if a value exists within the array, we have to loop
Ha
through it. This may be တတne for small arrays, but for large arrays with thousands of values and checks

happening hundreds of times per second, it's quite inneတတcient. The performance characteristic of

searching an array is described as linear because the time it takes to တတnd an item grows linearly with
the number of values in the array.

If rather than accessing a value by a numeric positional index, we want to access it by the value itself,

we can use a set. Since the way we access our data (or, the key) is the value itself, sets don't allow

duplicate values. These properties make sets ideal for a number of use cases: such as a shopping list. In

The reason we didn't use a set in the previous chapter is because browsers don't yet support them,

but newer versions will.

The way sets will probably end up looking is:

list = new Set()


list.set("milk")
list.set("eggs")
list.set("milk") #doesn't do anything Da
Ar
alert(list.exists("milk")) # will display true

In theory, we could use plain old arrays to create sets. In fact, in chapter 3 we could have modiတတed

the addItem function to make use of the itemExists and not allow duplicates to be added.

However there are certain performance characteristics that one expects from a set. Namely, the Q

speed of adding an item and checking for the existence of an item should not vary based on the size

of a set. This is a good example of how data structures not only deတတne the behavior of a collection,

but also their performance characteristics.

As a တတnal point, a properly implemented set should allow for set-based operation (in the

mathematical sense). For example, you should be able to create a union of two sets (to get all the

values contained in both), or an intersection (to get only the value which exist in both). That may

seem academic, but it's actually quite useful. Imagine having a set with the list of movies Jane has Se

seen and intesecting it with the set of movies Matt has seen. The result is a list of movies that both

have seen.

Sets are very powerful; but what you gain in terms of functionality and perfomance for some things,
you lose in terms of other. In comparison to arrays, you've lost ordering and the ability to hold
Ha
duplicate values.

Hashes

So far all the collections that we've looked at deal with a single value. Hashes on the other hand deal

with a key and a value. Hashes are also known as dictionaries and hash sets. Most of the time the

key is a string, while the value can be any other piece of data. As an example, if we wanted to track In

how many items to buy, we could use a hash:

list = {}
list["milk"] = 1
list["milk"] = list["milk"] + 1
alert(list["milk"]) # will display 2
Notice that we create a hash with braces {} . The value of a hash isn't limited to a simple string,

number or boolean. It can be something more complex, like an array, or another hash:
Da
Ar

list = {};
list['milk'] = {quantity: 1, section: "dairy"}
alert("You need to buy " + list["milk"]["quantity"] + " milk")

Above we see an inline method for creating a hash. Sets and hashes share a lot in common. We can Q

actually create a set using hashes. Our above set example could be rewritten like so:

list = {}
list["milk"] = true
list["eggs"] = true
list["milk"] = true
alert(list["milk"] == true) # will display true
Se

However, we don't have access to any set-based operations, like a union (which we might not need).

Hashes are powerful and are used often. They conviniently let you represent more complex data. For

example, we could represent a spreadsheet using an array of hashes:


Ha

rows = []
rows.push({type: "cat", name: "fluffy", age: 5})
rows.push({type: "dog", name: "hunter", age: 6})
rows.push({type: "fish", name: "jorge", age: 2})
alert(rows[1]["name"] + " is " + rows[1]["age"] + " years old"); # hunter is 6 years old

In
Like many things, the role played by hashes has changed over time. They were once used mostly to

quickly access data by key. While still used frequently for this purpose, we see hashes being used

more and more as simple containers of values, such as the animal data shown above. In a later

chapter, we'll learn about classes which are a more structured way to contain and represent such

data.
In This Chapter
Da
Ar
In this chapter we learned about arrays as well as hashes. These are two data structures that you'll

make heavy use of. We also saw queues, stacks and sets. While all three serve useful purposes, we
mostly explored them as a means to learn about di erent data structures. There are other classes of

data structures available, but they tend to be more complex, more specialized and thus less often

used.
Q

Se

Ha

In
In
More on Languages
M

Our goal thus far has been to learn about programming in general, regardless of the language and

its libraries. For this reason, we've looked at things that exist no matter what language you use.
How you de ne a variable, or the exact syntax of for loop is secondary to the concept of

variables and looping.

In this chapter we'll continue down this same path, but with a slightly broader perspective.

Speci cally, we want to familiarize ourselves with some of the other common things we are likely
St
to see in a program. Some of these are just shortcuts provided by the language, or di erent

approaches some languages take. Hopefully,to by learning these, you'll not only be in a better
position to write more complex programs, but also be better able to understand other people's
code.

Incrementing and Decrementing


St

We've already seen a number of examples where we increment and decrement a value by some

number:

i = i + 1
Lo
# or
account_balance = account_balance ‐ withdrawal_amount

Incrementing and decrementing values is such a common thing, that most languages provide
alternative syntax: In

i += 1
# or
account_balance ‐= withdrawal_amount

The two versions are identical, the second one is simply less verbose by making use of the += and
‐= operators. Not only is incrementing so common that we have this special syntax, but

incrementing and decrementing by 1 is itself so common that many languages give us special
syntax for that speci c purpose: In
M

i++

i‐‐

This is known as post-incrementing and post-decrementing. An alternative is to pre-increment or


pre-decerement. he di erence between them is all about the operator's precedence with respect St

to other operators. Consider:

i = 5
total = i++
//vs
i = 5
total = ++i St

In both cases i will be equal to 6. However, in the rst case, i is assigned to total and then

incremented. Thus, total is 5. In the second case, i is incremented and then assigned to total .

Thus, total is 6. Lo

Strings With Values

You'll often want to display a message which includes variable values. There are three common

ways to do this, but not all languages provide all three mechanisms. In

The simplest to understand, and the one we've used so far, is to join the pieces together with the

+ operator:

name = prompt("What is your name?")


alert("Hello " + name)
This works well for simple a message, but it can get quite messy for something even slightly
complicated.
In
M
Another common approach is to have some type of string formatting function. Every language

seems to have its own version, but it normally ends up looking something like:

name = prompt("What is your name?")


formatted = format("Hello %s", name)
alert(formatted)

# or, a more terse version: St

name = prompt("What is your name?")


alert(format("Hello %s", name))

Again, this varies a lot from one language to another, but in the above %s is a string place holder,

as opposed to a %d digit placeholder. Writing such a format function in most languages wouldn't

be too di cult (assuming one didn't already exist).


St

The last approach that you'll often see is the ability to put variables directly in your string, by

wrapping it in a special sequence of characters:

name = prompt("What is your name?")


Lo
alert("Hello #{name}")

The exact syntax will vary from language to language, and many languages don't even support this
approach.

In

Strings and Escape Sequences

Sometimes you'll want to include a special character within a string. The most common example is
a double quote. However, a computer can't make sense of the following since it means something

special within the language itself (the start or end of a string). It might be obvious to you and me
where the following string meant to end, but a computer can't tell:
message = "And he said "to get to the other side""

In
M
To avoid this ambiguity, languages tend to have an escape character, and that tends to be the

backslash \ :

message = "And he said \"to get to the other side\""

When you want to print an actual backslash, you simply escape it:

St

message = "I'm printing a backslash like so \\"

Finally, if you want to output a tab or new line, you can use the special \t or \n sequence. \n is a

line feed. To get a new line to display properly on some operating systems, you'll have to print out
a carriage return \r followed by a line feed: \r\n .

St

Loops

for loops aren't the only type of looping mechanism available in most languages. Two other

common ones are the while and do/while loop. In general, a for loop can be thought of as
Lo
iterating through a collection of values. A while and do/while loop iterate so long as a condition

is true. They are both similar in that, the for loop's condition is implied to be: is there another

value?. For example, we could iterate through a collection of values using a while loop like so:

i = 0
In
while i < deck.length
if decks[i] == 'Joker'
# .. do something
i += 1

With both a while and for loop it is possible for no iterations to take place if the condition is
initially false or the collection is empty. A do/while places the condition at the end, and thus will

execute at least once:


In
M

do
name = prompt("What is your name?")
alert("Hello " + name)
while name != "Joker"

Generally speaking you'll see for the most often, then while and nally do/while .

St

In This Chapter

This chapter introduced new keywords and operations which many languages make available.
Some of these may seem minor, that's because some are. Understanding the concepts behind

variables and conditions to control execution is a lot more important than knowing that i++ is a

quick way to do i = i + 1 . However, as soon as you start exploring other guides and sample
St
programs, these are things that you'll imediately run into.

For the time being, you might be uncertain about what's the best approach to use for a given

piece of code. What loop should you use, or how should you mix strings and values? At rst, worry
about making your code do what you want it to do. With experience, both from reading other
Lo
people's code, and expanding your own, you'll gain a feel for what improves and what distracts

from your codes readability.

In
More On Types
In chapter 2 we talked about types, focusing on three main types: strings , numbers and
booleans . In following chapters we used arrays and talked about other data structures. However,
throughout our coding, types haven't played big role. Besides knowing that a value was a string or
a number, and knowing that some operations only work on some types (like conditions are
expressed as booleans), it has all seemed rather academic.

Dynamic vs Static Typing

Types truly are important as they deᴀ밄ne what we can and can't do with our data. How much in-
your-face this fact is largely depends on the language. With respect to types, languages fall into
one of two categories: types are either explicitly stated or they are implied. The proper terms are:

static typed languages and dynamic typed languages.

So far we've only seen dynamic typing. In a static typed language, you'll see code peppered with

type information. If we were to rewrite our itemExists function in such a language, it would look

something like:

bool function itemExists(string itemToFind)


string[] items = getItems()
for item in items
if item == itemToFind
return true
return false

Notice that our variables are now declared with explicit type information - such as string[] ).

Furthermore, we've had to state the type of parameter our function expects as well as the type it

returns.

In a static language, once a variable is declared to be a certain type, the values assigned to it can

only be of that type. This isn't true of a dynamic language. Below we have code written in a
dynamic language, followed by code written in a static language. The static language version will
not compile - you'll get an error because name is deᴀ밄ned as a string and cannot hold a number:

name = "Goku"
name = 9001

# vs
string name = "Goku"
name = 9001 # error!

Many programmers passionately prefer one type system versus the other. Proponents of dynamic

languages say they are more productive. Developers who prefer static languages think their code

is less likely to contain errors and run faster.

This is a good time to point out that the type system isn't just about having to enter fewer
characters. Languages that are dynamic tend to have other common properties; and static

languages share many similarties with each other. As a simple example, arrays in dynamic

languages tend to be dynamic, while arrays in static languages tend to be ᴀ밄xed.

Professional programmers should strive to master at least one of each. As someone learning to

program, I don't think it matters woo much which one you pick. Dynamic languages are probably
easier to learn. The choice may very well be forced upon you based on what you want to program

.For example, if you want to write applications for Android mobile devices you only have one
language choice, Java, which is statically typed.

Numbers

So far we've treated all numbers the same. However, numbers actually come in a variety of shapes

and sizes. At the very least, most languages support two types of numbers: integer and ᴀ밄oats.

Integers don't support decimals and typically support a range of -4 billion to +4 billion (plus or
minus a couple hundred million). 0, 5, -1495 and 9001 are all examples of integers. Floats on the

other hand support a much wider range and support fractions. 0.1, -29394.49 and 2003.9 are all
examples of ᴀ밄oats.

Static languages tend to take this even further by introducing diᴀ洅erent types of integers and
ᴀ밄oats. The diᴀ洅erent integers represent diᴀ洅erent minimum and maximum ranges. A byte can go

from 0 to 255 while a long can go into the quintillions. Integers can also be made to disallow

negative values (and thus increasing the maximum positive value). Finally, ᴀ밄oats can also be
decimals . The diᴀ洅erence between a ᴀ밄oat and a decimal has to do with accuracy. When you

manipulate ᴀ밄oats (such as multiplying or dividing them) you can lose precision (think of it as

rounding errors) which is bad if you are dealing with things like money. Decimals don't suᴀ洅er from

this problem. The downside is that they don't perform as well

For now, you just need to know that numbers are categorized as integers and ᴀ밄oats. The main

diᴀ洅erence being that ᴀ밄oats support fractions.

Type Conversion

Whatever type system you are dealing with, you'll often want to convert data from one type to
another. Even in a dynamically typed language, a value still has a type. For example, the value

returned by the prompt function is always a string. If the user enters 5 when prompted, what do

you think the value of sum will be?:

sum = 4
sum += prompt("Enter price")

This depends on the language you are using. Some will generate an error. Others will convert the
sum to a string and append it to the 4 already stored in it - resulting in "45". To get the desired

answer of 9 we need to convert the value to an integer. Diᴀ洅erent languages have diᴀ洅erent
functions for doing this. In your browser the functions parseInt and parseFloat convert a value

to an integer or ᴀ밄oat:

sum = 4
sum += parseInt(prompt("Enter price"))

What happens if the value we are trying to convert isn't a valid integer? Again, this depends on the
language. Many will generate an error. Some may return special values that indicate that the
conversion failed.

Similarly, values can be converted to a string. This is often done via a method called toString .

Again, it's worth pointing out that not all languages behave the same. For example, your browser

will gladly execute the following:

power = 9001
alert("It's over " + power)

Whereas another language, even a dynamic language, might insist that power be explicatly

converted to a string.

In addition to conversions, static languages allow some types to be coerced into other types. For
example, we said that a byte can hold a value from 0 to 255 while a long has a much larger

range. Despite this diᴀ洅erence, there is some overlap. In some cases, a long could be a valid byte .

We can only turn a long into a byte by explicitly telling the compiler yes, we really mean to do

this. This coercion is done by casting:

long large = 200


byte small = (byte)large

Finally, you might be surprised by the result you get when dividing integers. In some languages,

dividing the integer 1 by the integer 3 will give you an expected ᴀ밄oat 0.333333. In static languages,
however, operations involving two integers will result in an integer, as will operations involving
two decimals result in a decimal. Therefore, 1 / 3 will result in 0. This is true for many dynamic

languages as well. To get the 0.3333, one or both values must be a ᴀ밄oat: 1 / 3.0 .

Getting The Type

It's always possible to get a value's type. This is often achieved via the typeof , or similarly named,

operator. The following code will display string.


alert(typeof "i love unicorns")

This is handy in cases where we don't know what type of data we are dealing with. Futhermore, in
many other languages, types themselves are complex objects supporting many advanced
functions. This isn't something you are likely to need as you get started. But it should give you

some idea of just how big a role types play - in both dynamic and static languages.

In This Chapter

This chapter expanded our initial concept of types into a much more comprehensive version. The
most important thing to know is that static typed languages exist and are very popular. If you are

looking at code and you see the words string and int (to name a few), you are looking at a

static typed language.

We also broke down numbers into two main groups. It's normally obvious if you want an integer

or a ᴀ밄oat. The breakdown from that point on isn't as important. The only exception is if you are
dealing with money, in which case you'll want to make sure you are using a type that won't lose
precision.
Next Steps
The world of programming is vast, but you've taken the †⁐rst step. There are a number of

advanced, yet fundamental, topics still worth exploring. There's an even greater number of higher-
level concepts and tools that might interest you. Even though you could continue to learn about

programming in general, a more speci†⁐c route would yield more tangible bene†⁐ts.

In this chapter we'll look at where you can go from here. Generally speaking, where you go is

de†⁐ned by what you want to do. Do you want to build mobile applications or websites? Do you
need to deal with data and report or maybe weave some spreadsheet magic? Each of these †⁐elds

tend to have their own languages. But learning a new language isn't the challenge. What's truly
di††cult about learning a new †⁐eld of programming are the libraries and constraints speci†⁐c to
that †⁐eld or technology. The way that you display an input †⁐eld on a website is di†⁐erent than how

you do it on an iPhone. Similarly, the challenges of dealing with di†⁐erent browsers and slow
internet speeds are di†⁐erent than those of dealing with limited battery life and a touch-based
interface.

A Tip On Learning

We all learn di†⁐erently. Some like to read, some like videos, others have to get their hands dirty.

There's one strategy that I've used which I'd like to share with you: learn by helping. Whenever I'm
learning something new, I join the forums and hang around in the groups and try to answer
whatever questions I can. At †⁐rst, I can't answer anything. But I read the questions people have,
spend a bit of time trying to †⁐gure it out, and read the replies they get. Eventually, someone asks a

question that I know the answer to. That †⁐rst "thanks" reply is quite satisfying; as is the pace at
which you †⁐nd yourself able to answer additional questions.

Maybe this trick won't work for you, but I suggest you try it. Many communities have their own
forums and groups where anybody can ask questions and anybody can answer. Alternatively, you
can try a more generic help site like StackOver††ow. You can follow only those topics which interest
you, ask questions when you need help, and answer questions when you can.
Also, practice! Programming is about experience and practicing is the key. Don't worry about
making mistakes, as it's one of the best ways to learn.

Finally, most of the day-to-day programming that goes on isn't a hard science. Despite what you
might read, there isn't necessarily one best way to solve a problem. There certainly isn't one best
tool, or one best language. Keep this in mind when getting advice.

Websites

Of all the technologies that may interest you, programming websites is likely the most daunting

for two important reasons. First of all, there's so much choice in technologies and tools, that it's
simply overwhelming. Which do you pick and where do you start? Secondly, in order to create a

meaningful website, you need to know 5 di†⁐erent technologies. HTML, CSS and JavaScript can be
thought of controlling everything the user sees and interacts with. You then need a language that

does all the behind the scenes work - like saving users. Finally, most websites rely on some type of

database to store data. Individually, these aren't hard to learn (you can put together a simpe
HTML page in a few minutes). But combined, it's a bit crazy.

However, of all the technologies, you won't †⁐nd better resources than those available to web
programmers. Using Google you can †⁐nd endless guides, tutorials, videos and blog posts that

cover each of these technologies - both separately as well as how they come together. It's a
passionate and mature community. Furthermore, the web is the most accessible platform

available. Build something for the web and anyone can use it.

While there truly is too much choice, I feel comfortable in recommending two speci†⁐c

technologies: PHP and Python.

PHP is the most established and most popular language for the web. It will be the simplest thing

to learn, and also one of the best documented. The downside of PHP is that it isn't particularly

elegant and many of the concepts are dated. Also, PHP is almost exclusively used for the web.
While much of the core experience you gain using it is transferable, the language and libraries

itself aren't. The o††cial PHP website, while intimidating at †⁐rst, is a good place to start.

Unlike PHP, which is both a language and a framework, Python is just the language. For web-based

applications, you'll want to pair it with a appropriate framework. Django is a popular choice with
excellent documentation. Python is modern and popular for tasks other than websites, making it a
more useful language than PHP. Python web frameworks, like Django, are more elegant and

promote good approaches to programming. Furthermore, the Python community as a whole tend
to write excellent documentation and guides.

Learn Python The Hard Way is a great ebook you can use to master Python. You can read the book
online for free, or pay for a pdf or epub.

Mobile Applications

If you are interested in writing mobile applications, the choice is much simpler. If you want to

target Apple-based devices (iPhones and iPads), you'll want to learn the Objective-C language and
the Cocoa framework. Apple's developer center is the right place to start. To write iOS applications

you'll need an Apple computer as well as XCode, which you can download for free from the app

store.

For Android-based devices, you can head over to Google's Android developer zone. Android

applications are built using Java (which has no relationship to JavaScript). The tools are free and
can be run on all popular operating systems.

Windows

For anything relating to Windows, you'll likely want to learn C# and check out MSDN. Of all the
technologies listed here, Microsoft's documentation is the worst - likely because its such a large
ecosystem. Microsoft has a number of free tools under its Express brand which are a great way to
get started.

Database

There are a number of databases available, but thankfully they all use a standard language known
as SQL (Structured Query Language). Di†⁐erent databases do extend SQL with their own

extensions, but once you know the fundamentals, everything else easily falls into place. A big part
of learning adatabase isn't the language, but rather how to model your data and how to e†⁐ectively
query it.

It doesn't matter which database you pick, but if you don't have any existing preferences, I'd

suggest you look at PostgreSQL. It's free, runs on most operating systems, has good
documentation and a strong community.

Conclusion

A challenge of learning and teaching programming is how long it takes before something tangible

can be created. In this respect, this book has failed you. You didn't create anything meaningful and
there's still much to learn before you can do so.

Despite this, I'm hopeful that you don't feel like your time has been wasted; nor that you are
discouraged. Even if you've spent all this time and many things remain unclear, don't be
dissapointed. As you start to turn this theory into practical solutions, much will become clear. In
some ways, we've barely taken a step forward. But we have oriented ourselves, ensured that we

have the basic provisions, and properly readied ourselves for our journey.

Thank you.

You might also like