Wiki : learning:programming
 

Basic Programming Concepts

Introduction

This text have the intention to introduce the basic concepts of programming. The pre-requisites are interest and having a computer. This is not focused on any particular language but we'll use Perl because of two things: availability and easy of use.

First, Perl is a very simple programming language and most of the time uses natural language to express commands so it's the best language to learn first. Second, perl is available for all platforms (Windows, Unix, Mac, etc) and is extremely simple to install (unix and Mac already comes with it built in) and is completelly free of charge.

Preparation

If you use Unix or Mac, it's all set. If you use Windows, you can download ActivePerl. While instaling, remember to choose the “put the Perl binaries on path” so you can call it directly from the command line. If you prefer, you can also associate it with .pl extension (also available as an option on installation) so you can double-click it on your explorer and run it.

All examples assumes you have a unix / mac console. The Windows console s not so different and you'll have no problems as well.

Concepts

In a nuthsell, a program is a set of instructions that receives some input, deal with them and show you the output. Every program does that, in way or another. It does not matter if your program receives text from a file, typed form the keyboard, clicked with the mouse or even browse the internet, it have to receive data to function. It's the same with the output, whether it goes to a file, to the console, to another program or even to the screen in the format of colored pixels as in games, all of that is output.

Some programs seems not require input. Probably because all required information is already present inside the code or because it generates it's own data using random numbers generators and some pre-defined rules, but again, this is input, and we call it hard-coded input.

A program without any kind of output is useless. You can store information for a while but if, at the end of the execution you have zero output you just spent computational power for nohing. In some very specific cases we do want programs without output, and that's the case of the /dev/null device on unix systems but its left as an exercise to the reader define in which cases it's of great use.

So, the big deal of a program is to create a function that receives a set of arguments (the input), process them and spit out some results (the output). It is as simple as it seems, no hidden treasures here, it's just that.

The whole point behind software engineering is not how to make a program, but how to best make a program.

Below, an example of calling a program from the command line using “input” as input and receiving the “output” from the program. The second dollar sign is the shell again meaning your program has ended.

$ program "input"
output
$

Storage

While performing all calculations your data needs to be stored somewhere. It's like a paper where you do a math calculus, you draw the numbers so you don't have to remember them all the time.

The place where all your data is stored s called variable. Funny but also the constant data is stored on a constant variable. Well, names… don't worry too much. You can store anything you like on variables, numbers, text, lists and complex data structures. Basically all programming languages allows you to store any kind of data, you just have to know how to do it.

In Perl (and most scripting languages) a variable is denoted by the dollar sign ($) before the name, so you can easily spot them on your code:

$number = 42; # a number variable
$text = "Dave, what are you doing?"; # a simple text
$fruit = new Orange(); # a complex structure

On the example above we have defined a variable to store a number, a text and a complex structure, called objects that you can define your self, as you'll see in further texts.

Let's make a program to gather information and show them formatted to the user! Note that everything after the # symbol is not part of the program and will not execute. We call it a comment and helps us to explain what's going on.

# example1.pl - gets user's name and age and display formatted on screen
 
# Get data
print "Please type you name: ";
$name = <>; # this 'command' reads from the keyboard and store on $name
chomp($name); # now it removes the ENTER you typed
print "Now, please type yor age: ";
$age = <>;
chomp($age);
 
# Display data
print "Your name is $name and you are $age years old.\n";
# '\n' is the NewLine character and perform an ENTER on the text

If you put this code into a file example1.pl and call Perl to execute it you'll see:

$ perl eample1.pl
Please type you name: renato
Now, please type yor age: -15
Your name is renato and you are -15 years old.

See, easy as pie! So, you already have your data in a safe place, what to do with them ? A very simple thing is to perform mathematical functions. So, for instance, let's show the user where would he be given a constant speed and the amount of time at that speed by aplying the Newton's equation S = S0 + V.t:

# example2.pl - newton's equation
 
# Get input
print "What's your speed (in m/s)? ";
$speed = <>;
chomp($speed);
print "How long are you running (in seconds)? ";
$time = <>;
chomp($time);
 
# Perform calculation and show output
$distance = 0 + $speed * $time;
print "You are $distance meters far from the beginning!\n";

And now, let's execute our little example:

$ perl example2.pl
What's your speed (in m/s)? 5
How long are you running (in seconds)? 10
You are 50 meters far from the beginning!

See, that we no longer show static results, but we're changing the input to present a completely new output, we're performing calculations and doing something useful to the user. That's the first important outcome of learning how to code: perform dificult and/or repetitive tasks automatically.

Conditionals

Now, what if the user want to choose which operation it wants ? You could write two pograms and ask him to use each one he wanted at a given time but, that's not the point of programming, you should make things simple and not more complicated. That's where the conditional statements are useful. The if and the else gains life when you need to choose between A and B.

# example3.pl - newton's equations using conditionals
 
# Choose which variable to get
print "Which equation? distance or speed ? ";
$type = <>;
chomp($type);
 
if ($type eq "distance") {
  # Get input
  print "What's your speed (in m/s)? ";
  $speed = <>;
  chomp($speed);
  print "How long are you running (in seconds)? ";
  $time = <>;
  chomp($time);
 
  # Perform calculation and show output
  $distance = 0 + $speed * $time;
  print "You are $distance meters far from the beginning!\n";
 
} elsif ($type eq "speed") {
 
  # Get input
  print "What's your distance (in meters)? ";
  $distance = <>;
  chomp($distance);
  print "How long are you running (in seconds)? ";
  $time = <>;
  chomp($time);
 
  # Perform calculation and show output
  $speed = $distance / $time;
  print "You are at $speed meters per second!\n";
 
} else {
  print "What?\n";
}

Wow, now we ave a big program! It lets you choose which type of calculation you want and we also learned a different concept, the elsif. On most programming languages it's just an else followed by an if but it makes no difference what's it called, the important is how it works.

The if will evaluate the expression inside the parentesis [[[) and, if the return value is true, it executes the code inside the brackts {}. If it's false the execution goes to the next stop, in our case, the elsif, which works exatly the same as the if and will only execute if the expression is true. At the end, after all ifs and elsifs the execution flow reaches the last item, the else, which is executed if no other statement is true.

In our program, we check for the type of calculation and if th users type it correctly we execute it, otherwise we just print him a message saying we didn't understand what he said.

So, the basic structure for the conditional operator is:

if (statement that should be true) {
  execution code;
} else {
  error code;
}

Sometimes we do want to put real code within the else block, it's not only reserved for error checking and report.

Looping

Now you're almost a programmer and your friend asks you to print the sum of all numbers between 1 and 10. You can do it, I'm sure! Let's implement it now:

# exmample4.pl - sum from 1 to 10
 
$sum = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10;
print "The sum from 1 to 10 is $sum\n";

Pretty easy huh ? Now, he asks you, in fact, to print a sum between 1 and a hundred and not to sum multiples of 3 and 7. What would you do ? If he had asked for the simple sm you could use Gauss theorem for arithmetic sums and end um with an one line program. But how to take into account the multiples of 3 and 7 ?

Well, maybe there's a mathematical theorem that I don't know to accomplish that, but let's do it the easiest way (and most of the time the slowest): using loops. A loop is an instruction that repeat over and over again the same portion of your code depending on some statement being evaluated as true or false.

The simplest kind of loop is the while loop:

while (statement) {
  code;
}

Simple as that, while the statement remains true the program executes that code within brackets. Your code is suposed to change the validness of the statement otherwise you'll never get out of the loop.

So, to sum simple numbers we could have written our code like:

# exmample5.pl - sum from 1 to 10 usng while
 
$sum = 0;
$number = 1;
while ($number <= 10) {
  $sum = $sum + $number;
  $number = $number + 1;
}
print "The sum from 1 to 10 is $sum\n";

Looks like it's more complicated, isn't it ? But it's not. You can replace the 1 and 10 by whatever you want and youcan have a generic sum. Now, let's see how to program the sum menioned above:

# exmample6.pl - sum from 1 to 100, no multiples of 3 and 7
 
$sum = 0;
$number = 1;
while ($number <= 100) {
  if ($number % 3 == 0 || $number % 7 == 0) {
    $number = $number + 1;
  } else {
    $sum = $sum + $number;
    $number = $number + 1;
  }
}
print "The sum is $sum\n";

So, for all numbers smaller or equals to 100 it takes the rest of a division (%) with 3 and 7 and if any of them (the OR operator is ||) is zero it just increments the number, otherwise it adds it's value to the global sum.

Note that the code is changing the statement so it can be false one day, If we hadn't put the increment code inside te if code block it'll never increment the number when it reaches the first multiple of 3 or 7 (which is 3 itself) and would keep running on 3 without increment, for ever. So, be specially carefull when dealing with loops, with a simple error you can make your computer work to death.

When the subject being iterated through the loop have well defined boundaries you can use another kind os loop as well, the for. Instead of having the expression alone, the for lets you define the boundaries and let your code run free, like this:

for ($number = 1; $number <= 100; $number = $number + 1) {
  code;
}

Note that it's just a rearrangement of things, it's nothing different from a while, you can also see the actual code above in the while example. It's particularly good for incrementing variables, as we had on our previous example.

The format of a for block is:

for ( initialization ; statement ; data change ) {
  code;
}

Initialize your affected variables on the first part, put the true / false statement ni the second and change your variables on the third so they can eventually reaches a false statement in the future.

The main loop of our forme example using while then becomes:

for ($number = 1, $sum = 0 ; $number <= 100 ; $number = $number + 1) {
  if ($number % 3 != 0 && $number % 7 != 0) {
    $sum = $sum + $number;
  }
}

It's simpler, more elegant and less error prone. And note ou can initialize as many variables as you want on the first part, just split them using commas. Note the use of ”!=”, it means different and theAND operator is && so reads as it says and you'll figure out what I was trying to say.

For more information on programming logic read the other text about it.

Flow control

So far so good, you're in the middle of your loop, executing a complex arithmetic expression for your school program and you find an error. An irrecuperable and unavoidable error that might happen because of the uniqueness of your problem and that's nothing to do with the programming language you have chosen, it's up to you to decide what to do, you can either go to the next loop or make it the last one!

On our previous example we could use it to avoid reversing the logic concept of our if and every time our flow reaches the if and it's true (ie. our number is multiple of 3 or 7) we send it to the next loop wihout computing anything at all:

for ($number = 1, $sum = 0 ; $number <= 100 ; $number = $number + 1) {
  if ($number % 3 == 0 || $number % 7 == 0) {
    next;
  }
  $sum = $sum + $number;
}

So, every time the loop fall on that if we'll ask it to gently follow to the next loop, and that will skip the sum right below. We could also make it break the execution , making the last execution when the number becomes bigger than 100:

while (1) {
  if ($number % 3 == 0 || $number % 7 == 0) {
    next;
  }
  if ($number > 100) {
    last;
  }
  $sum = $sum + $number;
}

The while syntax have a “1” inside to denote a value that will always be true no matter what happens to your pogram inside the loop, so, if we hadn't put the last inside it, the code would never be able to get out of that loop.

On most programming languages those two statements are called continue meanig next and break meaning last.

Last but not least

The last basic structure that is commonly used in all programming languages is switch and is only here because it trully needs the flow control statements. The switch statement chooses between a list of possible answers and execute the refered code.

Unfortunatelly Perl does not have a proper switch statement and I'll not show the hack to accomplish that in the switchway using perl, not here. So, I'll just exlain how des it work:

$option = 1, 2 or 3 for intance;
 
switch ($option) {
  case '1':
    # do something
    next;
  case '2':
    # do other things
    next;
  default:
    # if don't fall anywere above, comes here
    next;
}

The excuse of not having the switch statement in Perl is not bad, there are many other ways of doing the same thing, so it was redundant. I agree in parts, and will show you the equivalent code using if, elsif and else.

if ($option == 1) {
  # do something
} elsif ($option == 2) {
  # do other things
} else {
  # if don't fall anywere above, comes here
}

It's simpler, cleaner and should work exctly the same way, if it was not for one particular feature of switch that the above code don't mimic quite well. On switch, if you don't place the “next” at the end of each block it'll keep going and running on the blocks below.

It's good if you want to provide the same behaviour for diferent inputs, like:

switch ($option) {
  case '1':
  case '3':
  case '5':
    # do something
    next;
  case '2':
  case '4':
  case '6':
    # do other things
    next;
  default:
    # if don't fall anywere above, comes here
    next;
}

Now, if your option is either 1, 3 or 5 you'll have the same behaviour. The same will happen for choices 2, 4 and 6. Of course, you can do it using ifs but the result code is not so clear:

if ($option == 1 && $option == 3 && $option == 3) {
  # do something
} elsif ($option == 2 && $option == 4 && $option == 6) {
  # do other things
} else {
  # if don't fall anywere above, comes here
}


 
learning/programming.txt · Last modified: 05 09 2007 19:15 (external edit)
 
Recent changes RSS feed Creative Commons License Driven by DokuWiki