Programming Logic

Note: I think this page is just about done. I still need to fill in some gaps but if you see anything that you feel should be included, feel free to tell me about.

This page is quick reference for common programming logic. Keep in mind every language is different but the majority of what is covered here is more than likely covered in some fashion in the language your working in.

Relational Operators

Equal To

‘==’

Not Equal To

‘!=’

Greater Than

‘>’

Less Than

‘<‘

Greater Than Or Equal To

‘>=’

Less Than Or Equal To

‘<=’

Equivalent Values

‘===’

Not Equivalent Values

‘!==’

The ‘===’ is a relational operator in JavaScript and PHP. Lets say you have a string of the number ‘1’ and an integer of the number ‘1’. The ‘===’ operator ignores the data type and tries to compare the values. In this case, $match will be assigned a boolean true value. Likewise, the “!==” works in a similar fashion but will check if they are the same values. The variable match will be set as Boolean true value and notMatch should be false. Also take anything I say about PHP or JavaScript with a grain of salt. It’s been ages since I last did anything real in these languages but this should be right, expect for maybe the names I called them. I just referrer to them as an equivalency operator in my head and you might have look this one up.

$match = ( "1" === 1 )
$notMatch = ("1" !== 2)

Also the equal to operator won’t always work in the fashion you think it will. Google search how to create a comparable object or do a comparison operation in your programming language.

Incremental and Decremental Operators

There are generally two methods built-in that can increment and decrement numbers, pre and post.

Pre-Increment

++i

Post-Increment

i++

Pre-Decrement

--i

Post-Decrement

i--

Bitwise Operators

AND

‘&’

Inclusive OR

‘|’

Exclusive OR

‘^’

Left Shift

‘<<‘

Right Shift

‘>>’

Unary

‘~’

Note: These bitwise operators examples in C

Logical Operators

Logical AND

‘&&’

Logical OR

‘||’

If Statements

Generic If Statement
If statements are used to check the condition of a variable or function.

if( x == y )
// Do something if true

If Else Statement

The else statement is what will be executed if the condition in the if statement isn’t matched.

if( x == y )
// Do something if true
else
// Do something if not true

Else IF Statement
Else if statements are just another if condition to check against.

As you can see, at the core of if statements are Boolean logic. You can also throw a Boolean data type in the statement to simply things.

boolean bool = True;
if( bool )
// Will do something if bool is true
else if ( !bool )
// Will do something if bool is false
else
// Will never be executed!

Tenary Operator
Personally, I love tenary operators but they might be somewhat confusing compared to if statements. In a nut shell, tenary operators are just short hand of if ‘?’ then ‘:’ else statements. The code left of the ‘?’ mark will the condition your checking in this case I’m checking if 10 is less than 5. The code to right of the ‘?’ mark and left of the ‘:’ is what will happen if the test condition returns true. Since 10 isn’t greater than 5 this code will be ignored. The code left of the ‘:’ is the else part and will be executed. This this case, the variable max will be set with the 10.

int max = (10 < 5) ? 5 : 10;

Switch Statements

Switch statements are similar to if statements. Inside the switch parenthesis, the variable that we’re going to check is referenced. The case statements are the potential values for the given switch variable. In this case, the variable number is set to 1. The case statement referencing the integer 1 will be executed and “Hello World” will be sent to standard out. Also you can default case statement when the switch variable value isn’t defined in a case statement.

I’m an iteration junkie and it’s one of my favorite parts of programming. There are many forms of iteration and here are a couple of them.

For Loop
The most common form of iteration. This java for loop will iterate over 6 loops. On each loop, i will be incremented by one and sent to standard out. Sample out put will be 0, 1, 2, 3, 4, and finally 5.

for(int i = 0; i <= 5; i++)
System.out.println(i);

For Each Loop
For each loops iterate through the contents of an array. This C# for loop will iterate through the drives of the host machine.

Generators
I mostly work with generator functions in python and they are the bee’s knees of iteration. They work like a for each loop but you can control how they yield data. Anyway, keep in mind that that generators are data pushers. This python example is own of David Beazley’s creations. This code creates a generator function that walks through a directory.

Coroutines
I’m not sure if coroutines should be under the iteration, they work similar to iteration but in reverse. As I mention above, generators are data pushers and coroutines are data pullers. This python snippet is another one of David Beazley’s creations and will code a grep function using coroutines.

def coroutine(func):
#- Decorator function to supports coroutines.
#- Coroutines functions are a little strange in python and require to have next or send called on them.
#- This function is the example provided by David Beazley
def start(*args,**kwargs):
cr = func(*args,**kwargs)
cr.__next__() # You can also use send to advance a coroutine
return(cr)
return(start)
@coroutine
def grep(pattern):
#- This is where the magic happens.
try:
while True:
line = (yield) # This is where the pattern string is passed in.
if pattern in line: # Checking if pattern is in the current line
print(line) # Prints the whole line if found
except GeneratorExit:
print("Closing the coroutine.")
if __name__ == '__main__':
g = grep("Bueller") # This is where you pass in the pattern
# - Sending in non-Bueller strings
g.send("Whats the score?\n") # Dev Note: \n = new line
g.send("Nothing and Nothing.\n")
g.send("Who's winning?\n")
g.send("The Bears.\n")
#- Sending in a Bueller string
g.send("Random quotes from Ferris Bueller's Day Off are fun!\n")
g.close() # Closes the coroutine and causes the code stored in the GeneratorExit exception to execute

List Comprehension
List comprehension is a pretty cool way to solve problems. I only really see this form of iteration in python and erlang. This example will create a list of binary base digits.

Lambda expressions and functions can be pretty cool to play around with. They can let you make some really elegant one liners. With lambda you can even pass a function as an argument. This is a dumb example. I reworked my baseDigits in a different way completely different way. One thing I will say about this version is that I made it with using a map. I haven’t really made many maps in python but they seem kinda sucky too me.

The counter case may or may not be the best example. If you run it yourself it, the code will try to run in an infinite loop. Here is another common recursive function that you might be familiar with. This code is an inefficient Fibonacci sequence function.

Poorly written counters and Fibonacci numbers aren’t that interesting, so lets make a fractal with recession. This code snippet is part of a basic JApplet I wrote one night that will make a triangle inside a triangle, or Sierpinski triangle if you want to sound smart. All that this one does is draws a line between the midpoints of a triangle. I also did a blog a post about it you want to see the full to code.

I’ve also made a better version of this program written in JavaScript while playing around with the HTML canvas. The code is kinda scattared across multiply posts but it should be to hard to find them since I haven’t publish much JavaScript code here.

You’ll probably be using exception handling pretty often. Since the idea of bug free software doesn’t exists, you’re left trying to code in a fault tolerance way. The most common form of exception handling is try/catch/finally statements. The pythons case, the catch is called except. This example attempts to add two variables. If we call foo(2,3) the number 5 will be returned. Likewise, if we call foo(2, “ASDF”) will return False. Also the finally statement will print a string when the function is about to close.

Threads are an aspect of concurrent programming in many languages, expect for maybe Python. Threads are just resides within a process and they can share resources between other treads. Likewise you can really share resources between processes. Python is singled thread for the time being and they’re attempt around threads is to throw process. You can do some really neat things with coroutines if you try to make python concurrent.

http://en.wikipedia.org/wiki/Thread_(computing)
Here is some poorly written Java that shows the down side of threads. If you try using multi-threading with the Deadlock class the program will lock up. I also did a blog post on this one if you want to how to make a thread safe program.