Programming+Basics

=Frequently Asked Questions about Programming Basics=

What is an algorithm?
Article and examples on How Stuff Works - []

From Wikipedia:

" In mathematics, computer science, and related subjects, an **algorithm** is an effective method for solving a problem using a finite sequence of instructions. Algorithms are used for calculation, data processing, and many other fields.

Each algorithm is a list of well-defined instructions for completing a task."

" The word //algorism// originally referred only to the rules of performing arithmetic using Arabic numerals but evolved via European Latin translation of al-Khwarizmi's name into //algorithm// by the 18th century. The word evolved to include all definite procedures for solving problems or performing tasks."

Retrieved from Wikipedia on March 21, 2010 at []

**Humorous Example from the Big Bang Theory**
Sheldon needs to use the open science grid computer and must get authorization to use it from Barry Kripke (a rival of sorts). Leonard tells Sheldon that only Kripke's friends get to use the computer. Sheldon decides he must make friends with Kripke to accomplish his goal. Unfortunately, Sheldon is not good at making friends so he creates a friendship algorithm from a description (in a children's book) of how to make friends.

Sheldon demonstrates the algorithm in the company of his friends by calling Kripke on the phone. Sheldon's original algorithm contains an infinite loop, which Wolowitz fixes by adding a counter and an escape in the form of the least objectionable activity (LOA). This algorithm also contains a case statement regarding the choice of hot beverages.

Sheldon's Friendship Algorithm [] YouTube clip of the demonstration of Sheldon's algorithm []

Big Bang Theory Season 2, Episode 13 Friendship Algorithm

Humorous Example for Doing Design Work
[]

Humorous Example for Buying an iPad
[|http://www.bytesizer.com/wordpress/wp-content/uploads/2010/03/should-i-buy-an-ipad.jpg]

Related Information - Activity Diagram (User Interaction Design)
[]

What methods are used to represent and communicate the steps contained within an algorithm?

 * Flowcharts** are often used to graphically represent an algorithm. More information on flowcharts: []

Common ways to communicate/represent an algorithm in writing include use of **pseudocode** and **programming languages**.

"Algorithms can be expressed in many kinds of notation, including [|natural languages], [|pseudocode], [|flowcharts], [|programming languages] or [|control tables] (processed by [|interpreters]). Natural language expressions of algorithms tend to be verbose and ambiguous, and are rarely used for complex or technical algorithms. Pseudocode, flowcharts and control tables are structured ways to express algorithms that avoid many of the ambiguities common in natural language statements, while remaining independent of a particular implementation language. Programming languages are primarily intended for expressing algorithms in a form that can be executed by a [|computer], but are often used as a way to define or document algorithms."

Retrieved from Wikipedia on March 21, 2010 at []

Why would someone want to represent or communicate an algorithm?
Computers do not [|grok] *. People can grok. People can and do fill in missing information; computers cannot.

Suppose a neighbor tells you, "They already left." If you had been talking to your neighbor yesterday about bringing over some kids toys for the neighbor's visiting nieces and nephews, you could fill in the details and know that you are too late. The kids have gone home.

Unlike people, **computers require specific and unambiguous instructions**. Computers understand true or false, 1 or 0. A computer would never understand, "They already left." Computers cannot observe, remember context and fill in the blanks.

The tools and methods used to represent or communicate an algorithm help people **make sure there are no missing steps** or pieces **when the process is converted** into **the instructions for a computer** to understand and execute.

(*) " To **grok** (pronounced /ˈɡrɒk/ ) is to share the same reality or line of thinking with another physical or conceptual entity. Author Robert A. Heinlein coined the term in his best-selling 1961 book //Stranger in a Strange Land.// In Heinlein's view, grokking is the intermingling of intelligence that necessarily affects both the observer and the observed."

Retrieved from Wikipedia on March 21, 2010 at []

How can we tell a computer what to do?
Processes could include instructions to do any of the following:


 * Execute a task
 * Execute a task if a certain condition is true
 * Execute a task until a certain condition is true

Suppose you want to tell a computer to add air to a tire. If you just say **add air to the tire**, the computer will add air **until the tire bursts**.

We need to break this process down into logical steps:


 * 1) Check the air pressure.
 * 2) If the air pressure is low, add air until the air pressure measures the optimum level.

For step one we need to create a variable for air pressure, because this value will change as air is added and possibly removed.

code set variable air_pressure to {value of the current air pressure};

code

For step two, we need to help the computer determine whether or not the air pressure is low. We need to set the value for optimum air pressure. We could make this a variable as well. In cases where the value will not change for this process, we could also make it a constant. Let's say the optimum air pressure is 30 psi.

code set variable optimum_air_pressure to 30 psi; code

Now we need to look at all the possibilities:


 * //air_pressure// has no value, which means something went wrong when checking the air pressure so do step 1 again
 * //air_pressure// is less than //optimum_air_pressure//
 * //air_pressure// is equal to //optimum_air_pressure//
 * //air_pressure// is greater than //optimum_air_pressure//

code determine air pressure;

if (air_pressure has no value) { determine air_pressure; }

if (air_pressure LESS THAN optimum_air_pressure) { add air; }

if (air_pressure GREATER THAN optimum_air_pressure) { remove air; }

if (air_pressure EQUAL TO optimum_air_pressure) { end process; }

code

As we look more closely, we find parts of our process that repeat until some condition is true.

code determine air pressure until air_pressure has a value;

if (air_pressure LESS THAN optimum_air_pressure) { add air until air_pressure EQUAL TO or GREATER THAN optimum_air_pressure; }

if (air_pressure GREATER THAN optimum_air_pressure) { add air until air_pressure EQUAL TO or LESS THAN optimum_air_pressure; }

code

We also need to build in a time limit for adding air and removing air. The computer could add or remove air in 10 second increments and then check again.

code set variable add_remove_air_increment to 10 seconds;

set timer to add_remove_air_increment;

if (add_air is true) { add air until timer expires; determine air pressure; } else { remove air until timer expires; determine air pressure; } code

There is a danger here. If we try to get exactly to the optimum air pressure, the computer may continue to add and remove air forever. There are some ways to address this:


 * Provide a tolerance level in //optimum_air_pressure// of plus or minus 1 psi so we would accept a value of 29, 30 or 31
 * Decrease the amount of time the computer adds or removes air as the value gets closer to the optimum air pressure

Example for providing a tolerance: code set variable min_optimum_air_pressure to 29 psi; set variable max_optimum_air_pressure to 31 psi;

determine air pressure until air_pressure has a value;

if (air_pressure LESS THAN min_optimum_air_pressure) { set timer; add air; determine air pressure; }

if (air_pressure GREATER THAN max_optimum_air_pressure {   set timer;    remove air;    determine air pressure; }

if (air_pressure GREATER THAN min_optimum_air_pressure AND LESS THAN max_optimum_air_pressure {   end process; }

code

Decrease the increment to add/remove air as the air pressure gets closer to optimum air pressure.


 * If the air pressure is 5 psi below the minimum optimum air pressure, use 10-second increments to add air
 * If the air pressure is 5 psi above the maximum optimum air pressure, use 10-second increments to remove air
 * If the air pressure is within 5 psi of the minimum and maximum of the optimal air pressure, use 5-second increments to add and remove air

Example for changing the increment as the air pressure gets closer to the optimal air pressure: code determine air pressure until air pressure has a value;

if (air_pressure LESS THAN min_optimum_air_pressure) { if (air_pressure LESS THAN min_optimal_air_pressure minus 5) { set increment to 10 seconds; set timer; add air; determine air pressure; } else { set increment to 5 seconds; set timer; add air; determine air pressure; } }

if (air_pressure GREATER THAN max_optimum_air_pressure {   if (air_pressure GREATER THAN max_optimal_air_pressure plus 5) {        set increment to 10 seconds;        set timer;        remove air;        determine air pressure;    } else {        set increment to 5 seconds;        set timer;        remove air;        determine air pressure;    } }

if (air_pressure GREATER THAN min_optimum_air_pressure AND LESS THAN max_optimum_air_pressure {   end process; }

code

We can continue to refine our process until we are sure we have something a computer can execute and that will eventually end the process.

Now let's say we want the computer to do this for all the tires on a vehicle. Vehicles do not all have the same number of tires. We could set a variable for the number of tires and then run the loop until all the tires are done.

code current_tire_number = 1; // initialize a counter to keep track as each tire is processed number_of_tires = 2; // scooter

while current_tire_number LESS THAN OR EQUAL TO number_of_tires {

determine air pressure until air_pressure has a value;

if (air_pressure LESS THAN min_optimum_air_pressure) { if (air_pressure LESS THAN min_optimal_air_pressure minus 5) { set increment to 10 seconds; set timer; add air; determine air pressure; } else { set increment to 5 seconds; set timer; add air; determine air pressure; }   }

if (air_pressure GREATER THAN max_optimum_air_pressure {       if (air_pressure GREATER THAN max_optimal_air_pressure plus 5) {            set increment to 10 seconds;            set timer;            remove air;            determine air pressure;        } else {            set increment to 5 seconds;            set timer;            remove air;            determine air pressure;        }    }

if (air_pressure GREATER THAN min_optimum_air_pressure AND LESS THAN max_optimum_air_pressure {       end process;    }

at end process, set current_tire_number to current_tire_number PLUS 1; // increment to the next tire }

code

We can also create a list of tires and then tell the computer to loop through the list.

code for each tire in tire_list {

determine air pressure until air_pressure has a value;

if (air_pressure LESS THAN min_optimum_air_pressure) { if (air_pressure LESS THAN min_optimal_air_pressure minus 5) { set increment to 10 seconds; set timer; add air; determine air pressure; } else { set increment to 5 seconds; set timer; add air; determine air pressure; }   }

if (air_pressure GREATER THAN max_optimum_air_pressure {       if (air_pressure GREATER THAN max_optimal_air_pressure plus 5) {            set increment to 10 seconds;            set timer;            remove air;            determine air pressure;        } else {            set increment to 5 seconds;            set timer;            remove air;            determine air pressure;        }    }

if (air_pressure GREATER THAN min_optimum_air_pressure AND LESS THAN max_optimum_air_pressure {       end process;    }

}

code

For more information on control structures (if statements and loops): []

For more information on control flows (if statements and loops): []

For more information on variables: [|http://en.wikipedia.org/wiki/Variable_(programming)]

What are data types?
"In programming, classification of a particular type of information. It is easy for humans to distinguish between different types of data. We can usually tell at a glance whether a number is a percentage, a time, or an amount of money. We do this through special symbols -- %, :, and $ -- that indicate the data's //type//. Similarly, a computer uses special internal codes to keep track of the different types of data it processes. Most programming languages require the programmer to declare the data type of every data object, and most database systems require the user to specify the type of each data field. The available data types vary from one programming language to another, and from one database application to another, but the following usually exist in one form or another:
 * integer** **:** In more common parlance, //whole number//; a number that has no fractional part.
 * floating-point** **:** A number with a decimal point. For example, 3 is an integer, but 3.5 is a floating-point number.
 * character** **(text** **):** Readable text"

Retrieved from Webopedia on March 21, 2010 at []

Another common data type is **boolean**, which represents a value of true or false.

How does Common Gateway Interface (CGI) scripting work?
Tutorial []

What is object-oriented programming?

 * Class:** defines attributes (properties - in the form of variables) and behaviors (methods - in the form of functions for objects). A class is the blueprint for creating objects.


 * Object:** an instance of a class


 * Instantiation:** the process of creating a new instance of an object.

Class for a User:

Properties
 * Username
 * First name
 * Last name
 * Email address

Methods
 * Edit profile
 * Accrue bonus points
 * Post to forum

Instance of User Robert Gregory:

Properties
 * bobgreg
 * Robert
 * Gregory
 * bobgreg@bobgreg.com

Methods
 * Robert changes his address
 * Robert buys products and his bonus points are increased
 * Robert comments on a question posted by another user


 * Abstraction:** reducing details into core concepts i.e. a list of properties and methods


 * Encapsulation:** wrapping the properties and methods in such a way as to keep them private from other classes (also referred to as black boxing)


 * Inheritance:** the idea of parent and child classes, which allows a child class to define more specific properties and methods while retaining all the properties and methods of the parent class. This allows us to define properties and methods once. If changes are made to the parent, children will inherit the changes.

Example 1: A Customer is a child class of User. The Customer class can add properties and methods specific to customers. Not all users are customers.

Example 2: A Vendor is a child class of User. The Vendor class can add properties and methods specific to vendors. Not all users are vendors.

Example 3: An Employee is a child class of User. The Employee class can add properties and methods specific to employees. Not all users are employees.

Example 3: If new properties and/or methods are added to User, then Customer, Vender, and Employee will inherit those changes because Customers are Users, Vendors are Users, and Employees also are Users.


 * Polymorphism:** means "many forms". It refers to treating something as something else. When it comes to executing a process meant for a User, the process also will execute for a Vendor because a Vendor is a child of a User. Likewise for Customer and Employee.

What is a function?
Think of a function as an "action" entity or object that contains instructions for completing tasks.

Creating or Declaring a Function
When the function is created or declared, it must have a name. Let's say we want to create a function to add any two numbers. We can call it //**add_two_numbers**//. Just from the name, we know we will need to provide or pass in two numbers. We could name the function //**add_numbers**//, or //**add_numbs**// or //**add_ns**// or //**add_x_and_y**//. The names for the first three provide not clue as to the quantity the function will handle. The last name gives us a clue that two things are being added but are we adding numbers or adding strings of characters? It really helps to construct our code for maximum readability and understandability. Most of us do not have a eidetic memory and it is amazing how confusing an uncommented piece of code with abbreviated or unclear variable and function names can be when you have not looked at it for a while.

The declaration of the function may look like the following.

code function add_two_numbers($number1, $number2) { $sum = $number1 + $number2; return $sum; }

code

"**function**" represents the keyword to tell the scripting language parser this is a function. "**add_two_numbers**" is the name of the function. "**$number1**" holds the first value. "**$number2**" holds the second value. The **opening curly brace {** tells the scripting language parser "this is where the instructions begin". "**return**" tells the scripting language to send the value of $sum back to script that called the function. A **semi-colon ;** represents the character that tells the scripting language parser "this is where an individual step ends". The **end curly brace }** tells the scripting language parser "this is where the instructions end".
 * Parentheses** **** are used to hold the any passed in values or arguments.
 * $sum** is a variable that will hold the sum of the two numbers.

The function can also be written without using $sum and/or by abbreviating the variables holding the values ... but, in some cases, this may make it harder to understand what the function is doing. Readability and semantic understanding is very important when writing script or code.

code function add_two_numbers($n1, $n2) { return $n1 + $n2; }

code

Important note: Each scripting language may have a slightly different syntax for declaring a function so check the documentation.

Calling a Function
Once created, the instructions will not be completed until the function is called. If a value is being returned, we need to create a variable to catch what is coming back from the function.

code // call the function, pass it 2 numbers and catch the value coming back

$thisParticularSum = add_two_numbers(5,8.9);

code

Functions are useful when a task will be completed numerous times. Because the instructions are in one place, they easy to edit and can be called from anywhere in the scripting.

What is a design pattern?
Excellent article/tutorial: //MVC for Noobs// []

.