Subscribe to Penguin-man the computer guy

Monday, May 13, 2013

Understanding the Logic of Looping Structures

One of the subjects that gets taught very early in computer programming is the idea of a Logical loop. Unfortunately, it seems that some people find it difficult to see that looping structures are a very important part of understanding the universe, and in this post, we will try to examine the how and why of looping structures in order to see if we can understand them not just as a method of controlling logic flow in a coded program, but as a way of understanding language, behaviors, neurological processes, etc. I hate to be grandiose and pretend that this is an all important concept, but this in fact is a quite profound idea.

Our first question will be a simple one: What is a logic loop? I think that showing this by some kind of pseudo code is the easiest way to begin. Don't worry if you find this a difficult idea at first... we will attempt to break it down.

while (some_condition = true )
{
     // some action is done.
}

This code snippet (which uses C/C++ syntax) shows that the condition in the parenthesis governs if, and how many times, the statements inside the brackets are done. Before executing the code inside the brackets the very first time, a while loop checks that the condition is true. If the condition is true, then the code between the brackets is executed. When the last statement of code between the brackets is executed, the condition is checked again. If the statement is true, the code continues to be executed starting once again with the first line of code between the brackets. If the condition is not true, the loop is exited. To continue this thought, lets look at two loops where we specify the conditions of the code. Once again, this snippet of pseudo code will uses C/C++ like syntax, however it will not compile. We are using pseudo code for logical clarity, not  real code. We are also not going to specify a data type for our variables, and will be using line numbers so we can follow the ideas in more clarity.

1       x = 5;
2
3       while( x > 0 )
4       {
5           print "Hello John";
6           x = x -1;
7       }

8   
9       // next line of code

Here in this example we first create a variable, 'x', in line 1, and then set it equal to five. We then use the  variable 'x' as the condition of the loop. Remember the syntax for the while statement:

1      while (some_condition = true )

In our example above, the third line is while( x > 0 ). We see that the condition ( x > 0 ) must equal true. If x <= 0, the condition is not true. But, because x = 5 and 5 > 0, then the condition evaluates to true. The loop executes until the condition is false. To see how to control amount of times the loop executes, consider how the below code will work:

1       while( 1 = 1 )
2       {
3           print "Hello John";
4       }

5   
6       // next line of code

I think the above is obvious... 1 will always equal one no matter what so this is an INFINITE loop... it will loop as a long as the program is running. Remember that an infinite loop could also take this form:

1       x = 5;
2
3       while( x > 0 )
4       {
5           print "Hello John";
6       }
7       

8       // next line of code

Do you notice what is missing that would control this statement? The expression to increment the variable 'x'. This expression is found on line 6 of the original code and is ( x = x - 1; ). Here we see that for every loop, the variable x becomes one less than its initial value. (Note, the syntax of C++ allows a shorthand version of the statement  x = x - 1 to be written x = x--;. The name C++ comes because the x = x-- is the decremented form and x = x++; is the increment form).

The website http://www.cplusplus.com/ has some great resources in there tutorials describing control structures in depth. I recommend the following page if you want to better understand the specific syntax for loops in C/C++ http://www.cplusplus.com/doc/tutorial/control/. There are three kinds of loops; while loops, the do-while loop, and the for-loop. Similar control structures are if statements, if-else statements, and switch statements. Below is the basic syntax we showed before for a while loop:

1       x = 5;
2
3       while( x > 0 )
4       {
5           print "Hello John";
6           x = x - 1;
7       }

8       // next line of code

This is the basic syntax for a do-while loop:

1       x = 5;
2
3       do
4       {
5           print "Hello John";
6           x = x - 1;  
7       

8        }while( x > 0 );
9       
10      // next line of code

And finally, is the basic syntax for a for loop:

1       for(  x = 5;  x > 0;  x = x - 1)
2       {
3           print "Hello John";
4       }

5       // next line of code

Notice how the for-loop takes all the statements that control the loop and places them in the same line. While this is more complex to learn, it is ultimately less lines of code and more elegant.

What do we use Loops for?

Why do we need loops? What are they used for? Well, when we program, we are emulating reality, and that is where the value of loops is found. Lets take my favorite example that can be expressed either as code or in a sentence. In a sentence "while I pull Sally's hair, Sally will scream." Below the same in code form.


1       while( I pull Sally's hair )
2       {
3           Sally screams;
4       }


This is similar to the statement "while the car has gas and the engine is turned on, the cars engine will run. Here again, there is a condition ("while the car has gas and the engine is turned on") and a result ("the cars engine will run"). Note though that the condition has an and... this makes a more interesting loop structure. Note that && is the computer code way of expression a logical and.


1       while( ( car has gas ) && (the engine is turned on) )
2       {
3           The engine will keep running;
4       }



Here we see that we have two statements separated by an and. Remember the truth table for an and statement of two variables which we will call p and q in respect to convention:

       p   &   q    Truth value

       T         T            T
       T         F            F
       F         T            F
       F         F            F

This table shows us why a logical and is so special. Only in one case, both premises are true, is the statement true. Thus, when a while statement contains an a logical AND, the statement is quite narrowly defined. Less narrowly defined is the or statement:


       p   OR   q    Truth value

       T           T            T
       T           F            T
       F           T            T
       F           F            F

In a logical or, the statement is true unless both premises are false. That means the difference between an or statement verses an and statement is huge.

Conclusion

In conclusion, we need to look at the ways in which we may encounter loops. In reality we see loops all the time. Consider the following:

"While it is cold, I wear a jacket."

In the above, identify that the action, "I wear a jacket", will be terminated when the condition, "while it is cold", is negated. In logic, a ~ is the symbol used to show negation. So,

 ~(action) --> ~(condition)  which could also be written   NOT(action) --> NOT(condition)               

This means that we can expect that if I am not wearing a jacket, then the weather is NOT cold. This is a simple, but valuable insight. Also note that the use of a while here is appropriate, as I repeatedly don my jacket as long as the weather is cold.

Ultimately, anytime we see a process frequently occurs in reality, then we can expect to see it equally frequently in code. In fact, when coding, anytime a task needs repetition until some condition is either met, or not met, the logic of that task is a loop. This makes understanding loops of primary importance to both programmers and philosophers.

3 comments:

  1. Calvin,
    I take one exception to your thoughts. Your loop theorem cannot apply to philosophy, for it is far too simplistic of a system, to only look at one variable. The loop you have described is an "If, and only if, then" loop. If it is cold, I will wear a jacket...that only looks at one variable, and even that variable could be incorrect. Peoples in very hot climates wear garb to block the sunlight, essentially creating their own shade. This garb is, for all intents and purposes, a long, light jacket. Also, I, like many others, will wear a jacket in warm weather in cases of inclement weather, whether that be rain or a dust storm kicked up by a haboob.

    Just my thoughts my friend.

    J W Huettl

    ReplyDelete
  2. Interesting post, Penguin Man. A couple of thoughts come to mind, especially in terms of cognitive and behavioral science.

    First, it’s interesting to see programming loops related to logical conjunction- implication in terms of truth tables. For my Master’s thesis, I used truth tables to look for variable conjunctions that correlated to a particular outcome—assumed to be an implication of the combined variables, which are thereby assumed causal. My approach was informed by Mill’s method of induction, which is not without problems because no number of observations of the conditions leading to an outcome guarantee the outcome or that the observed conditions are causal (which, I’m sure you know as the problem of induction). Part of the problem is that we can’t ascertain all the variables within a complex system; another part of the problem is that we’re forced to assume uniformity to nature but cannot guarantee it. The uncertainty of nature leaves us confounded…this must be the beauty of programming (not to say that programming is without uncertainty).

    I also see a strong analogy between the programming loop and the theory of cognitive heuristics. The theory argues that decision making is cognitively taxing and therefore we rely on conditioned rules unless we’re sufficiently motivated to systematically work out the problem. Early accounts of cognitive heuristics treated them as fallacious thinking…but a growing perspective in social psychology is that they’re essential to functioning because it is too taxing otherwise and that they generally serve their purpose in leading to self-preserving or adaptive decisions.

    ReplyDelete
  3. Jason... I appreciate your perspective and your ideas. You no doubt are a deeper philosopher than myself. I ask however why you would require that a complex problem have a complex solution. This seems a fallacy. If one put several loops within each other (as is common in programming) and could only view the external, to see the simple loop structures would be quite an insightful thing. I am disposed to believe that many very simple units working together and interacting are a better description of complex systems than some single complex entity. The brain in fact fits this parallel simplicity that gives boundless complexity model.

    ReplyDelete