Chapter 2 – part b Brent M. Dingle Texas A&M University CPSC 110 - Pascal Chapter 2 – part b Brent M. Dingle Texas A&M University
Back to the programming - Variables in Pascal As in math variables are ‘abstract’ representations of values. Think of a variable as a name. For example consider your name, it represents you. So instead of listing out all of your traits to identify you, we can talk about you by name – and the traits are known.
Variables (cont) Unlike in math the value of a variable may change – as the program runs. Also variables in a program may be one or more characters in length. Some example variable names are: X Y Sum N1 N2 Rate time ANS
Values Values may be numbers or other types of data. Variables are said to contain values.
Working up to understanding variables and their values Shortly we will look at a sample program to demonstrate what variables are and how they contain values. You may or may not be able to immediately tell what it does – don’t worry it will be explained.
Sample Program 1 Variables and their values PROGRAM AddTwo VAR n1, n2, sum : integer; BEGIN writeln(‘Enter two numbers’); readln(n1, n2); sum := n1 + n2; writeln(n1, ‘ plus ‘, n2, ‘ = ‘, sum); END.
Statements Between the BEGIN and END lines are 4 instructions to be performed by the computer. Each instruction is called a statement. Every statement ends with a semi-colon (;) There are some exceptions to the ending semi-colon, but don’t worry too much about that now.
Some commands We will be returning to that program – but before that we need to learn some Pascal commands.
writeln The writeln (pronounced write line) command tells the computer to write a line of text. Specifically the computer is to output to the screen whatever is in the parentheses after the word writeln. Anything in single quotes is output “as-is” Anything not in single quotes is assumed to be a variable and the variable’s value is output.
writeln - example 1 So the statement: writeln(‘Enter two numbers’); will cause the computer to print: Enter two numbers to the computer screen.
writeln – example 2 The statement: writeln(n1); would cause the computer to output the VALUE of n1. Assuming that n1 holds the value 42, then the output of the above statement would be: 42
writeln – example 3 The statement: writeln(‘The value of n1 is’, n1); would cause the computer to output: The value of n1 is 42 (again assuming n1 contained the value 42)
readln The readln command causes the computer to read data from the keyboard (or other input device – such as a file) and place it into any variables specified between the parentheses following the readln command. If no variables are specified (i.e. there are no parentheses following the readln command) then the computer will simply wait for the user to press the [enter] key.
readln – example 1 So the statement: readln(n1); would read ONE number (of 1 or more digits) from the keyboard and place the value of that number into the variable n1. So if the user typed: 31 and pressed enter, the value of n1 would become 31.
readln – example 2 So the statement: readln(n1, n2); would read TWO numbers (of 1 or more digits) from the keyboard. So if the user typed: 53 27 and pressed enter, the value of n1 would be 53 and the value of n2 would be 27.
Assignment Operator := The assignment operator in Pascal is the colon equals, := So the statement: n1 := 5; would cause the value of n1 to become 5 Important note: we call the number 5 a constant because it will not change in value.
Assignment Op – continued The statement: sum := n1 + n2; would cause the value of sum to become whatever the value of n1 plus the value of n2 is. So if n1 contained the value 55 and n2 contained the value 33, then the above statement would set the value of sum to be 88.
Expression Just for reference an assignment statement is always made up of a variable on the left hand side of the := and an expression on the right hand side. IN THIS CONTEXT, an expression may be a variable, a number, or a more complicated expression made up of variables, numbers and arithmetic operators (like +, -, / or *).
Going back to Program 1 You should now know what most of it does. PROGRAM AddTwo VAR n1, n2, sum : integer; BEGIN writeln(‘Enter two numbers’); readln(n1, n2); sum := n1 + n2; writeln(n1, ‘ plus ‘, n2, ‘ = ‘, sum); END.
Identifiers In the sample program notice the name of the program is AddTwo – this is an identifier. The variable names: n1, n2, and sum are also identifiers. In general a name used in a Pascal program is called an identifier. Identifiers are defined to be any string made up of letters, digits and the underscore symbol.
Identifiers – rules ALL identifiers MUST start with a letter or an underscore. Any two identifiers or numbers must be separated by one or more spaces, by a line break, by a punctuation symbol (comma, semi-colon, colon, etc) or by a combination of two or more of these separators.
Identifiers – Examples All the below are valid Pascal identifiers: X x1 x_1 Sum ABC1234q7 _abc RATE count DaTa2 Hi_There
NOT Identifiers None of the below are identifiers: 21 3x 4Y %change Data.1 Bad-Data FIRST.PAS Do you see why?
NOT Identifiers – explanation 21, 3x, 4Y and %change are NOT identifiers because they do not start with a letter or underscore. Data.1, Bad-Data and FIRST.PAS are NOT identifiers because they contain characters that are not letters or the underscore.
Identifiers – length Technically identifiers in Pascal may be of any length, however Pascal limits you to 63 characters – which should be more than you need. (Who wants to type a variable name that is that long anyway?)
Case (In)Sensitivity In Turbo Pascal there is NO distinction between upper and lower case letters when it comes to identifiers. For example: Sum, sum and SUM are all the same identifier as far as Turbo Pascal is concerned.
Reserved Words So getting back to our sample program, you should be wondering about the words: program, var, begin and end. These are all reserved words in Pascal. A reserved word has a predefined meaning in Pascal.
Standard identifiers You may wonder why words such as readln, writeln, and integer are NOT reserved words… This is because their meaning, while predefined may be changed – these type of identifiers are called standard identifiers.
General Program Layout Program Heading Variable Declarations (global) Program Body
Program Heading This is just the first line of most programs. For example: PROGRAM AddTwo;
Variable Declarations This is where the (global) variables are declared. For example: VAR n1, n2, sum : integer; r1 : real;
Program Body The program body is the list of statements to be executed. This in general are all statements between the BEGIN and END lines. Side note: the last END is followed by a period.
Data Types A data type is a type or category of data. All variables are of some data type. When you declare a variable you also declare its type.
Variable Declaration An example of variable dclaration is: var n1, n2, sum : integer; This declares 3 variables of type integer.
Numbers in Pascal There are two major number data types in Pascal: Integer (e.g. –1, 53, 1002, etc) Real (e.g. –4.3256, 1.045, 120.29801, etc)
Integers Integers are stored as exact values. Because a computer has finite storage, there does exist a minimum and maximum integer value that Pascal will understand. Can you write a program to determine these minimum and maximum values? Hint: maxint
Reals Type reals are stored only in an approximate form – again due to the finiteness of a computer. Type reals may be written using a form of scientific notation: 5E27 = 5 * 1027 or 6.5E-3 = 6.5*10-3 Note though the below are NOT valid numbers: .5E12 because there is no number before the decimal point 3.78E11.4 because there is a decimal point in the exponent Reals also have a maximum and minimum value in Pascal.
Type Compatibility Notice that the number 3 and 3.0 are NOT the same type. 3 is type integer 3.0 is type real
Type Compatibility (cont) Say you have the following variables: var n1, n2 : integer; r, q : real; You may assign an integer value to a variable of type integer OR type real. So the statements: n1 := 3; and r = 3; and q := n1; would all be valid.
Type Compatibility (cont 2) However you may assign a real value ONLY to type reals. So the statements: r := 4.05 and r := q; are valid. But the statements: n1 := 4.05; and n1 := q; are NOT valid.
Arithmetic Expressions Arithmetic expressions also have a type associated with them. For example in: x := 5 * (n + (m/9) + 3*y); the expression is the right hand side of the statement (i.e. 5 * (n + (m/9) + 3*y) ). The expression returns a type real (because it contains division).
Determining Type of Expressions Combining something of type real with something of type integer or real always yields something of type real. real + real => real real + integer => real
Determining Type of Expressions Combining anything with a division sign always yields something of type real. real / real => real integer / integer => real real / integer => real integer / real => real
Determining Type of Expressions Combining two things of type integer with an addition sign, a subtraction sign, or a multiplication sign yields something of type integer. integer + integer => integer integer – integer => integer integer * integer => integer
Determining Type of Expressions Placing a minus sign in front of an arithmetic expression does NOT change its type. - integer => still an integer - real => still a real
MOD and DIV Pascal has two built in arithmetic operators that work ONLY on integer (ordinal) types. Mod returns the remainder of an integer divided by an integer. So, 5 mod 3 returns 2. Div returns the quotient of an integer divided by an integer. So 5 div 3 returns 1.
Char and string data types Pascal has two types that deal with characters – a character is generally anything that can be typed from the keyboard. Type char can hold ONE character. Type string may hold more than ONE character, based on how it is declared.
Strings Variables of type string are declared: var name : string[40]; This declares a string that can hold up to 40 characters. To assign a string a value you use a statement like: name := ‘Robert Frost’;
Problems with strings Make sure your strings are declared long enough. Programming as follows: var name : string[4]; : : name := ‘Bob Hope’; will cause errors to develop ! (Notice ‘Bob Hope’ is longer than 4 characters)
String Trick To place a single quote inside a string you must type it twice. For example to set message to have the value Bob’s rock you would say: message := ‘Bob’’s rock’; And that is 2 single quotes between the b and the s, NOT a double quote.
String Concatenation Strings may be concatenated together (i.e. placed together) by using the plus sign. So if first = ‘John’ and last = ‘Smith’ then the statement: name := first + ‘ ‘ + last; would cause name to be: ‘John Smith’
Output – writeln vs. write writeln automatically forces a carriage return line feed (i.e. the output advances down a line) write does NOT advance a line. The code: writeln(‘one’); writeln(‘two’); would result in the output of: one two The code: write(‘one’); write(‘two’); would result in the output of: onetwo
Formatting Numbers Suppose you want to force the output of an integer to occupy a specific number of spaces. Say that number of spaces is 5, here is the code to do it: n := 12; writeln(‘n =‘, n:5, ‘#’); The above code would output: n = 12# Notice there are 3 spaces between the equal sign and the 1. So the output for the n took up exactly 5 places. This is called specifying the field width.
Formatting Real Numbers So integers are easy to format, what about reals? Try this: cost := 3.4513; writeln(‘The cost is $’, cost:5:2, ‘.’); The above code will output: The cost is $ 3.45. There is one space between the $ and 3 So what happened to the 13 in the decimal part?
Formatting Real Nums (cont) The :5:2 took care of it. The 5 says ‘use 5 places’ the 2 says and use only 2 places for anything after the decimal point. The :5 is a field width (i.e. how many places to use) The :2 is a field specification (i.e. how many numbers after the decimal to use)
Real Numbers – Try this at home It is important to know if your numbers are going to be displayed rounded or truncated. Try this at home and find out: cost := 2.127; writeln(‘The cost is $’, cost:5:2); Is the output: Rounded The cost is $ 2.13 Truncated The cost is $ 2.12
For the lazy Assuming you were too lazy to actually try to create the program yourself, field specifications in Pascal will ROUND the answer.
Field Width – A trick with zero If a field width specification is too small to hold a number, Pascal will make enough room to hold the number. For example: writeln(‘$’, 1234.567 : 0 : 2); will output: $1234.57 Likewise: writeln(‘$’, 3456.123 : 3 : 2); will output: $3456.12
Input - read and readln These work similar to write and writeln: read reads a list of variables readln reads a list of variables AND the [enter] Variables of types real, integer, character and string may be read using read and readln. If you wish to enter multiple numbers on the same ‘line’ of input they must be separated by spaces, however – BE CAREFUL.
Numbers, spaces and [enter] Be careful reading numbers off a single line and mixing read and readln. Consider the code (with n1, n2, n3 of type integer): readln(n1, n2); read(n3); If the input is: 1 2 3 [enter] 4 What do you think the values of n1, n2, n3 are?
Nums, spaces, and [enter] (cont) As it happens: n1 is set to 1 n2 is set to 2 BUT n3 is set to 4 This is because the readln(n1, n2) reads the 1, 2, 3 AND the enter key. It then assigns the values to its variables. When we get to the read(n3) we have already missed the 3.
More on read and readln It should be obvious that: read( x, y ); readln; and readln( x, y ); are equivalent. Experiment with these commands, you will use them often.
Prompt Lines prompt lines are lines of text displayed to the user that request information or action from the user. For example: Please enter your name: would be a prompt line.
Programming Style There a variety of ‘styles’ to programming. All styles will address issues such as capitalization – what to capitalize spacing – where/how to use spaces/indenting comments – where are comments placed and what gets commented on. You will find a styles handout sheet on the web page or you may be given one in lab.
Programming Style (cont) A GOOD STYLE is a READABLE STYLE. A GOOD STYLE is a CONSISTENT STYLE. All GOOD programmers program in a GOOD STYLE. For this class ask the TA’s what style they expect from you – they will be grading your programs.
Constants Pascal allows you to declare constants. This is done something like this: CONST NUM_BRANCHES = 10; CD_CODE_TYPE = ‘CD’; INTEREST_RATE = 0.03; It is NOT necessary to use all capital letters for constant names, it is the STYLE I have chosen to use. Notice that the constants can be of almost any type (that we know of so far) – integer, string, char, or real.
Constants (cont) Using constants well in a program can make the program easy to modify. For example consider a program that uses some RATE – perhaps you don’t know what this rate is when you start writing the program, but you do know that it will NOT change. It would be wise to declare it a constant at the beginning of the program. Then it will be easy to set its correct value when it is known and you can write the program before then.
Predefined Constants There exist some predefined constants in Turbo Pascal. For example: maxint pi There may be others – look them up =)
End Chapter 2