The Start: Introduction, Comments, Output, Variables, Input (Turing)

From Compsci.ca Wiki

Jump to: navigation, search

Contents

Introduction to Programming

Programming may seem scary at first, but hold fast! It is elegantly simple. Here's why: Programming languages are not computer languages. They are human languages that computers can translate into their own language (binary). They have been successfully designed by humans for use by humans, despite the restrictions placed on programming languages because they must be understood by computers as well. Writing in a programming language is strikingly similar to writing in a language in the traditional sense of the word: there are syntax rules to follow, there are objects that analogous to nouns, and methods that are analogous to verbs. There are no adjectives, mind you, because computers understand quantity, not quality.

That said, let's delve in and learn just how computer languages work. The only thing you need to know right now is that the computer executes the code sequentially--line by line. The first line of a program is completely executed before execution of the next line has begun.

Comments

Some code is difficult to understand, even if you understand the language it is written in. To that end, the designers of programming languages have allowed us to comment our code. In Turing, this is done by placing the percent sign (%) before a comment.

% This is a comment.  Everything after the % on this line is ignored by the computer.

Another way of commenting code is by using matching sets of "/*" and "*/"

/*
This is a comment.  Everything after the forward-slash-asterisk but before the matching asterisk-forward-slash is ignored by the computer.
*/

Commenting makes your code more understandable to yourself (you may think you know what your code is doing, but you probably won't know when you return to it a month later) and to others who read your code. If your code is more understandable, you will be more productive in writing it and others will spend less time understanding it and more time helping/learning from you.

Output

There are several ways that our computers can communicate to us. The first and most obvious is visually, through the monitor. The second is audibly, through the speakers. The last is much more tangible: the printer. We will begin by learning how to output text to the monitor, and save the speakers and printer for later lessons.

We want to put some text on the screen, to prove that the link between us and the computer does in fact exist. Let me repeat that again: We want to put some text on the screen. In Turing, we do this by using the put command, followed by the text, contained in double quotes, that we want to output, like this:

put "Hello World"

Type this code into your Turing window and click the Run button (or hit F1). You should see a Turing Run Window pop up with some buttons across the top and text that says "Hello World". If you see this, the first task is complete. If not, go update your version of Turing.

Now, a bit of explanation is due. The put command takes whatever is after it and puts it at the cursor location in the Run Window. You don't see the cursor, mind you, because we never asked for input; only output. The cursor begins in the upper left corner, and with each time you put text on the screen, the cursor moves down one line.

What comes after the put command determines what you will see on the screen. In the case of our "Hello World" program, we put a string on the screen. "What's a string?" you ask. Let us examine.

Variable Types

Strings

We have already encountered the string. Now let us answer the unrelenting question, "What is a string?" A string is a sequence of characters. The characters can be ordinary things such as letters and numbers, or they can be wacky things found in the ASCII chart such as the plus-minus sign (±). A string is bounded by quotation marks, as in "Yarr! I caught me aye fish!" A string can contain a maximum of 255 characters.

Characters

A character is a single letter, number, or any wacky symbol that you can find in the ASCII chart. Characters are bound by quotation marks, as in 'Q'. Generally, strings use double quotes and characters use single quotes, though either type can use either style of quotation mark.

Integers

We should all know what an integer is, given some fundamental math. Just to make sure, an integer is a whole number; it has no decimals; it is a fraction whose denominator is 1; it can be negative, zero, or positive.

Real Numbers

Real numbers can contain decimal places. Turing supports up to 16 decimal places for real numbers. Real numbers contain the realms of the positive, the negative, and zero.

Boolean

The boolean (named after George Boole) variable type contains only two alternatives: true or false. We will look into these in greater depth later, particularly when learning about conditions or if statements.

Returning to Output

Now that we know our Hello World program output a string on the screen, let's experiment with the other variable types. Let's try outputting an integer, then a real number.

put 7                               % Outputs 7
put 8.19538032154                 % Outputs 8.19538

Notice how the real number was rounded.

Now I know everyone loves arithmetic, so it's about time we did some. Quickly now, (4 + 8) / 2 * (3 - 5) equals what?

put (4 + 8) / 2 * (3 - 5)       % Outputs -12

Turing does the math following the precedence rules, BEDMAS (Brackets, Exponents, Division and Multiplication, Addition and Subtraction). Now let's output the question and the answer:

put "(4 + 8) / 2 * (3 - 5) = ", (4 + 8) / 2 * (3 - 5)
% Output: (4 + 8) / 2 * (3 - 5) = -12

Notice the use of the comma (,). The comma separates one section from the next. The first section is a string, which shows us the question. The next section is an integer, which is the answer.

Strings can be added together, a process called concatenation: we are taking one value and placing another value directly after it.

put "Hello " + "Alan Turing."      % Outputs "Hello Alan Turing."

"Alan Turing" is placed directly after "Hello ", to produce a quaint greeting to the legendary mathematician, cryptographer, logician, philosopher, biologist, and computer scientist, Alan Turing (1912 - 1954).

Constants and Variables

We use constants and variables in mathematics all the time. Consider the following equation:

V = 4/3 * pi * r ^ 3

Volume equals four-thirds pi times the radius cubed.

There are two variables in the above equation: V and r. V represents volume. r represents the radius of the sphere. V and r have values that can change. They are probably real numbers.

There is only one constant in the above equation, pi. It's value is constant, unchanging, no matter when or where you are in the universe. It is always (approximately) 3.14159265358979323846.

In programming, a variable represents a location in the memory where a value is stored.

Declaring Constants and Variables

The general syntax (read: grammar) for creating a constant in Turing looks like this:

const variableName : typeSpec

Declaring a variable is the same, except the keyword const is replaced with var.

var variableName : typeSpec

variableName is the name of your variable. It can contain letters (upper case and lower case), numbers (though it cannot start with a number), and underscores.

typeSpec is the variable type: a string, integer, real number, or a boolean value. Let's create one variable of each type:

var customerName : string          % A variable to store the name of your customer
var numberOfPassengers : int        % A variable to store the number of passengers (in your private jet, nonetheless)
var priceOfASausage : real         % A variable to store the cost of a sausage at the local supermarket
var tastyToblerone : boolean        % A variable to store whether a toblerone bar is tasty or not

Assigning Values to Variables

The thing is, none of these variables have been assigned any values. To assign a value to a variable, we use the colon-equals (:=).

The general syntax (read: grammar) for creating a variable in Turing looks like this:

customerName := "Wolfgang Mozart"
numberOfPassengers := 645
priceOfASausage := 2.55
tastyToblerone := true

The variable on the left side of the assignment (:=) is given the value on the right side of the assignment (:=).

You can assign more complex things to variables, as well. You can assign entire expressions, variables, or mixtures of both to variables. Watch:

var priceOfChocolateBar : real
var priceOfTeddyBear : real
var priceOfBicycle : real
var numOfChocolateBars : int
var numOfTeddyBears : int
var numOfBicycles : int
var total : real

priceOfChocolateBar := 1.49
priceOfTeddyBear := 6.99
priceOfBicycle := 349.99
numOfChocolateBars := 2
numOfTeddyBears := 4
numOfBicycles := 1
total := priceOfChocolateBar * numOfChocolateBars + priceOfTeddyBear * numOfTeddyBears + priceOfBicycle * numOfBicycles

put "The cost of ", numOfChocolateBars, " chocolate bars, ", numOfTeddyBears, " teddy bears, and ", numOfBicycles, " bicycles comes to $", total, "."

You can even use the value of the variable you are assigning to on the right side of the assignment (:=). Say we want to buy another chocolate bar:

% Add the current total and the cost of  another chocolate bar,
% and assign the sum to the variable, total
total := total + priceOfChocolateBar

Three Examples to Digest

If you haven't opened Turing (the programming language, not the person) already, do so. Copy and paste the following code into the typing area and run the program.

Example 1: Various Facts

var customerName : string         % A variable to store the name of your customer
var numberOfPassengers : int       % A variable to store the number of passengers (in your private jet, nonetheless)
var priceOfASausage : real        % A variable to store the cost of a sausage at the local supermarket
var tastyToblerone : boolean       % A variable to store whether a toblerone bar is tasty or not

customerName := "Wolfgang Mozart"
numberOfPassengers := 645
priceOfASausage := 2.55
tastyToblerone := true

put "A wispy, frail man named ", customerName, " has entered your store."
put "Despite the occupant limit of 200 people, you have managed to fit ", numberOfPassengers, " people into your private jet!"
put "Due to inflation, the price of a single, moderately spicy, Italian sausage has risen to $", priceOfASausage, "."
put "True or False: Toblerone's are tasty: ", tastyToblerone

The program should execute successfully. The output should look like this:

A wispy, frail man named Wolfgang Mozart has entered your store.
Despite the occupant limit of 200 people, you have managed to fit 645 people into your private jet!
Due to inflation, the price of a single, moderately spicy, Italian sausage has risen to $2.55.
True or False: Toblerone's are tasty: true

Example 2: Volume of a Sphere

var V : real
var r : real
/*
Because pi is declared as a constant, we must give it a value immediately.  We cannot wait a line or two, because then we are changing the value of pi from nothing (nil) to 3.1415...
*/
const pi : real := 3.14159265358979323846

r := 10
V := 4 / 3 * pi * r ** 3       
% Usually we use the carat (^) for exponents, but Turing uses a double-asterisk (**). 
% The base is immediately before the double-asterisk.
% The exponent is immediately after the double-asterisk.

put "The volume of a sphere with radius ", r, " units is ", V, " cubic units."

Here's the output:

The volume of a sphere with radius 10 units is 4188.790205 cubic units.


Example 3: Quadratic Formula

If you don't know anything about the quadratic formula, don't worry. Just look at the programming, and don't worry about the math.

% We can declare variables of the same variable type on the same line,
% by separating them with commas.
var a, b, c, x1, x2 : real
a := 5
b := 8
c := -3
x1 := (-b + (b**2 - 4*a*c) ** 0.5) / (2 * a)
x2 := (-b - (b**2 - 4*a*c) ** 0.5) / (2 * a)
/*
Raising something to the power of one-half is the same as taking the square root of it.
for curiosity, these lines could also be written like this:
x1 := (-b + sqrt (b**2 - 4*a*c)) / (2 * a)
x2 := (-b - sqrt (b**2 - 4*a*c)) / (2 * a)
*/

put "The roots of the parabola 'y = ", a, "x**2 + ", b, "x + ", c, "' are ", x1, " and ", x2, "."

Here's the output:

The roots of the parabola 'y = 5x**2 + 8x + -3' are 0.313553 and -1.913553.

Problems with Assignability

If you've been tinkering around with Turing as you're reading this, you may have already discovered this. Say you have a integer variable. You are not allowed to assign it a value such as "Fred" or 4.684. This is a syntax error.

That's understandable, but what about this next scenario? You've got an integer variable and you want to assign it a value of "7". That's 7, in double-quotes. We can't even do this. The reason is "7", the string, is stored in memory differently than is 7, the integer. (Integers can be stored using simple binary. 7, for example, is 111 in binary. Strings, however, are actually a collection of characters, and the characters are defined by their ASCII value. 7 has an ASCII value of 55, which in binary is 110111. A conversion must take place in order to allow things to operate smoothly. I discuss this in my String Manipulation tutorial, but don't go there. This is all just to peak your unbridled and ever-lusting curiosity. Is it satisfied now?)

For now, accept the rules of assignability. Don't go trying to assign a value of "Jared Diamond" to your boolean variable.



Getting Information From The User

Now comes the fun part. We're going to learn how to get input from the user of your program. The most basic way of doing this is using the get command. It's rather simple:

var name : string
put "What is your name?"
get name
put "Hello ", name, "!"

First, we must declare our variable. Then we get the variable name, which will get input from the user. Try running this program.

Question 1

Try to crash the above program.

Hint 1

Look above, where we first introduced the variable types.

When you're done crashing that delicious program, try running the following, very similar program:

var age : int
put "How old are you?"
get age
put "Wow! ", age, " sure is old, especially for you mortals! *cackle*"

This program is much easier to crash. Entering a string such as "Insolent fool! I'm immortal!" or entering a real number such as 9e5 (this means 9 * 10^5, which is nine hundred thousand [900 000], and is in fact a valid real number).

Question 2

Write a program to output the kinetic energy of an object given its mass its velocity (that is, the user inputs the mass and the velocity) according to the following formula:

Ek = 1/2 * m * v^2

where Ek is the kinetic energy of the object,
m is the mass of the object,
and v is the velocity of the object.



Conclusion

If you've made it this far, kudos to you! You've mastered the fundamentals of Turing and of any programming language. You can now interact with the computer through Turing, and you're program can interact with the user through the put and get commands.

Now take your mind off these things. Spin an album-side (or have you been multitasking this whole time?), go for a run, talk to your family/friends, or, in the spirit of getting into the CompSci.ca community, download and watch some anime / play DDR.

The Beatles - Tomorrow Never Knows

Turn off your mind, relax, and float downstream.
It is not dieing. It is not dieing.
Lay down all thoughts, surrender to the void.
It is shining. It is shining.
That you may see the meaning of within.
It is being. It is being.

When you're ready, learn how to test certain conditions using if statements.


Answers

Answer 1

Input a string longer than 255 characters. 3.5 lines of characters using the standard run window size should do it.

Answer 2

var kineticEnergy, mass, velocity : real
put "Please enter the mass of an object, in kilograms: " ..
% The .. makes the cursor follow this line,
% rather than jumping down to the next line.
% Thus, the text the user types will appear
% immediately after the request.
get mass
put "Please enter the velocity of the same object, in metres per second: " ..
get velocity
kineticEnergy := 0.5 * mass * velocity ** 2
put "The kinetic energy of your object is ", kineticEnergy, " Joules."

Credits

Author: Cervantes Added by: Wtd

Personal tools