Monday, 21 January 2013

Programming and Problem Solving in PHP #1

Programming and Problem Solving

"computer science is no more about computers than astronomy is about telescopes." -Edsger W. Dijkstra

Hey Everyone, welcome to my first tutorial on Programming and Problem solving. The purpose of this tutorial is to break the ice and provide an introduction to the world of programming and problem solving for you guys.  The language being used for this will be php for a number of reasons: PHP is a very robust and powerful scripting language, its syntax is highly influenced by C/C++ and as such it is very similar to a number of other programming languages so if you decide to branch out after it should make the transition a little easier, it's an interpreted language, so you don't need to go through the process of compiling or using a debugger to get started which can be a little intimidating to some new users. A key focus of this is on the methods and concepts used though, as they will be universal no matter which language you are writing in. To start we will discuss briefly Algorithms, which are often overlooked by novice programmers but are crucial to producing quality and efficient code as well as saving you hours of ripping your hair out in frustration.

Algorithms:

An Algorithm is the first step in the problem solving process. Before you even touch your keyboard and write one line of code you should at the very least have written out a basic algorithm to provide a framework for your application. The technical definition of an algorithm is "A finite number of steps that solve a particular problem". A very good analogy to an algorithm is a recipe card, if each step is followed then the end result will be whatever food you're trying to make and obviously there is a finite number of steps to baking a cake. Without first logically stepping through your problem you can find yourself writing code for 3 or 4 hours only to find that you have misunderstood your original problem and solved a different one or none at all, meaning you've wasted your time and need to start again. It also causes headaches if you ever try to add to an application and havn't planned for it, you'll have to splice new code in and create a clusterfuck of frankenstein code that is near unmaintainable. So lets first try and make a simple algorithm for making a pot of coffee.

Step 1: Get a coffee filter
Step 2: get coffee grounds
step 3: get water
step 4: fill coffee machine with water
step 5: put coffee filter into coffee machine
step 6: put coffee grounds in coffee filter
step 7: turn on coffee machine


If we follow this set of instructions we're minutes away from a fresh cup of coffee! fuck yeah! we could make it more thorough by adding additional steps, such as specifying what angle to tilt the water container when pouring it to determine if it pours quicker or slower, the faster it pours the higher chance of spilling the slower it pours the lower the chance, here we have an opportunity to tweak the process out, we can weigh the cost benefit analysis between speed and spillage to create an optimal pour, or we can remove steps to make it a more basic outline. Generally a more detailed algorithm is always superior to a more basic one but make sure you always have at least something before you start. If you want to be a good programmer you have to view everything as a problem to be solved, in life there is almost always more than one solution to a given problem but not all solutions are created equally and some are inherently better than others, by assessing the problem and breaking it into its core components we can create a more elegant and efficient solution.

Variables:

OK so up until now we've been discussing a lot of boring theory but havn't actually written any code. Well thats going to change now. The first thing we want to look at with regards to the programming language itself, is the syntax for variables(syntax is just a fancy word for the way the language is written. It works with non-programming languages too :D). A variable is a container for data. Think back to math when you were a kid and you had to solve this problem:

let x = 2 + 5
solve for: 2x + 3


In this example x is equal to the value 7, the solution to the question then is: 2(7) + 3 or 14 + 3 or 17. However it is much easier to write 2x + 3 than 2(2 + 5) + 3, and if we want to change the value of x but keep the same equation all we have to change is the first line where we declare x. Variables work in the exact same way in programming. But before we go further and actually declare a variable theres something else we should look at with regards to variables: Data Types

Given the nature of programs and computers sometimes we need values other than 2 + 5, say, if you wanted to store someones name, or if you wanted to operate on a fraction of a number. When we declare a variable it is assigned a data type that tells the computer how to store the data we assign to it internally. Some basic data types that you should be familiar with are:

Integers
    Integers are whole numbers: 4, 2, 3, 87, 349234 are all integer values
Floats(doubles)
    floats or floating point numbers are used for numbers with a decimal point like 5.2 or 4.20
Chars
    a char, as its name suggests, is a single character like 'a' or '@'
Strings
    a string is a sequence of characters, like a name: "Brian" or "Phaedrus"
Boolean
    Boolean values are a logical true or false value, in many languages boolean values are aliases for the binary values 0 and 1. 0 representing false and 1 representing true(although in many instances any non-zero value will be considered true but we will come back to that point later on)


There are some other data types as well as the ability to create your own data types but for now these are the core types we will focus on. With Data types in mind theres a few things to address, you might ask "whats the difference between 5 and 5.0? why is it necessary to have more than one data type for numerical values?" The answer is a long complicated and largely boring one that involves converting from decimal into binary(Remember, computers work internally using binary values, so when you give the variable age a value of 25 the computer needs to convert it into a binary value to store it) Computers allocate more space for a float than they do for an int so even if the value is equivalent such as 5 or 5.0 the value is internally represented differently. So what happens if we try to multiply an integer value age equal to 25 with a double value cur_year which is equal to 0.8? Now in php, because it is such a robust language the answer is slightly anti-climactic. The php interpreter will automatically convert age to 25.0 and multiply that. In some languages like C or C++ we would have to explicitly typecast(convert a value from one data type to another) before performing the multiplication, but php being the sexy beast it is, takes care of this process for us behind the scenes. Even though php can typecast automatically it still provides a set of functions for you to explicitly typecast values if you ever have need. For more information on data types you can consult: http://php.net/manual/en/language.types.php

When declaring a variable the following set of instructions must be adhered to:

    Variables in PHP start with a $ sign, followed by the name of the variable
    The variable name must begin with a letter or the underscore character
    A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
    A variable name should not contain spaces
    Variable names are case sensitive (y and Y are two different variables)

So now that all of thats out of the way we can start writing some basic programs:

<?php
$x = 25;//Assign a value of 25
$y = 42;//Assign a value of 42
$z = 56;//Assign a value of 56

$q = $x + $z;//Assign a value of 81
$r = $y * $x;//Assign a value of 1050
$s = $q * 5;//Assign a value of 405

?>

Notice that to assign a value we simply use a single = sign. Make a mental note that assignment uses a single equals sign, later on you'll see why this is important.

So we can now do some basic arithmetic, but how do we get the computer to display our results back to us? Theres several options but for the time being we'll just focus on the basic ones echo and print. Both echo and print work in nearly identical ways:

<?php
$name = "Phaedrus";
print "Fuck " . $name . " is awesome\n";
echo $name . " is the shit!\n";
?>

will produce the output:

Fuck Phaedrus is awesome
Phaedrus is the shit!

so now we can assign values, perform basic calculations, and print our values back out to the screen! That covers the basics that we'll go over in this tutorial, Ill post some followups that go into further programming concepts like loops, if/else conditionals, functions, all the way up to creating objects. If anyone has any questions about this tutorial or if anythings written in an unclear way please let me know and ill try to clear things up. For practice try writing some basic programs that play with performing basic equations and printing the results, a basic list of mathematical operators is:


+
    Addition: Adds the value on the left to the value on the right
-
    Subtraction: Subtracts the value on the right from the value on the left
*
    Multiplication: Multiplys the value on the left by the value on the right
/
    Division: Divides the value on the left by the value ont he right
%
    Modulus Division: written in the same format as regular division but returns any remainder from the division

No comments:

Post a Comment