Eight things programming languages do
Part One: Things 1 - 5
When learning computer programming it can be difficult to separate general programming principles from the specific details of one particular language. In some languages the underlying general principles of programming may remain obscured by the sheer volume of information needed just to make a program work. General principles may not emerge until the new programmer has learned two or three other languages.
This article illustrates eight basic programming concepts with examples in five programming languages - Java, Perl, Python, REBOL, and Scheme - which will allow the reader to make comparisons and generalisations. Part one addresses the first five ideas: output, variables, expressions, input, and selection. Part two covers lists, subroutines, and repetition.
The five languages were chosen for no other reason than they happened to be installed and working on my computer when I sat down to write this tripe. I make no claim to expertise in these or any other programming language and I am aware that I have ignored common idioms of the languages in some examples. The five languages are available for all common desktop environments including Windows, Macintosh, and Linux.
For the sake of clarity I have only included the relevant lines of code in the Java examples and omitted the standard header in the REBOL examples. All of the examples, except those for Java are complete programs. The examples are available for download here.
1. Output
The vast majority of computer programs provide some information to the outside world - that is, they produce output. Let’s face it, a program is not very useful if it doesn’t output something. The most common form of output is printing text to the screen (sometimes known as standard output or stdout). This leads us to the simplest computer program in the world - the clichÈd “hello world”, which prints a simple message (e.g. “hello world”) to the standard output.
So this will be our first example in listing 1. The output of all of these programs is the text girt by sea printed to the screen followed by a line feed.
Listing 1.
Java
System.out.println("girt by sea");
Perl
print "girt by sea\n";
Python
print "girt by sea"
REBOL
print "girt by sea"
Scheme
(display "girt by sea\n")
Did you notice that the Perl and Scheme examples include \n at the end of the output? The output commands of the other languages include a line feed in the output automatically, but Perl and Scheme output commands don’t so a line feed must be included explicitly. The character combination \n is recognised as a line feed character and produces a new line in the output.
2. Variables and assignment
In the first example, the string of characters “girt by sea” is referred to as a constant value, meaning that every time the program runs this text will remain constant. Contrast this with a variable. Think of it as a box that can hold a value that can change as the program executes. Give the “box” a label, and whenever that label appears in the program the current value stored in its box will be retrieved and used at that point in the program.
The act of giving a variable a new value is called assignment and it is often represented by the equals sign =.
The next example (listing 2) has the same output as the first, but this time the text girt by sea is assigned to a variable called message, and the value of that variable is printed to standard output.
Listing 2
Java
String message = new String( "girt by sea" );
System.out.println( message );
Perl
$message = "girt by sea\n";
print $message;
Python
message = "girt by sea"
print message
REBOL
message: "girt by sea"
print message
Scheme
(define message "girt by sea\n")
(display message)
For each of the variations on the print message instruction, the output is NOT message it is the value assigned to the variable message: girt by sea In effect, the print instruction is telling the variable “give me your value and I’ll print that”.
Sometimes limitations are placed on the sort of value that can be assigned to a variable. For example look at the assignment statement in the Java example in listing 2, which starts with String message This indicates that for the Java example the variable called message can only accept a string of characters between quotation marks (that is, text). So it is not possible to give message a numeric value (such as your age - but a post code is OK) or perform mathematical operations on it.
3. Expressions
This is a concept borrowed from mathematics - values and/or variables are combined with operators to form an expression. When an expression is evaluated a result is produced. For example, the expression 1 + 2 uses the addition operator (+) on two values (1 and 2), and when evaluated it produces the result 3 In programming, expressions are not limited to mathematical statements. Let’s say we have an operator join that works on strings of characters. The expression “this and ” join “that” uses the join operator on the two string values to produce the result “this and that”
In programming, the result from an expression is a value that can be handled like any other - it can be assigned to a variable or used as part of another expression.
The examples in listing 3 evaluate the expression x times y, where the value in x is 101 and the value in y is 22. The result of the expression is assigned to the variable answer and then the value in answer is printed on the standard output.
Programming languages typically use the symbols * for multiplication and / for division. The characters â—Š and Ëœ aren’t available on an ordinary computer keyboard so it’s a matter of using what’s available.
Listing 3
Java
int x = 101;
int y = 22;
int answer = x * y;
System.out.println( answer );
Perl
$x = 101;
$y = 22;
$answer = $x * $y;
print $answer;
Python
x = 101
y = 22
answer = x * y
print answer
REBOL
x: 101
y: 22
answer: x * y
print answer
Scheme
(define x 101)
(define y 22)
(define answer (* x y))
(display answer)
Again notice that the output of each of these programs is the correct answer: 2222 You will not see anything like x * y or 101 * 22 or even answer This is because variables are replaced by their current values and expressions are fully evaluated.
There is not a typo in the Scheme example: (* x y) is the correct way to represent “multiply x by y” in Scheme.
4. Input
One way to get different values into a variable is to have the human operator provide the values - to capture what the operator types at the keyboard (sometimes called standard input or stdin) and assign this input to a variable.
Listing 4 shows this in action. Each of these programs wait for the operator to type something and press the enter key then whatever was typed is assigned to the my_message variable, which is then printed to the standard output. If, like me, you are of a juvenile inclination this is the chance to get your computer to swear at you…
Listing 4
Java
try {
BufferedReader in =
new BufferedReader(new InputStreamReader(System.in));
String my_message = in.readLine();
System.out.println( my_message );
} catch (IOException e) {}
Perl
$my_message = <STDIN>;
print $my_message;
Python
my_message = raw_input()
print my_message
REBOL
my_message: ask []
print my_message
Scheme
(define my_message (read))
(display my_message)
When these programs run they do absolutely nothing - until the operator types in something (or nothing) and presses the enter key. Notice that Perl is very literal - it assigns <STDIN> (that is, standard input) to the variable.
5. Selection
Unless told otherwise, computer programs execute each of their instructions in order from start to finish. The ability to alter this order is called control of flow. Selection is the first of three features that provide control over the flow of programs. (We will look at the other two - repetition and subroutines - in part two.)
The usual means of selection is to make a true-or-false decision based on a comparison expression. The only values produced by a comparison are true and false (the Boolean values). For example, the expression Is 10 equal to 5 + 5? produces the value true. On the other hand, the expression Is x greater than 0? is only true for values of x that are positive numbers. If x is assigned the value -2, then this comparison produces the result false.
The most common way to make a selection based on a Boolean value is with the IF-THEN-ELSE structure. In human language, it works like this:
IF the statement “x is greater than 0″ is TRUE (that is, the value in x is positive) THEN do the instructions for the positive numbers OTHERWISE do the instructions for the negative numbers
In the interests of brevity, programming languages use the shorter word else rather than otherwise (”else” strikes me as a more unusual word, but it’s a 55% saving in typing effort over “otherwise”!).
The result is that different segments of code are run depending on the true-or-false result of the test condition. Either the “instructions for the positive numbers” are run or the “instructions for the negative numbers” - but never both.
The example in listing 5 combines everything covered so far by simulating a simple password check, as follows: 1. wait for operator input
assign the input to the variable password
compare - is the value in password equal to the secret word “fish”?
if the result of the comparison is true, print the message “OK, you’re in.”
else print the message “Sorry, that’s wrong.”
Listing 5
Java
try {
BufferedReader in =
new BufferedReader(new InputStreamReader(System.in));
String password = in.readLine();
if ( password.equals( "fish" ) ) {
System.out.println( "OK, you're in." );
}
else
{
System.out.println( "Sorry, that's wrong." );
}
} catch (IOException e) {}
Perl
chomp( $password = <STDIN> );
if ( $password eq "fish" ) {
print "OK, you're in\n";
}
else
{
print "Sorry, that's wrong\n";
}
Python
password = raw_input()
if password == "fish":
print "OK, you're in"
else:
print "Sorry, that's wrong"
REBOL
password: ask[]
either password == "fish"
[print "OK, you're in"]
[print "Sorry, that's wrong"]
Scheme
(define password (read))
(if (eqv? password 'fish) (display "OK, you're in\n")
(display "Sorry, that's wrong\n"))
In Java, Perl, and Python the assignment operator is =. Compare this to the “test for equality” operator in Python and REBOL, which is ==. Watch out! They aren’t the same.
It’s interesting to note that REBOL and Scheme dispense with the else instruction, presumably for brevity and simplicity.
And what is chomp in the Perl example? Perl reads every key stroke from the standard input including the enter key, which is recorded as a line feed character. If chomp is not included and the operator types in “fish” the value recorded in password will actually be “fish\n”. When this value is compared to the secret word “fish” it will evaluate to false, so Perl needs to chomp off the trailing \n character, then the comparison evaluates to true.
Five down, three to go
So there we have it; output, variables and assignment, expressions, input, and selection in Java, Perl, Python, REBOL, and Scheme. Hopefully you can see that there are common principles at work here and the differences are only in the “grammar” of the languages. To summarise with some rough rules of thumb:
output requires a “write” instruction and a value to output
assignment requires a variable label and a value to store
an expression requires operators and values and/or variables, which when evaluated produce a result value
input requires a “read” instruction and a variable in which to store the incoming value
selection requires an expression that evaluates to a value of true or false, a set of instuctions to execute when the expression is true, and a set of instructions to execute when the expression is false
Downloads
Examples are available for download here.
In part two these ideas will be extended further in looking at lists, subroutines, and repetition.
tech.thingoid Gosbell First published: PC Update Apr 2004