Difference between revisions of "User:Hatter/programming principles"
(→Loops) |
(→Loops) |
||
Line 148: | Line 148: | ||
==Loops== | ==Loops== | ||
− | :''See also: Loops in [[C#Loops|C]], [[ | + | :''See also: Loops in [[C#Loops|C]], [[CPP#Loop_Functions|C++]], [[Perl#Loops|Perl]], [[PHP#Loops|PHP]], and [[Ruby#Loops|Ruby]]'' |
Loops are very similar to conditionals in that they test a condition in order to function, but unlike conditionals instead of continuing with the program, they go back to the start of the block they are in until that condition is no longer true. A loop that is always true, either intentionally or not, is called an <i>infinite loop</i> and will run until the program is stopped, or the loop is escaped. This means to avoid infinite loops, you must change the condition in some way. Generally loops test against variables that are changed inside the loop. $variable++ (The common form for increment, or +1) would be taking a variable and adding one, so if you have a loop that tests your variable to be less than a number (say 10), adding $variable++ would repeat until it's larger (say 10 times from $variable equaling 0) Common loops are ''while'' and ''until''. | Loops are very similar to conditionals in that they test a condition in order to function, but unlike conditionals instead of continuing with the program, they go back to the start of the block they are in until that condition is no longer true. A loop that is always true, either intentionally or not, is called an <i>infinite loop</i> and will run until the program is stopped, or the loop is escaped. This means to avoid infinite loops, you must change the condition in some way. Generally loops test against variables that are changed inside the loop. $variable++ (The common form for increment, or +1) would be taking a variable and adding one, so if you have a loop that tests your variable to be less than a number (say 10), adding $variable++ would repeat until it's larger (say 10 times from $variable equaling 0) Common loops are ''while'' and ''until''. | ||
Revision as of 23:52, 14 October 2012
Contents
Introduction
Pseudocode
Pseudocode is a human readable expression of the intended functionality of a program. It tends to consist of very high level descriptions of the code it is describing while leaving out aspects of programming languages that, while necessary for computers, are unneeded for human understanding. Pseudocode is often used in place of actual code during the initial design of a program to allow the writer to outline the function of his program and how he intends to implement it in an easy to understand manner. Pseudocode cannot be compiled nor executed, it is purely human language oriented.
Variables and Data Types
Variables, as the name implies, are dynamic objects in programming which change based on their context. That is, for instance, $variable can always be returned with $variable but the value returned may change. In high-level languages, there are generally three types of variables: Scalars (single values), Arrays (or lists), and Associative Arrays (or hashes).
In more mid-level languages, variable types are broken up further into integers, strings, character arrays, floating point, booleans, and more. In these languages, arrays are simply constructs of a particular type (non-mixed) and Associative Arrays or hashes are actually user-defined data types.
Integer:
- A whole number, positive or negative
Floating point:
- A number with a decimal point
Character:
- A single text character, e.g. "h"
String:
- Multiple text characters, e.g. "hello world!"
Boolean:
- Can only be true or false. Some languages preprocess these as 1 or 0, respectively.
Scalars:
- A scalar is the simplest form of a variable, as it is a single object. You may recall a person's name or a single number. These are typically used for basic things like running the same equation (think X + 10 =) when you'll need changing data to test.
Arrays:
- An array is a bit more complex than a Scalar. Arrays are formed from multiple scalars and can contain scalars or predefined, static strings. You may have a variable for a classroom, which inside lists all the names rather than one.
Associative Arrays:
- An associative array is similar to an Array, but with two fields that compare each other instead of individual strings. For instance you might have an array that compares the classes first names to last so that at any point if you know the person's last name, you can find their first.
Combining Variables:
- The true benefit of variables comes when you combine them. You may have a scalar called number to recall an element in array called months to pull a month's name by its chronological number, or use a scalar called last_name that refers to your hash called full_names so that every time you recall last_name it associates the first.
Control Flow
Validity
Validity is a simple concept. If a condition is true, the conditional or loop will act accordingly. Likewise if it's false, that is a 0, empty string, or incorrect comparative operator, it will treat the loop or conditional in the opposite manner.
Comparative Operators
Comparative operators are used when you want to return a true value by comparing two other values. You might have a 7 and a 5. Since they're not empty strings, (7) would always be true. (5) would likewise be true, but is 7 less than 5? Common comparative operators are and, or, equal to, not equal to, greater than, greater than or equal to, less than, and less than or equal to. They return true when the mathematical value is satisfied.
Comparative Operators and Symbols | ||
---|---|---|
Literal | Shorthand | Symbolic |
And | and | && |
Or | or | || |
Equal to | eq | == |
Not Equal to | ne | != |
Greater than | gt | > |
Greater than or equal to | ge | >= |
Less than | lt | < |
Less than or equal to | le | <= |
Conditionals
Typically found as if, unless, else, or else if, conditionals take action according to the validity of a condition. That means they either do an action contained in the block of code, or skip past the block altogether depending on the conditional used.
If
The most common conditional is if. If your condition returns true, for instance:
if (5 < 7) or if (5 != 7)
It proceeds with the block and performs actions. If it returns false, it ignores the block altogether and goes to the next.
Unless
Unless is the exact opposite of if. It only continues with the block if the condition isn't met and returns a false value.
unless ($variable < $limit)) do something
This conditional can be reworded into an if, and you should use what feels more natural to you ("if exists $variable" is the same as "unless not exists $variable")
Else
Else is plain conditional in that it doesn't test anything except the previous conditional. For instance you could have a statement that reads
unless this variable is less than a limit do this else print "You're not allowed!"
If the previous condition is not satisfied, it will always run. If it was, it will never run.
Else if
Else if, or more commonly elseif is exactly what it sounds like: A combination of if and else. It tests the previous condition and then tests a new condition if the previous one was false. A good example is Goldilocks and the Three Bears is:
if $temperature is greater than 10 print "This porridge is too hot" elseif $temperature is less than 10 print "This porridge is too cold" else print "This porridge is just right!"
Only if the first condition isn't already met, it moves on to test the next one. If the next one isn't met, either, the else at the end assumes itself true.
Switch
Loops
Loops are very similar to conditionals in that they test a condition in order to function, but unlike conditionals instead of continuing with the program, they go back to the start of the block they are in until that condition is no longer true. A loop that is always true, either intentionally or not, is called an infinite loop and will run until the program is stopped, or the loop is escaped. This means to avoid infinite loops, you must change the condition in some way. Generally loops test against variables that are changed inside the loop. $variable++ (The common form for increment, or +1) would be taking a variable and adding one, so if you have a loop that tests your variable to be less than a number (say 10), adding $variable++ would repeat until it's larger (say 10 times from $variable equaling 0) Common loops are while and until.
While
While is very similar to if, generally both in syntax and function. If a condition returns true, it runs the block, and then checks again to see if the block is still true. If it is, it runs it again. This means if you don't do something to change the condition somewhere in the block, it will always be true and run infinitely. 1, since it is not an empty string, false comparative operator, or 0 would always test as true, so while (1) will perform the same action or set of actions over and over.
while 1 is less than 10 do this do this after all that
Until
Until is while's polar opposite. It tests for a false value, and runs the loop until the value tests positive. Taking the Goldilocks example again, you could say
until a random number between 1 and 20 is 10 print "I'm not eating that!"
This would make your program keep testing random numbers until a 10 is reached, at which point you could program what would happen with the best porridge.
Functional Programming
Functions
A function contains code that will be executed whenever the function is "called." A common use is to prevent redundancy in code and keep it organized. Functions accept arguments and can return a value. This allows a function to be dynamic, for example, you might have a function that accepts two numbers and adds them together and returns the result. This might look like (in pseudo code):
func add(integer a, integer b) return a + b; print add(1, 2);
This code would add the two arguments together (in this case a (= 1) and b (= 2)) then it adds them together and returns the result (3), the return value is then printed.
Recursion
Data Structures
Objects
Programming Style
A critical strategy to keep in mind is the practice of keeping your code organized and to follow the standards put forth by coders who came before you. This is known as programming style and can spell the difference between a good hacker and an amazing hacker.
The vast majority of programming languages offer the ability to comment your code by using special syntax. It is important that you use comments to document your code, it's useful to think "If I returned to this code in 20 years to improve it, would I be able to tell what it was doing?".
Variables are something that you will deal with constantly in your programming activities, these are names given to some piece of data and like the name implies can vary during the life of your program. Good programming style incorporates useful variable names. In other words, if you had a program that took input from a user then changed the first letter of their name it would be bad style to name that variable "apple" as opposed to "userInput". Something to strive for is code that is self-documenting, the organization and variable naming being so good that it requires few comments to explain it's execution.
A major benefit of keeping good programming style is that the clear organization of your program will aid in spotting errors at a much faster rate than someone who was careless in crafting their program (resulting in the dreaded "spaghetti code"). Not only does it help in debugging but, it will also make it easier to update your code to patch any exploits/vulnerabilities. There exist many other minute programming styles which are specific to the language you are learning (in Java it is customary to use camelCase to name variables while in Python you will see variables written as name_of_var) so it is recommended that you talk with the community in order to discover best practices.