Commentary on science, math, education, and aerospace.
Introduction to Programming, Part II
Tags programming
--- Continued from Part I---
Flow Control
If a program could only go from one step to the next, it wouldn't be of much use. Luckily, there are constructs that allow us to change the way the program flows. These include loops, conditionals, and switches.
Loops
A loop is a programming constant that repeats a block of code if a condition is met.
Loops allow us to repeat code in certain cases. Their are two main kinds of loops, the while loop, and the for loop.
While loops
A while loop is a loop that checks if a condition is met. If the condition is met, it evaluates the block of code until the condition is not met.
A while loop requires a condition. For example, a while loop might check if the value of a variable is less than ten before stopping. The following example of a while loop counts the integers from 0 to 9:
The code starts by setting the value of i to zero. It then checks if i is less than 10, and proceeds to evaluate the code, displaying i to the screen and incrementing its value by one. It repeats this process until i equals ten.
If the condition for a while loop is set to a number greater than 0 or to True, the loop will never end. This is called an infinite loop.
For Loops
A for loop is a special case of while loop that iterates over a set of values. Usually, a for loop checks the value of a counter and increments it after each loop. It repeats until the value of the counter reaches an upper bound.
The following for loop is equivalent to the while loop above:
Many languages implement for loops differently. For example, in the C programming language, a for loop is written as:
For loops are useful for iterating over data, or evaluating a block of code for a set number of repetitions.
Conditionals
A conditional is a statement that evaluates an expression. If the expression meets a certain condition, it evaluates a block of code. Otherwise, it evaluates another block of code or does nothing.
The classic conditional is the if-else if-else block. These blocks often look as follows:
In this case, a the value of a variable x is compared to some value a. If x is equal to a, the code underneath the if statement is evaluated. If x is less than a, another block of code is evaluated. If x is greater than a, the "else" case, another block is evaluated. If statements are very useful for structuring code. Note that if statements do not require else if or else statements.
Switches
A switch is a type of control flow that gets the value of an expression. It then compares the value to values defined in cases. If the value of the switch matches the value of a case, the block of code in the case is evaluated.
Switches are useful when numerous actions can be taken based on the outcome of an expression. Switches can replace long if-else if-...-else blocks. Switches are not found in all programing languages, but are usually in the form:
In this example, the switch gets the value of the expression a. If it is equal to the value of b, it evaluates the code under case b. If the value of a equals the value of c, the code under case c is evaluated. Otherwise, the block does nothing.
Functions
A function is a block of code that can be called. A function can be thought of as a mini program. Functions can take inputs and return outputs.
Functions are key to programming. Functions allow you to write a single block of code and then call it from elsewhere in the program. This avoids having to copy and paste blocks of code when reuse is necessary. An example of a function that solves a quadratic polynomial follows.
This example is a good deal more complicated than those previous. The code defines the quadratic() function of three variables, a, b, c, the coefficients of a quadratic equation ax2+bx+c=0. It then returns the roots of the equation. To call the function for the parabola x2-3x+2, you would type quadratic(1,-3,2). The function would then return (that is, give back a value as an output) the solutions, x={1,2}.
Documenting Code
One good habit to learn while writing any sort of code is to document it well. Having good documentation makes it easier for people unfamiliar with your code to follow the logic, and can help you remember how the program works. Extremely obvious constants are unnecessary, but describing methods and functions make it easier to effectively utilize the program. As an example, consider the previous code snippet, the quadratic() function. Here is the code with comments:
As you can see, it makes the program easier to follow. The preceding example was rather heavily commented; in practice such a large amount of comments is unnecessary. Usually, a couple of sentences describing the function would suffice.
Conclusion
We covered variables, data types, operators, program flow control, functions, and commenting/documentation. While this tutorial is by no means complete, it should provided a minimum level of knowledge about programming to provide a conceptual basis for learning how to program. While it is often frustrating while learning, programming is a useful skill and can be quite fun. I recommend trying to learn on a language such as Python, which was used for many of the examples in this paper. (Examples were written in Python and C). Python is available free at www.python.org; MIT has a series of podcasts on learning programming using Python ("6.00 Introduction to Computer Science and Programming") available here.
Flow Control
If a program could only go from one step to the next, it wouldn't be of much use. Luckily, there are constructs that allow us to change the way the program flows. These include loops, conditionals, and switches.
Loops
A loop is a programming constant that repeats a block of code if a condition is met.
Loops allow us to repeat code in certain cases. Their are two main kinds of loops, the while loop, and the for loop.
While loops
A while loop is a loop that checks if a condition is met. If the condition is met, it evaluates the block of code until the condition is not met.
A while loop requires a condition. For example, a while loop might check if the value of a variable is less than ten before stopping. The following example of a while loop counts the integers from 0 to 9:
Code:
i = 0
while i < 10:
print i
i = i + 1
If the condition for a while loop is set to a number greater than 0 or to True, the loop will never end. This is called an infinite loop.
For Loops
A for loop is a special case of while loop that iterates over a set of values. Usually, a for loop checks the value of a counter and increments it after each loop. It repeats until the value of the counter reaches an upper bound.
The following for loop is equivalent to the while loop above:
Code:
for i in range(0,10):
print i
Code:
for (i = 0; i < 10; i++) {
// do stuff
}
Conditionals
A conditional is a statement that evaluates an expression. If the expression meets a certain condition, it evaluates a block of code. Otherwise, it evaluates another block of code or does nothing.
The classic conditional is the if-else if-else block. These blocks often look as follows:
Code:
if (x = a)
// do something
else if (x < a)
// do something else
else
// do something else
Switches
A switch is a type of control flow that gets the value of an expression. It then compares the value to values defined in cases. If the value of the switch matches the value of a case, the block of code in the case is evaluated.
Switches are useful when numerous actions can be taken based on the outcome of an expression. Switches can replace long if-else if-...-else blocks. Switches are not found in all programing languages, but are usually in the form:
Code:
switch (a) {
case b:
// do something
case c:
// do something else
}
Functions
A function is a block of code that can be called. A function can be thought of as a mini program. Functions can take inputs and return outputs.
Functions are key to programming. Functions allow you to write a single block of code and then call it from elsewhere in the program. This avoids having to copy and paste blocks of code when reuse is necessary. An example of a function that solves a quadratic polynomial follows.
Code:
from math import sqrt
def quadratic(a, b, c):
d = b**2 - 4*a*c
if d > 0:
x1 = (-b + sqrt(d))/2.0/a
x2 = (-b - sqrt(d))/2.0/a
return x1, x2
elif d == 0:
x = (-b + sqrt(d))/2.0/a
return x
else:
print('Nonreal answer.')
Documenting Code
One good habit to learn while writing any sort of code is to document it well. Having good documentation makes it easier for people unfamiliar with your code to follow the logic, and can help you remember how the program works. Extremely obvious constants are unnecessary, but describing methods and functions make it easier to effectively utilize the program. As an example, consider the previous code snippet, the quadratic() function. Here is the code with comments:
Code:
# get the square root function from another file
from math import sqrt
def quadratic(a, b, c):
'''Returns the solution to an quadratic equation
of the form ax**2+b*x=c'''
# calculate the discriminant
d = b**2 - 4*a*c
# if the discriminant is greater than zero,
# there will be two roots.
if d > 0:
# calculate both roots
x1 = (-b + sqrt(d))/2.0/a
x2 = (-b - sqrt(d))/2.0/a
# return both roots
return x1, x2
# otherwise, if the discriminant is zero
# there is exactly one real root.
elif d == 0:
# calculate and return the root
x = (-b + sqrt(d))/2.0/a
return x
# otherwise, if the discriminant is less than
# zero, there are no real roots.
else:
# display a message telling the user that
# there are no real roots.
print('Non-real answer.')
Conclusion
We covered variables, data types, operators, program flow control, functions, and commenting/documentation. While this tutorial is by no means complete, it should provided a minimum level of knowledge about programming to provide a conceptual basis for learning how to program. While it is often frustrating while learning, programming is a useful skill and can be quite fun. I recommend trying to learn on a language such as Python, which was used for many of the examples in this paper. (Examples were written in Python and C). Python is available free at www.python.org; MIT has a series of podcasts on learning programming using Python ("6.00 Introduction to Computer Science and Programming") available here.
Total Comments 4
Comments
-
Posted Mar28-11 at 09:30 AM by micromass
-
Posted Mar30-11 at 10:19 PM by jhae2.718
-
Posted Mar31-11 at 11:28 AM by micromass
-
I am learning C++ too...
It's so hard that for me to learn this subject...Posted Apr5-11 at 09:44 PM by Julian2011


), so that's why I don't include any OOP stuff.
