LuxSci

Introduction to Internet Programming with Perl and HTML: Part 2 – Introduction to Programming Concepts

Published: January 7th, 2010

[RAW]

This article is Part 2 of our series on Introduction to Internet Programming series. See the Introduction and Part 1, Introduction to HTML. The Introduction to Programming covers basic programming concepts and teaches the reader to develop “pseudo-code” for various tasks.
[/RAW]

[RAW]

2.1 What is a Program?
2.2 Basic Programming Concepts
2.3 Looping and Functions
2.4 Your Homework

2.1 What is a Program?

So, you have never written a program, don’t know what a programming
language is, and have not a clue where to start? Great — this lesson
is just for you!

A program is a sequence of commands that a computer executes
in order to perform some actions, be it the calculation of the number of
calories in your lunch or the trajectory the space shuttle will follow
on its re-entry to Earth from space. The sequence of commands can
be as short as just 1 command or as complex as you can imagine (millions
of commands, or more). It is the job of the programmer to create and
test the commands that will perform some predefined task.
We shall teach you to be a programmer!

A programming language is a language in which you can
specify the commands in a program. Just like there are innumerable
ways to say “Hello” in the spoken languages of the world, there are innumerable
ways to make a computer say “Hello”, depending on what programming language
you use. Different computer programming languages have different
pros and cons to their use. Some are only available on certain
operating systems (i.e. Visual Basic only works on Microsoft
Windows), some are very complex (like C++ or Java),
some are simple (Basic), and some are designed
for specific tasks like mathematics (Fortran).
It is partially up to the programmer
to choose the appropriate language for his or her program. In this
class we will be teaching your Perl. We will discuss Perl
and its particular pros and cons in the next lesson.

So where do you begin? You can prepare for writing computer programs
before you even learn your first programming language! You do this
by specifying how you would go about writing a program to accomplish
some specific task using pseudo-code, plain English statements
describing what to do. In this lesson, we will teach you how to
write pseudo-code along with many of the basic concepts behind
computer programming languages.

2.2 Basic Programming Concepts

Statements: A statement is the simplest concept in
a programming language. A statement is merely a single command
to perform a single well-defined task. For example,
“Stop the car”, and “leave the house” are single statements describing
single well-defined tasks. Note that even seemingly simple statements
can often be broken down into many simpler statements. “Stop the car”
could be broken down in to steps such as “Apply the brakes”, “Downshift”,
“pull over to the curb”, and “Apply the parking brake”.

The number of steps you should supply and the level of detail
you should use for describing their performance
will be determined in part by the programming language you use
— in some languages “Stop the car” may be a single statement,
on others, hundreds or thousands of statements! It will also
be determined by how specific you wish to be in describing
how to perform the action
versus how much you want to leave up to the people who take your
pseudo-code and write a program based upon it.

Variables: Statements only get you so far without additional
concepts. Variables are perhaps the most ubiquitous entity in any
programming language. You can think of a variable as a box in which
you can store something — a number, a date, someone’s name, the
price of a sweater, the number of people in your immediate family,
the current speed at which your car is traveling, etc. The beauty
of a variable is that you can store information
in it and retrieve information from it any time you want!

Each variable “box” has a name. You refer to the different variables
that you are using by their names. You can choose pretty much any name
you wish, but it is advised to choose names that reflect their
purpose or what is stored within them.

With variables, you can start having more interesting statements and
start having the computer perform mathematics. The following is
example pseudo-code for calculating the length of the hypotenuse of a
right triangle.

Example 2.2.1: Pseudo Code For Length of the Hypotenuse


1. Ask the user for the length of leg 1 of the triangle
2. Store his answer in variable named "leg1"
3. Ask the user for the length of leg 2 of the triangle
4. Store his answer in variable named "leg2"
5. Calculate the sum of the value in "leg1" squared plus
   the value in "leg2" squared (leg1 ** 2 + leg2 ** 2)
6. Take the square root of the result
7. Store the result in variable named "hypotenuse"
8. Tell the user that "The hypotenuse has the length of"
9. Tell the user the value stored in the variable
   "hypotenuse".

You see with this first example of pseudo-code how you can specify
the actions required to perform a task in plain English without
regard to any specific programming language. The assumption made in
our example is that actions like “Ask the user for something” and
“Calculate something” are simple enough that they require no further
details. In truth, it will be your knowledge of the programming languages
that the program may be written in, and the people who will be
writing the code, that determine the level of detail that you need.
For now, just follow your intuition.

Logic: One thing that computers do REALLY well is obey
the rules of logic. In particular, they are really good at doing
calculations and comparisons. For example “5 is less than 3” is
a false statement, “A Ford Escort is a VW Jetta” is a false statement,
and “2 + 2 = 4” is a true statement, are all straight-forward logical
conclusions. “Yellow is a nice happy color” is not something that
can be determined logically unless you have already specified what
makes a color “nice and happy”.

Performing logical operations, especially when a variable is
involved, allows you to determine the truth or falsity of all kinds
of things. This is known as “Boolean logic” as the result is
the 2-valued truth or falsity of the statement.

Conditionals: Well, since we can determine if
comparison is true or false, it would be nice if we could
act on this information. This is where a conditional comes in.
Consider the example of driving “If the stoplight is red then
stop the car”. This uses a little logic (is the stoplight red
or not?) or determine whether or not we should stop the car.
As you can imagine, we use these types of rules all the time
in everyday life without ever realizing it! They are used
all the time in computer programs too. Lets consider another
mathematical example, computing the result of dividing one number
into another…

Example 2.2.2: Pseudo Code For Dividing 2 Numbers


1. Ask the user for the first number
2. Store his answer in variable named "X"
3. Ask the user for the second number
4. Store his answer in variable named "Y"
5. If the contents of "Y" are zero then
   5.1 Tell the user that he can't divide by zero
   5.2 Exit the program

6. Calculate the X divided by Y.
7. Store the result in a variable named "Z"
8. Tell the user the value stored in the variable "Z".

The trick here is that we use a conditional to
check to be sure that the user provided us with valid number.
Since you cannot divide by zero, we have to be sure that we
don’t try and that well inform the user of the error.

Conditionals can contain more complicated logical statements
and can be chained, for example, if you are driving your car…

Example 2.2.2: Driving


1. If the car is moving and the road turns to the left, then
   1.1 Steer to the left until the road is straight again

2. Otherwise, if the car is moving and the road turns
   to the right, then
   2.1 Steer to the right until the road is straight again

3. Otherwise, keep going straight

Obviously, you could make these instructions arbitrarily complicated,
but even this much shows us how you can chain “ifs” together
so that if the first rule doesn’t happen, then you can consider
the second, and so on, until all the rules fail when you can
perform some default action (“keep going straight”). It also shows
you how you can have compound logical statements “the car is moving
AND the road turns right”. These are two separate statements that
must both be true in order for the rule to take effect. You will
often see multiple logical statements joined together with
words like “and” and “or”.

2.3 Looping and Functions

Looping: Many times in your daily life, you repeatedly
do the same action. For example, when washing dishes by hand,
you “grab a dirty dish, wash it, put it in the drying rack, and
repeat until there are no more dirty dishes to wash.” This is a
kind of “loop”.

Loops are essential in many programs, too.
There are two general types of loops — those where the condition
is tested first, and those where the condition is tested last.
In our dishes example above, the condition is tested last
“repeat until there are no more dirty dishes” — in other words,
it assumes that there is at least 1 dirty dish since the first thing
we do is grab one! This loop could be
re-phrased with the condition first: “while there are dirty dishes,
grab a dirty dish, wash it, put it in the drying rack, and repeat”.
This accomplishes the same task, but it also works if there are NO
dirty dishes. For us humans, it wouldn’t matter — if there are
no dirty dishes, we are not going to try to grab one (note the if statement
there — we do that unconsciously all the time). For a computer, if you
tell it to, it WILL try to grab that dirty dish, even if there are none
left! This could cause all sorts of problems — so you have to be careful
to be logical and take into account all the situations that could occur.

Another thing you should be careful of with loops is to make sure that
they always end! If a loop never ends, it is called an “infinite loop”
and almost always is not what you intended! If you run a program and it
never stops, chances are good that you have an infinite loop somewhere.

In the following example, we are going to the grocery store
with a list of items. We need to describe a method for shopping.
A list is a kind of variable that is like a box with many numbered
compartments — each compartment behaves like a normal variable.
You can refer to the contents of the compartments in your list
(aka the list elements or items) by their “compartment number”, i.e.
item 1 of “shopping list”, item 2 of “shopping list”, etc.

Example 2.3.1: Grocery Shopping


1. Drive to the grocery store
2. Exit the car

3. Go up to the grocery store
4. If the store is open then
   4.1 Enter the store
5. Otherwise,
   5.1 Go home
   5.2 Stop the program

6. Enter the grocery store and go to the area where
   carts are stored

7. If there is a free cart, get it
8. Otherwise,
   8.1 wait until someone returns one
   8.2 get the newly free cart

9. Let variable "n" be the number of the item in our
   shopping list that we are currently looking for
10. Set "n" equal to 1

11. while "n" refers to one of the items in our list, do
    11.1 Look at every item in the store until we find
         a match for grocery list item "n".
    11.2 If we find the item, add it to our cart
    11.3 Otherwise, mark our list that it was not found.
    11.4 Change "n" to "n+1". (i.e. lets look for the next
         item in the list)

12. Proceed to the checkout counters
13. Let "counter" store the number of the checkout counter
    we will proceed to.
14. Let "people" be the number of people currently in line
    at that counter. Set this to "99999999"
15. Let "items" be the number items in our cart.
16. Count the number of items in the cart and save it in
    "items".

17. For each checkout counter
    17.1 Find out the maximum number of items that you can
         checkout with at that counter, store in "max".
    17.2 If "max "is less than "items", go to the next counter
    17.3 Find out how many people are currently in line,
         store in "p".
    17.4 If "p" is less than "people" then
         17.4.1 Set "counter" equal to the current counter
                number
         17.4.2 Set "people" equal to "p"

18. Go to counter number "counter"
19. Check out
20. Take groceries to the car
21. Drive home
22. Stop program

This example is a good demonstration of the use of all
the pseudo-code features we have so far mentioned. As you can
see, many of the parts of this example could be extended
with more detail, or simplified by suppressing detail. I.e.
what do you do if you couldn’t find ANY items on your list at
the store?

Functions: There are often computations or operations
that need to be performed at multiple places in your program.
Instead of repeating the statements over and over,
it is usually better to extract these statements and place them
into a “function” or “subroutine”. These are named sets of statements
that perform a specific action, like “calculate the average
of a list of numbers” or “drive home”. Then, in your program,
you can just refer to the function wherever you need to perform
its action, simplifying your work.

Example 2.3.2: Finding the Average Height


1. Make a list called "height" with enough items for
   every person in your class.
2. For each person in your class
   2.1 Calculate Person's Height [A Function]
   2.2 Store the height in the "height" list
       in an item labeled by that person's name.

3. Make a variable "height_total" and initialize
   it to zero.
4. For each item in the "height" list
   4.1 Add the height to variable "total_height"
5. Make a variable "height_average"
6. Set "height_average" equal to "height_total" divided
   by the number of people in the class
7. Display the contents of "height_average"

Function "Calculate Person's Height"
  1. Stand the person up straight
  2. If the person's shoes are on, then
     2.1 have them take his/her shoes off
  3. Use a yard stick to measure the height in inches
  4. Record the height and return it

This example shows a function that performs some
set of actions and returns a result. That means that
back in the main program, after you executed the function,
you get back anything that it “returns”, in this case, you
will know the person’s height.

Breaking up your programs into functions that perform
repeated tasks is a very good thing as it makes your
programs smaller, reduces the number of errors you might
make, and makes it easy to update and change your program
later. Use functions.

You will also notice one new concept that we introduced above.
We stored the students’ heights in an array where the items
were labeled by the students’ names and not some number.
You can do this in many programming languages (especially Perl).
It is technically called a “hash”, but you can just think of it
as labeling a list by a name vs a number; depending on the situation
one way may be simpler or more appropriate than the other.

2.4 Your Homework

You are a “pollster”. You have a list of questions each with a
list of acceptable answers. You need to write pseudo-code for the following
process: Calling a “poll taker”. Asking all of the questions in your poll.
Getting all the responses. Making sure that the responses are acceptable.
Recording all the responses. Of course, you need to figure out and describe
in detail a good method for doing this in your pseudo-code!
(I.e. this could be used to train a
new pollster how to give a poll to someone over the phone).

Your pseudo
code should convert your common-sense idea of of how to give a poll into
instructions. Try to be clear, concise, and logical.

You would be graded on how well you implement your ideas in pseudo
code and how clear and logical they are. Your should absolutely
avoid writing a narrative description of the poll giving process!

The idea behind pseudo code is that you should be able to hand it to
anyone and they should be able to write a computer program based on
your code that implements your ideas. Hence, you should limit
ambiguity where possible and consider all “corner” and “unlikely”
situations that may occur.
[/RAW]

Leave a Comment


You must be connected or logged in to post a comment. This is to reduce spam comments.

If you have not previously commented, you can connect using existing social media account, or register with a new username and password.