Tuesday, September 21, 2010

Rock, Paper, Scissors, Pythons....?

Here's assignment for Logic turned Python. We were to describe the logic for an easy childhood game and I chose Rock, Paper, Scissors.


import random
choices = ['Rock','Paper','Scissors']
oppChoice=0
playerChoice=0

def rock(oppChoice):
    if oppChoice == 'Rock':
            print("It's a tie!")
    if oppChoice == 'Paper':
            print("You Lose! Paper covers Rock!")
    if oppChoice == 'Scissors':
            print("You Win! Rock smashes Scissors!")
          
def paper(oppChoice):
    if oppChoice == 'Paper':
            print("It's a tie!")
    if oppChoice == 'Rock':
            print("You Win! Paper covers Rock!")
    if oppChoice == 'Scissors':
            print("You Lose! Scissors cuts Paper!")
           
def scissors(oppChoice):
    if oppChoice == 'Scissors':
            print("It's a tie!")
    if oppChoice == 'Paper':
            print("You lose! Paper covers Rock!")
    if oppChoice == 'Rock':
            print("You Lose! Rock smashes Scissors!")
           
def choice(playerChoice,oppChoice):
    if playerChoice==1:
        rock(oppChoice)
    if playerChoice==2:
        paper(oppChoice)
    if playerChoice==3:
        scissors(oppChoice)
   
def RPSgame():
    oppChoice = random.choice(choices)
    playerChoice = input("Make your selection:\n[1] Rock\n[2] Paper\n[3] Scissors\n...")
    playerChoice=int(playerChoice)
    if playerChoice not in(1,2,3):
        print("Please input 1, 2, or 3 only!")
        RPSgame()
    print('You Chose', choices[playerChoice-1])
    print('Your Opponent Chose...',oppChoice)
    choice(playerChoice,oppChoice)
    playAgain = input("Try again? (Y,N)")
    if playAgain== 'Y' or 'y':
        RPSgame()
    else: return

The first 44 lines are the game's logic, just telling you if you won or lost based on your choice vs. opponent's choice. The "main" code is RPSgame() which, if you ran this code, is all you would have to type to start the game. I tried to account for incorrect input (not using 1,2, or 3 for initial input and disregard for capitalization for "y" to continue playing). The only thing in here we haven't covered thus far on the GeekSpot Blog is the use of lists. I will go into that more in depth later this week when I have more time. In the mean time, I'll leave it at:

Lists are built in brackets: []
Lists are mutable: They can be changed... added to, taken away from...
List elements are numbered starting from 0: choice[0] thus equals Rock.

There is much more to lists, lists can be used for many things and have much potential in your programming. Thanks for stopping by! If anyone has suggestions, comments or concerns about the above code, please feel free to leave a post or shoot me an email.

Saturday, September 18, 2010

Defining Functions

Functions. What are they?

In math you know a function as f(x)=3x+3. substitute any number for x and you get a value. Typically a function is used to define something, such as the rate of change in speed of a car, or a runner. One variable is time, the other is speed. If you plug the value in for one your can get the other, as long as they follow the rules of the function created to define their motion (which for now we are assuming they do). If you wanted to write that same function in Python, and all you wanted it to do is print out the value, you could write:


>>>def function(x):
    print(4*x+2)

Now every time you want to call the function, you only have to type, say...

>>>function(3)
14

The value x in "def function(x)" replaces the x in the indented lines following the defining statement and your function runs, printing 4 * 3 + 2. But the function doesn't have to take a value.

>>def declaration():
    print("When in the Course of human events.")

Here the function just prints out what the function is. A benefit to functions is that you can modularize your program. You can break it up into it's basic functions which can then be used over and over again, not only in that program but in others as well. If you create a function that asks for a user name, you can use that in any program that requires the user to input their name.

You can also nest functions. Such as...

>>>def repeat(f):
    f()
    f()

This function takes a function name as it's input and outputs that function twice.

>>repeat(declaration)
When in the Course of human events.
When in the Course of human events.

You may have noticed when you typed repeat( ... a helpful box comes up with (f), reminding you that the function takes f as it's value. But this isn't always helpful. You could instead write a docstring, or documentation string, giving more helpful information to remind you and others what to input here. You do this by placing three double quotes before and after as shown.

>>>def repeat(f):
    """Input a function name here"""
    f()
    f()

This is what it should look like. There are many, many uses for functions in programming. We'll be using functions in most, if not all, of the posts from here on out.

Wednesday, September 15, 2010

Random Number Game - Python

In my logic class we were instructed to produce psuedocode for a program that produces a random number 1-10, asks the user to input a number, and outputs both numbers. Here is my version and the python code for it:

Start
Declarations
  int randomNumber = random(10)
  int guess = 0
output "Guess my number! (1-10)"
input guess
while guess != randomNumber
  if guess == randomNumber
    output "Good Job!"
  else
    output "Sorry you're wrong"
    if guess < randomNumber
      output "Guess too Low. Try again."
    else
      output "Guess too High. Try again."
Stop

The nice thing about Python is that it is not much different than psuedocode, we just have to pay attention to the syntax. The only thing new here from previous posts is the random number generator which you will see below.

#Start
import random    # Necessary to call random later
randomNumber=random.randint(1,10)
guess=0
while guess != randomNumber:
    guess=int(input("Pick a number 1-10: "))
    if guess == randomNumber:
        print("Good Job!")
    else:
        print("Sorry you're wrong.")
        if guess < randomNumber:
            print("Guess too low. Try again.")
        else:print("Guess too high. Try again.")
#Stop


I used random.randint(x,y), x and y being low and high values respectively, to generate my number. You could also have used random.randrange(x,y,z) with x as low value, y as high value, and z being step. For example:

>>random.randrange(0,100,10)
80

The above code generates a random number 0 through 100 at steps of 10 (i.e. 10, 20, 30,...). How would you produce the above "game"?

Tuesday, September 14, 2010

Finding the 1000th Prime

I mentioned the other day the homework assignment for MIT OCW Intro to CS course was to find the 1000th square root. Here is a possible solution to the problem:

primeCheck = 5
primeCount = 3
while primeCount <= 1000:
    for divisor in range(2, primeCheck//2+1):
        remainder = primeCheck % divisor
        if remainder == 0:
            break
    else:
        primeCount += 1
    primeCheck += 1
print(primeCheck - 1)

*Note - Thanks go out to Nallo who helped make my original code with clarity.

You can see we've got a few new things here. The while loop on line 3, the for loop in line 4, and a few new uses for our operators. I started explaining everything new here and it became a fairly long explanation I split into two other posts so if you want the explanation you can go there and if you just wanted to see the code you can stop here. We could also have changed 1000 to variable and inserted >>>variable = input("What prime number do you want") in the front to make this code find just about any prime.
The result is 7919 which you can also see here: List of 1000 Primes

Related posts:
Finding the 1000th Prime: Explanation
While Loops
Declaring Variables with Python
Order of Operations

Finding the 1000th Prime: Explanation

This is the explanation for the code for 1000th prime.
Here's the code again:

primeCheck = 5
primeCount = 3
while primeCount <= 1000:
    for divisor in range(2, primeCheck//2+1):
        remainder = primeCheck % divisor
        if remainder == 0:
            break
    else:
        primeCount += 1
    primeCheck += 1
print(primeCheck - 1)


I started our prime checker with 5 which is the 3rd prime. This is why the variable primeCount is 3, as it is checking for the 3rd prime. If 5 passes the test (which it does) the count will go to 4 and it will search for the fourth one. I'm using the while loop to continually repeat everything below and indented right of the while. The test for primality I have used is checking to see what the remainder is when applying the modulo operator to the possible prime and numbers 2 through half of the possible prime. It is not necessary to go further than this since all numbers above are inherently tested by testing the numbers below half.

The while loop was explained here, so I will move on to the for loop. The for loop is used when you know when you want your loop to end. We have a starting point (here it is 2) and an end (primeCheck//2+1). There are many ways to use a for loop, and the nice thing about it is you do not have to specify a counter (a variable that continually increases with each repetition of the loop, our while loop uses primeCount as the counter), it goes to the end and repeats until the end value is met.


Our end value to our for loop is primeCheck//2+1, which takes the number we are checking, 5 for instance, and does integer division on it ( // ), which gives us 2 rather than 2.5 if we used /. (Unless you are using pre-Python3 which divides based on your type and would also give two unless we changed a value to float).

Our next line is remainder = primeCheck % divisor, which performs modulo division on primeCheck by divisor. What is the modulo operator? The modulo operator is the % sign and it gives you the remainder after division of any two numbers. Here's a few examples to help you understand:

>>>4%2
0

This is because 4/2=2 with no remainder.

>>>5%2
1

Because 5/2=2 with a remainder of 1.
This is why it makes sense to use it in our test, because a prime should not be divisible by a whole number integer evenly. If it does (if x==0) then the number is not prime and break is called which stops the loop there and starts again at the next value. The first 0 remainder we find is proof enough that that number is not a prime.


And that's as simple as it is, our for loop is nested within our while loop, every time the for loop finds another prime the counter for primes goes up and when it meets our requirement of 1000 it stops and prints the value. The reason for the -1 at the end would be because even after if finds the 1000th prime it finishes with the primeCheck+=1 which we have to negate at the end.


1000th Prime = 7919


Here is a list of the first 1000 primes if you want extra validation.
See more interesting Python below:




Sunday, September 12, 2010

The While Loop in Python

The while loop says that while one thing is true, do something. Here we can count to ten:

counter=0
while counter < 11:
 print(counter)
 counter=counter+1

What did we do here? First we initilized counter as 0, this is where our counter is starting. It is important to initialize the variable you are using in your while loop outside of the loop. After we have initialized counter to 0 we say: While the value of counter is less than 11, do something. In our case, do something is print(counter), which the first time through would be 0, and then we set counter equal to itself plus one.

Our loop will now continue with counter as 1 print one and add 1 to itself. When counter is equal to 10, it goes through one last time, prints 10 adds one to 11 and then passes through the while test again. This time it is not less than 11, because it equals 11 and so it stops. Your output should be:

0
1
2
3
4
5
6
7
8
9
10

We can say this same thing but, in my opinion, make it look nicer. We can do this by making use of multiple operators. The first example will be in line 2, instead of < 11, we can use <=10, which is less than or equal to. A list of such comparison operators is:

<=     If left operand is less than or equal to right operand, condition is true.
>=     If left operand is greater than or equal to right operand, condition is true
==     If left operand is equal to right operand, condition is true.
!=      If left operand is not equal to right operand, condition is true.

Notice the difference between the assignment operator = and the conditional operator ==. The first makes one operand equal another, the other tests the equality of the two operands. 

The second way we can simplify the program is by using the compound assignment operator +=. In line 4, where we say counter=counter+1, the same thing could be said with the expression, counter+=1. This takes the value of counter, adds one and assigns that value to counter. You can see how this be of use. Here are some more compound assignment operators:

+=  Adds left and right operand and assigns total to left operand
-= Subracts right from left operand and assigns total to left operand

*=Multiplies left and right operand and assigns total to left operand
/= Divides right from left operand and assigns total to left operand
**= Takes left operand to the power of the right operand and assigns total to left operand
%= Finds remainder of division between left operand and right operand, and assigns total to left operand.
//= Performs integer division between left and right operand and assigns total to left operand.

Our "improved" code would now be:


counter=0
while counter <= 10:
 print(counter)
 counter+=1

Saturday, September 11, 2010

Order of Operations and Naming Conventions

Order of Operations
Yesterday we went over operators and operands. Today I'd like to go over Order of Operations. When you were going through elementary or middle school math you may have learned a similar way to remember it and mathematical order of operations is the same here. I learned it as, Please Excuse My Dear Aunt Sally, or Parenthesis, Exponents, Multiplication/Division (both have the same precedence), Addition/Subtraction (so do they). You can also remember, as offered by Thinking Like a Computer Scientist, the acronym PEMDAS. I like mnemonics so the former works better for me. I made it a point to list them in order in the last post.

Here are a few examples. Try to figure out what the results should be. You can also test it (and me) by putting the operation into the Python Shell to see for yourself what it comes out to.

8*1**4 = ?
3-6/3 = ?
(8*2)**4 = ?
12*2/4+4-2 = ?

The first example comes out to... 8! Because 1 exponent 4 is still one, times 8 is still 8. The second example is 1, because we first divide 6 by 3 then subtract the result from 3. Making sense? This next one is the same as the first one but notice the parenthesis. This will now do the parenthesis first, giving us 16 and taking 16 to the exponent 4 which gives us 65536. For the last one we have multiple operations with the same precedence. How will Python evaluate it? The same as you would read it, left to right. It would take 12*2 to get 24, 24/4 to get 6, 6+4 to get 10, and 10-2 to get 8.

We've also gone over variables, but not the naming conventions of them. There are some rules, and there are some style suggestions. Some rules are:

  1. Variable names cannot begin with a number.
  2. All numbers are legal (Just not to begin the variable name)
  3. Variable names cannot contain the character $.
  4. Variable names cannot be a keyword (see list below)
  5. Multiple variabls cannot share the same name.
  6. Variable names are case sensitive. (i.e. name is separate from Name)
  7. Variable names cannot include a space. 
  8. Variable name must be on the left side of the assignment operator.


False      class      finally    is         return
None       continue   for        lambda     try
True       def        from       nonlocal   while
and        del        global     not        with
as         elif       if         or         yield
assert     else       import     pass
break      except     in         raise 

As for style, there are a few general suggestions. One is to use meaningful names. This helps you when you have to go back to your code later on and interpret it, and it helps others know what is going on. This goes along with leaving comments in your code. Another suggestion is to use _ to break up words in a variable name, such as coffee_made = no. You can also use what is called camel case. Camel case is what I prefer and is when you capitalize the first letter in each word excluding the first and include no spaces, such as coffeeMade = no. According to Wiki, if you capitalize the beginning as well it is known as Pascal case.
Sorry, I like the camel.

Friday, September 10, 2010

Converting Data Types in Python

If you remember so far we have mentioned three types, int, float, and str. For those who don't remember int is integer and is a whole number integer (3 and 91 for example). Float is floating point and has a decimal value (7.2 or even 9.0) and str is string or a string of characters ("Hello, World" is a string). To convert between types Python allows the following:

Convert to integer:
>>>int("29")
29

>>>x=5
>>>int(x)
5

>>>int(3.14159)
3

Convert to float:
>>>float("3.14159")
3.14159

>>>float 5
5.0

Convert to string:
>>>str(3.14159)
'3.14159'

>>>str(42)
'42'

You can also test to see what type you have. You do this by using the type() function call. Here are some examples.

>>>type('42')
<class 'str'>

>>>type(4.2)
<class 'float'>

As the class I am following online is using an older version of Python I'm trying to keep up with the new rules but I may (will) miss some. I started running them on the new one so I can learn it better and hopefully this will fix the discrepancies I've been having. Here is a site that has a lot of the new changes.

Input and Output in Python

Computers have three major operations, the sole reason they exist. These are input, processing, and output. If they computer couldn't do one of these it would become practically useless. You input data with every movement of the mouse and every button pressed on the keyboard. The computer processes that data into something, a movement of the cursor, a character typed, and outputs that data to the screen so you can see where the computer thinks the cursor is and what character you typed on the monitor. So far we have placed our variables and their values within the program itself so the user has no interaction with it. They click, it runs. Now let's try building an interactive program.

If you checked out the MIT OCW Introduction to Computer Science and Programming course you may have seen the first homework assignment was to create a program with the following requirements:

Problem 1.
Write a program that does the following in order:
1. Asks the user to enter his/her last name.
2. Asks the user to enter his/her first name.
3. Prints out the user’s first and last names in that order.

Before we start writing code, we can create pseudocode.

Start
input lastName
input firstName
output firstName lastName.
Stop

This would do the job, but how does the user know which name to put first or that you want them to enter a name at all? You can ask them, with:

Start
output "What is your Last Name? "
input lastName
output "What is your First Name? "
input firstName
output firstName lastName
Stop

This is better, but I think we can do even better. Here is the Flowchart and Psuedocode for a simple answer to that problem.




Start
output "What is your Last Name? "
input lastName
output "What is your First Name? "
input firstName
output "Is your name " firstName lastName ?
Stop






And finally in Python:

##This program asks for Last Name, then First Name and then gives
##First and Last name in that order.
lastName = input("What is your Last Name?")
firstName = input("What is your First Name?")
print("Is your name" , firstName , lastName ,"?")

*Note - Apparently raw_input() has been disabled for Python V3.0 (I have updated my code to reflect this). 

**Edit** Thanks to bernd-petersohn. Here is his Python3 code:

#!/usr/bin/python3
lastName = input("What is your Last Name? ")
firstName = input("What is your First Name? ")
print("Is your name {0} {1}?".format(firstName, lastName))

We still do not act on our data or have decisions, but you can input some data, the data is saved into variables, and the data is then output for your viewing pleasure. His next assignment gets much more difficult and I'll pose the question to you now to think on it... How would you design a program that finds and outputs the 1000th prime number?

Operators, Operands, and Hello, World!

Good morning! I couldn't sleep so I'm going through my Python tutorial before work. This morning we'll talk about manipulating variables. We used operators and operands yesterday, but I did not explain them. Operators are symbols, like + and - that manipulate data. The data being manipulated is the operand. So in the statement:

>>>x*3

We are multiplying the variable x (The value of a variable is substituted prior to evaluation by the computer) by 3. 3 and x are operands and * is the operator.  You can remember this easily by remember the operator of a piece of machinery is the person doing the work. In this case the * is doing the work on the two operands. The following are legal operators:

** = exponent/power
* = Multiply
 / = Divide
+ = Plus
 - = Minus

Another operator we have used already is the assignment operator or =. Using = assigns the value on the right to the variable on the left. It is similar but different from the equals sign which we will go over later. First let's remember the different types we have gone over (int, float) and let's add another one 'str.' Str, or string, types are strings of characters such as "Hello, World." The "Hello, World" program is a popular first program and so we can use it today to create our first saved program while learning about strings.

First open IDLE (Python GUI). Select File>New Window. A new window with a text editor pops up and here we can write our program.

##This is a Hello, World! program.
##It prints "Hello, World!" on the screen.
print "Hello, World!"

*Note - Remember the # is the comment designator and is not necessary, but a tip for later when writing longer more complex programs is to always include good notes in your program. You can include these comments for your own benefit, put comments of your own or simply start with print. 

Select File>Save>> HelloWorld.py (or any name followed by the .py extension) >Save. Now, let's run our program! Do this by selecting Run>Run Module, or pressing F5. If you have made changes it will let you know you need to save it to run it. When you click Run Module a Python Shell will pop up if you didn't have one up already and you should see this:
Hello, World!
 
You now have a program you can run over and over again as long as you want! It doesn't do a whole lot, but it's all yours. Hope everyone has a great Friday!

Thursday, September 9, 2010

Declaring Variables w/ Python

Hello again! It's Thursday, which is one of my favorite days, if only because it means Friday is almost here! I'd like to end my Thursday with a lesson on variables. Before we get started however I thought it would be a good learning experience, for myself and perhaps others, to do my logic work in psedocode, and actual code (and perhaps a flowchart). For the "real code" I'm going to use Python.

There are a few really good links for help on Python programming. One is from the Python website itself here. As well as from the Introduction to Computer Science and Programming course on MIT's OpenCourseWare (OCW) website. The MIT OCW website has many classes and programs you can go through free of charge and look very interesting. Harvard also has a similar setup here and it looks like they use C whereas MIT is using Python in instruction.  

If you want to follow along with me you should go to the Python website and download version 2.7 If you prefer to use 3.0 that's fine but 2.7 is backward and forward compatible whereas 3.0 has gotten rid of some things that I may be using since I'm following the MIT OCW course, recorded in 2008.

Once you've installed Python, bring up the Python Shell also called IDLE (Python GUI) which should look like this:
IDLE (Python GUI) / Python Shell
From here you can input all the commands which I will preface with >>> to look the same as the Python Shell.

Now, onto the lesson: Variables are memory locations, the contents of which may vary throughout the program. For example:

          >>>numberOne = 1 #Hit Return

*Note - # is Python for comment. Meaning, typing it would not hurt, but does nothing for you. I am only letting you know here to hit return to enter 1 as the value for numberOne.

This sets a memory location, nicknamed "numberOne" to the value of 1. To write this in pseudocode you can write it the same "numberOne = 1" since this is a simple statement, or to be more clear:

          set numberOne = 1

Remember I said variables can change. We can now type in the Shell:

          >>>numberOne = numberOne + 1

This may look weird, but it should be simple enough to see what is happening. We are taking numberOne and setting it equal to numberOne + 1, or just adding one to it. If you type:

          >>>print numberOne

You should now get the result: 2.

The last thing I want to mention briefly is the data type of this number:

2

The number 2 is an integer or int, and has no decimal value. In Python, and most other programming languages, this is important. The type is decided when you initialized the variable. To make this make sense try typing 7/2 into the Python Shell and hit return. Notice the answer is not 3.5 but 3! An integer has no decimal value, and your attempt at dividing, which would create a decimal is ignored and it throws out the remainder.

If you are writing a program that requires the decimal values, you can use what is called a floating point or float. To make it a float, just type 7.0 (the .0 part making it float) and divide that by 2. What do you see? 3.5!

Be careful when writing your programs that you keep track of this. There are ways in many programming languages to change the type, but doing so unnecessarily can cause leaks and bugs in your program.

Lastly, a neat trick to see the remainder of the integer division is by using the % sign. Using % divides one side by the other and gives the remainder.

          >>>7%2
          1

Tomorrow I'll try and post something a little more... interesting to program. Until then enjoy the tutorials and let me know what you think!

Wednesday, September 8, 2010

Integrated Development Envioronments

When you're first getting into programming you may hear the term integrated development environment (IDE) and wonder: What is it? and Do I need one?

An IDE is a common toolsuite for programming combining all the necessary tools (editor, compiler, and other programming tools)into one. Many will now help you with your programming guessing at what you are going to type and helping you complete it. Microsoft Visual Studio and Eclipse (Along with a whole lot of others) are popular IDEs that support multiple languages.

Some beginning programming books have you learn programming from a text editor, save the file, put it through a compiler (in a command window) and then run your program (as well in the command window). With the IDE all of that can be done with the click of a button. This makes it much easier to debug and test changes in your program.

If you want to get started, how about trying the C++ guide (a free download) from Microsoft's Development for Beginners site. and downloading one of these programs:

Visual Studio can be downloaded by language (VisualBasic, C#, or C++) as a free version here.

Eclipse is a free open-source program available here. It is written primarily in Java and is built by the non-profit Eclipse Foundation. Eclipse is also the development environment suggested by Android for programming Android applications. I've tried some basic programming in both Visual Studio and Eclipse and personally I like Eclipse better. What do you guys think?

Tuesday, September 7, 2010

Introduction to Pseudocode

First off, what is pseudocode? It is merely a combination of: pseudo (meaning almost, approaching, or trying to be) and code (the language you are writing in; the set of instructions in a program). It is an informal written representation of your program. In pseudocode you don't need to follow syntax requirements, and really as long as it makes sense to you it doesn't matter how you do it. Here are a few guidelines you can follow however to get the most use out of your pseudocode:

  1. Begin and end your code with terminal statements (i.e. begin,end,start,stop).
  2. Don't use terminal statements if you don't like them.
  3. Use indentation freely to increase readability.
  4. Don't overuse indentation.
  5. Make it make sense to you.
Basically it all boils down to, how do you want to do it? As you learn more about if then, while, do while, statements it becomes more clear what to do. Here is a short example using the same program in my Flowchart introduction.

             start
               input phoneNumber
               call phoneNumber
               if phoneAnswered = no
                 call phoneNumber
               else output "Hello"
             end


Does anyone else have some tips or pointers when using pseudocode?

    Monday, September 6, 2010

    Flowchart

    Flowchart Example
    Here is a simplified example of a flowchart for a program that calls a number for you until someone answers and says "Hello" for you. You'll notice at the beginning and the end there is the racetrack shaped symbol:

    Terminal Symbol


    This is called the terminal symbol and denotes the beginning and end of a program.



    After the terminal symbol you should notice the parallelogram shape:



    Input/Ouput Symbol

    This is the input/ouput symbol. Anytime a new constant or variable needs to be input or output, use this symbol. Here we use it to input phoneNumber and ouput the phrase "Hello".




    Next in the flowchart is the plain rectangle shape:


    Processing Symbol

    Here is the processing symbol. This is where something is done, input is used, and/or data is manipulated. Here we use it to call the input phoneNumber.


    The final shape looks like a diamond:

    Decision Symbol

    The diamond shape denotes the decision symbol. Here the computer checks to see if a statement is true or false and acts on that truth value as you have determined. Here we have said if the phone is not answered then call again. If it is, then the program finishes by saying "Hello" and ending.

    Note: The does not equal could have also been written as !=, <>, or simply "does not equal". This is your preference. Sometimes using does not equal makes it easier to understand what the program, rather than using "= no."

    Note 2: Yes and no can be denoted as 1 and 0 respectively.

    Thursday, September 2, 2010

    Structured Programming

    Structured programming states that any program can be created through the use of three procedures: sequence, selection, and repetition.

    1. Sequence: One thing happens, then another, then another... Get bowl, Place bowl, fill bowl with 1 cup cereal, put 1/4 cup milk in bowl, scoop cereal, eat cereal. To make this work each process must be done in order, else you may be eating your cereal off of the table.

    2. Selection: Selection is the decision portion of your program. If you don't have a bowl in front of you, then grab a bowl. If you have a bowl to put on the table, then put it on the table. If there is no cereal in your bowl, then put cereal in the bowl... by now I'm sure you get the gist.

    3. Repetition: Repetition tells the program to do something again and again as needed (or specified by you, the programmer). At the end you can add a selection, if hungry repeat. You already have a bowl, so the program continues to the next step. The bowl is filled (because you have only taken one bite), you continue until you are either no longer hungry or the bowl is empty, in which case the bowl would refill and you would eat until no longer hungry.

    Anything else you want to do can be done by placing one or more of these within themselves (i.e. nesting statements) but every programming element is a composition of one or more of these three.

    The examples given are not necessarily complete, there are practically an infinite number of steps that could be inserted (breathing between bites, wait time between bites, chewing, swallowing, etc. etc. etc.), but you should have a general understanding of structured programming.