Chapter 5 - ANSWERS Variables and Constants
Chapter 5 - ANSWERS Variables and Constants
Instructions
1. Replace the words Student Name in the header of this document with your own
name.
2. Read Chapter 5: Variables and Constants and make notes for yourself by
completing the following:
Variables
A name or identifier is given to each location in a computer’s memory where data is
located.
A variable is a location that holds data.
Before a variable can be used in a program, it must be declared.
To declare a variable, give it a name and its data type.
For example,
var firstName: string
var is the keyword in Turing for a variable.
The rules for naming a variable are:
1. the first character must be a letter
2. after the first character, digits and the underscore character are valid
3. special characters (e.g. spaces, hyphens, periods) are not valid
get is the Turing operator that accepts input from the keyboard.
get reads characters for a string variable until it hits “white space” such as a blank or a
Return.
Token-oriented input is a quoted string or a string surrounded by white space.
A syntax error occurs when the rules of grammar or syntax of the programming
language are broken.
An example of a syntax error is attempting to use an undeclared variable.
A run-time error (also known as an execution error) occurs when the program is run,
not in the program itself.
For a real variable, it is legal to input an integer.
When a numerical result is very large, Turing outputs the number in exponent form.
Constants
A constant is a memory location holding data that remain constant.
Chapter 5 — ANSWERS
Variables and Constants
An example of the declaration of a constant is
const pi : real := 3.14159
To declare a constant, we give three parts: its name, type, value.
It is often useful to declare the text of a prompt as a constant at the top of a program
because you can easily find and change the text of the prompt, which you might
want to use in various places in the program.
What does an assignment statement do? An assignment statement gives a value to a
variable or constant.
:= is the symbol that assigns a value to a variable or constant.
Here is an example of how to use a put statement with a very long quoted string.
put “Here is a very long line that had to “,
“be broken”
Three ways of making a program easily understood are:
1. put each statement on a separate line
2. choose good names for variables
3. add comments
% is the symbol that begins a comment line in a program.