Wednesday, April 20, 2011

LESSON 3: Algorithms and Psuedocode

What is an algorithm?


Put simply, an algorithm is just a set of steps you complete in order to solve a problem or perform an action. For instance, lets say the problem you are solving is that you need to determine what a two week pay check for a salaried employee should be:

1. Determine what the salary amount for the employee is
salary = 40,000
2. Determine what 1 week worth of pay is for that salary
weekly = 40,000 / 52 (or 769.23)
3. Multiply by two to figure the 2 week pay check
paycheck = weekly * 2 (or 1538.46)

So you could say that these 3 steps make up an algorithm! Obviously, algorithms can get really complicated depending on what it is you're trying to accomplish. But for the sake of understanding the concept, this should be enough.

What is Pseudocode?


Pseudocode is exactly what it sounds like. It is code that isn't really code. Some people will call this "structured english". Personally I think the two are different, but its not important as a codemonkey, just understand that it is fake code. So what does that mean? Well from my experience,

Pseudocode could be all english:


get salary
divide salary by 52
multiply result by 2
display result


or english structured like code


declare salary as integer
declare weekly as double
declare payCheck as double


set salary = 40000
set weekly = 40000/52
set payCheck = weekly * 2


or a combination of actual code and structured english


int salary;
double weekly, payCheck;

salary = get employee salary;
weekly = salary / 52;
payCheck = weekly * 2;
NumberFormat formatter = new DecimalFormat("$#,###.##");

display formatter.format(payCheck);

So you can see the point here, I think. Pseudocode allows you to structure the logic without worrying about proper code syntax. Mixing real code with pseudocode can help you remember specifics about how you were thinking it should be implemented.

When trying to figure out a complex problem or process, it is very helpful if you write out the pseudocode first, to help you get your ideas out quickly before you lose them! Sometimes the brain get in the way of your creativity when you start thinking about the details of implementing the algorithm. Just get it out in english first, then come back and convert it to actual code. I'll try to do this when we get into real coding, at least for the early stages.

No comments:

Post a Comment