Home
Intro
LC
ACR
About

Day 3 - Variables and Constants

-=-=-=-=-=-=-=-=-=-=-

What you are going to learn today:

  • What variables and constants are
  • Some examples of variables and constants
  • How variables are implemented in Pascal
  • And an variables example program

-=-=-=-=-=-=-=-=-=-=-

So, you've typed your first program, dissected it line by line, and now you're ready for anything. Well, today you're going to learn about variables and constants, nothing particularily difficult, so just sit back and enjoy!

What are Variables and Constants?

That's an interesting question. How would you define a variable? Well, ever learnt Algebra before? It's the same concept. Just take a name, and assign it a value. It's that simple. For instance, you could say that a = 2. So, a + a is the same as 2 + 2, which equals 4. Easy does it.
Well, then you may ask, "If it's so darn simple, why call them variables, and not an algebric number or something?" Ahh, good question! You see, the name comes from the very nature of variables in programming. They can vary. Sure, I know it wasn't like that in Algebra class, but our aim now is not to find out what x is, but to instead use x as just a storing place for a value. Get the idea? Our x is just a storing place for 2.
Then what about constants? Well, constants can be said to be the exact opposite as variables. Instead of just being storage space, the aim of a constant is to replace values. For example, if we had replaced every occurance of the word "lamb" with the word "head" in a certain famous nursery rhyme, we would had got:

"Mary had a little head,
its fleece was white as snow.
And everywhere that Mary went,
her head was sure to go."

Yes, it's a very strange version of the original classic, but that's only if you read it literally. If I had said that "head" is just a constant representing "lamb", it would have made perfect sense. Never thought of it that way, eh? Well, better start thinking about it. Constants were created to make program code more readable by replacing meaningless numbers with a meaningful name. A very nifty feature!

Some more examples of Variables and Constants

Still can't get the idea? Don't worry, here are a few more examples to help you out. (We call this 'Learning by Example'.)

A variable can be viewed as a box with a value

One method we can use for explaining a variable is to use the analogy of a box. Imagine that a variable is actually a box carrying the value which it stores. Now, you can actually take the value out, and put in a new one. After that, you can look up the value in the box and do things with it. You could also copy the value into other boxes, or take the values from other boxes and put them in your box. Variables are very flexible. They can store values from almost any other source you specify.
But here's where the concept of data types come in. You see, just like in real life, boxes come in all shapes and sizes. So, some boxes can't store certain values beyond their limits. Ahh, you guessed there was a catch! The different data types will be introduced to you later. For now, however, let's just talk about constants first.

Constants are just like a look-up table

Constants can be compared to a look-up table, something you'll use to look up unknown terms. (This is similar to the use of the word 'software' in license agreements, if you ever read them.) When you come across this 'unknown term', you will have to look up this table and understand what it means. For instance, if you declare a constant 'Name' representing "Tan Chun Ghee", the sentence "I think Name is really great!" would translate to "I think Tan Chun Ghee is really great!" This would be the same with the sentence "Name is my idol!" which would translate to "Tan Chun Ghee is my idol!" As you can see, "Name" is explicitly replaced with the text that it represents.

How Variables and Constants are implemented in Pascal

Yes, now that you have understood the underlying concepts behind variables and constants, you can finally find out how to implement them in Pascal!

Implementing Variables

Variables in Pascal are declared using the 'var' keyword. You need to declare a variable before you can use it. Why? Well, it's like if you were making the box for the value to be stored. Then, after the box is finished, you can start placing the value into it. You can't use a box if you don't make one! These are how declarations look like:
  var
    Number, Value: integer;
    Text: string;
    TrueOrFalse: boolean;
The syntax for a declaration is to put the name of the variable, a colon, the data type of the variable, and finally, the grand semicolon. You can also declare more than one variable in one line by separating them with commas. Now that reminds me, we still haven't told you the different data types, haven't we? Well, here they are, shamelessly lifted from the Turbo Pascal help:

Type Range Precision
Shortint -128..127 Whole numbers only
Integer -32768..32767 Whole numbers only
Longint -2147483648..2147483647 Whole numbers only
Byte 0..255 Whole numbers only
Word 0..65535 Whole numbers only
Boolean True or False Whole numbers only
Real 2.9e-39..1.7e38 11-12
Single 1.5e-45..3.4e38 7-8
Double 5.0e-324..1.7e308 15-16
Char a character Characters only
String 255 delightful characters! Text only

Of course, those are not all the data types you can have in Pascal. In fact, you can even make your own data types, so there really isn't any limit! Variables can be any size you want them to be.

Implementing Constants

In Pascal, constants are listed under the 'const' keyword, just like the look-up table concept explained above. A typical list of constants would look like this:
  const
    Pi = 3.14;
    Gravity = 9.8;
    Golden = 1.6;
Because these numbers are meaningless by their own, we give them more meaningful names to make our code more readable. Imagine reading an entire maths textbook which refers to pi by its value! Unthinkable!

Below is the example program listing for today. Open a new code window to type in the code. Ahh, the three famous bars!

Type

1: program VariableMania;
2:
3:   const
4:     Interest = 2;
5:
6:   var
7:     Money, Debt: integer;
8:
9:   begin
10:    { This is a very sad story of a man and a bank. }
11:    { Moral: Never tell a story about a man and a bank. }
12:
13:    Debt := 100;
14:    Writeln('There was once a man who owned a bank $', Debt, '.');
15:
16:    Money := 99;
17:    Writeln('However, he only had $', Money, '.');
18:
19:    Writeln('After one year, an interest of ', Interest, '% was issued.');
20:    Debt := Debt + (Debt div 100 * Interest);
21:    Writeln('His debt increased by $', (Debt div 100 * Interest), '.');
22:    Writeln('Now, his debt was $', Debt, '.');
23:  end.

Run

There was once a man who owned a bank $100.
However, he only had $99.
After one year, an interest of 2% was issued.
His debt increased by $2.
Now, his debt was $102.

Analyse

Once again, let's have a line-by-line analysis of this program. It looks long, but inside it's simpler than you think!

  • Line 4 - This is a declaration for the constant 'Interest'. Now, whenever the compiler sees 'Interest', it'll return this number instead.
  • Line 7 - Here are the declarations of variables 'Money' and 'Debt'. Both are integers, which only allow them to store whole numbers, but as you'll see later, this arrangement makes the program much easier to read.
  • Line 13 - This is where the program really starts. See the := sign? Whenever that sign is used, it means that the value to the left of the sign will now store the value to the right of the sign. So in this case, 'Debt' now stores the value 100.
  • Line 14 - This line prints out a message that changes with the value of 'Debt'. If you inspect the line closer, you'll see that after the first string, there is a comma, the variable name, and another comma, followed by the next string. When this line gets printed, The value of the variable is printed onto the screen.
  • Line 16 & 17 - These lines do exactly the same thing as lines 13 and 14, except that they print out 'Money' instead of 'Debt'.
  • Line 19 - This line uses a constant to print out the sentence. The compiler replaces the word 'Interest' with the number 2. Once again, this uses the Writeln command to output the sentence.
  • Line 20 - Here, a calculation is carried out at the right of the :=, and the value is stored into 'Debt'. What it does into to take the current value of 'Debt', add it to Debt divided by 100 times 2, and place the new value into 'Debt'. In this calculation, division is replaced by 'div', and multiplication is replaced by '*'. You'll see why later.
  • Line 21 & 22 - These lines output the amount of interest and the new value for 'Debt'.

Remember the procedure to run programs in Day 1? Well, here's how it works: When you first ran the program, the output flashes by so quick that it's nothing but a flicker on your screen. When you select 'User Screen', or press Alt-F5, you are just simply seeing what the user would see after he exits the program.
Now, had fun writing that? You might notice that our mathematical operations seemed to have changed a bit. Well, the standard for the four mathematical operations are +, -, *, and, /, with the slash meaning division, but you may notice that in our program, the slash is replaced by the keyword 'div'. This is because we're dealing with integers here, and the / symbol only returns real numbers. So we calculate integers with the 'div' keyword instead. Look up the help for more details.

End of Day 3

All right! It's over for now. Get up and give yourself a little stretch. You've just gone through a crash course through Variables and Constants, and now we're going on to Day 4, where we talk about "Control Flow", so hang on! It's not over yet!

-=-=-=-=-=-=-=-=-=-=-

HomeIntroLCACRAbout
Back to Class B

-=-=-=-=-=-=-=-=-=-=-

This page is ThinkQuest entry 11127.
email: tq97-11127@advanced.org