Programming For As Comp

50 %
50 %
Information about Programming For As Comp

Published on November 30, 2008

Author: david.halliday

Source: slideshare.net

Description

This covers details on Writing Pascal using Lazarus.
A teaching resource for students without any previous experience. Can be used for teaching or direct notes for students (Continued with notes for A2).
Originally written for AQA A level Computing (UK exam).

Programming for AS Computing Using Pascal & Lazarus By David Halliday

Pascal Pascal is a high level imperative language Developed in 1970 Named after mathematician and philosopher Blaise Pascal. More history: http://en.wikipedia.org/wiki/Pascal_programming_language Pascal documentation available here: http://www.freepascal.org/docs-html/ref/ref.html

Pascal is a high level imperative language

Developed in 1970

Named after mathematician and philosopher Blaise Pascal.

More history: http://en.wikipedia.org/wiki/Pascal_programming_language

Pascal documentation available here: http://www.freepascal.org/docs-html/ref/ref.html

Delphi/Object Pascal Borland Delphi is a trade name for Object Pascal created by Borland. The language is actually called “Object Pascal” but is widely referred to as “Delphi”. Object Pascal adds object oriented programming and graphical (GUI) “widgets” to the language. Released in 1995. More history: http:// en.wikipedia.org/wiki/Delphi_programming_language Object Pascal documentation available here: http://www.freepascal.org/docs-html/ref/ref.html

Borland Delphi is a trade name for Object Pascal created by Borland.

The language is actually called “Object Pascal” but is widely referred to as “Delphi”.

Object Pascal adds object oriented programming and graphical (GUI) “widgets” to the language.

Released in 1995.

More history: http:// en.wikipedia.org/wiki/Delphi_programming_language

Object Pascal documentation available here: http://www.freepascal.org/docs-html/ref/ref.html

Lazarus An IDE (Integrated Development Environment) for Pascal & Delphi. A RAD (Rapid Application Development) tool. Freely available under GNU GPL. Platform independent.

An IDE (Integrated Development Environment) for Pascal & Delphi.

A RAD (Rapid Application Development) tool.

Freely available under GNU GPL.

Platform independent.

The Lazarus Interface

Getting normal Pascal in Lazarus Save any work/project you are working on Project>New Project Select “Program” You are now ready to edit Pascal code without the graphical aspects (can make learning easier). Many tutorials (and the early lessons here) are based on Pascal not Delphi and removing the graphical aspects can make learning easier.

Save any work/project you are working on

Project>New Project

Select “Program”

You are now ready to edit Pascal code without the graphical aspects (can make learning easier). Many tutorials (and the early lessons here) are based on Pascal not Delphi and removing the graphical aspects can make learning easier.

Pascal code - comments The first thing to learn in any language is comments Comments are ignored by the compiler and help you remember things or provide guidance to other developers. (* This is an old style comment *)   {  This is a Turbo Pascal comment }   // This is a Delphi comment. Ignored till end of line.

The first thing to learn in any language is comments

Comments are ignored by the compiler and help you remember things or provide guidance to other developers.

(* This is an old style comment *)  

{  This is a Turbo Pascal comment }  

// This is a Delphi comment. Ignored till end of line.

Statements Statements are “instructions” in a programming language. Some languages use line breaks (pressing return) to separate statements. Many languages including C, C++ and Pascal use a special character to say “end of statement”. In Pascal the character is the semi colon “;”. writeln('hello world'); //output “hello world” myNo := thisNo + thatNo; //Add two numbers

Statements are “instructions” in a programming language.

Some languages use line breaks (pressing return) to separate statements.

Many languages including C, C++ and Pascal use a special character to say “end of statement”. In Pascal the character is the semi colon “;”.

writeln('hello world'); //output “hello world”

myNo := thisNo + thatNo; //Add two numbers

First application The first part just tells the compiler this is a program and in “Project1”. The sections in curly brackets {} are comments. Uses & Classes is for including extra library code. The Begin and end. (the period is important) mark where the actual code starts/finishes. All of this code is already written for you by Lazarus. program Project1; {$mode objfpc}{$H+} uses Classes { add your units here }; Begin end.

The first part just tells the compiler this is a program and in “Project1”.

The sections in curly brackets {} are comments.

Uses & Classes is for including extra library code.

The Begin and end. (the period is important) mark where the actual code starts/finishes.

All of this code is already written for you by Lazarus.

program Project1;

{$mode objfpc}{$H+}

uses

Classes

{ add your units here };

Begin

end.

First application part 2 The command used between the begin and end. Is “writeln” which will be covered in more detail shortly. The statement consists of a key word “writeln” followed by “arguments” in brackets. In the brackets is text in single quotes. The text will be displayed the quotes are there just to tell the compiler that this is to be treated as text. program Project1; {$mode objfpc}{$H+} uses Classes { add your units here }; Begin writeln('hello world’); end.

The command used between the begin and end. Is “writeln” which will be covered in more detail shortly.

The statement consists of a key word “writeln” followed by “arguments” in brackets.

In the brackets is text in single quotes. The text will be displayed the quotes are there just to tell the compiler that this is to be treated as text.

program Project1;

{$mode objfpc}{$H+}

uses

Classes

{ add your units here };

Begin

writeln('hello world’);

end.

First application part 3 A subtlety of modern operating systems being graphical is that when you launch an application using a command line (shown in a window) the window closes when the application finishes. For now just use the extra lines shown. This is all one line but is wrapped around on the slide. program Project1; {$mode objfpc}{$H+} uses Classes { add your units here }; Var myint : integer; Begin writeln('hello world’); writeln(‘type in a number and press enter’); read(myint); end.

A subtlety of modern operating systems being graphical is that when you launch an application using a command line (shown in a window) the window closes when the application finishes.

For now just use the extra lines shown.

This is all one line but is wrapped around on the slide.

program Project1;

{$mode objfpc}{$H+}

uses

Classes

{ add your units here };

Var

myint : integer;

Begin

writeln('hello world’);

writeln(‘type in a number and press enter’);

read(myint);

end.

First application part 4 Press the green arrow/play button in Lazarus to compile Below is an image of the code running after being compiled program Project1; {$mode objfpc}{$H+} uses Classes { add your units here }; Var myint : integer; Begin writeln('hello world’); writeln(‘type in a number and press enter’); read(myint); end.

Press the green arrow/play button in Lazarus to compile

Below is an image of the code running after being compiled

program Project1;

{$mode objfpc}{$H+}

uses

Classes

{ add your units here };

Var

myint : integer;

Begin

writeln('hello world’);

writeln(‘type in a number and press enter’);

read(myint);

end.

Pascal input & output The extra code we added actually did both input (taking data into the program from the user) and output (producing something for the user). We also declared a variable (more on this shortly). The output was done by telling the application to write something to the screen using “writeln”. The input was when we asked the user to type in a number (and the application waited for the user to type a number…and press enter to let the application know the user had finished typing). program Project1; {$mode objfpc}{$H+} uses Classes { add your units here }; Var myint : integer; Begin writeln('hello world’); writeln(‘type in a number and press enter’); read(myint); end.

The extra code we added actually did both input (taking data into the program from the user) and output (producing something for the user).

We also declared a variable (more on this shortly).

The output was done by telling the application to write something to the screen using “writeln”.

The input was when we asked the user to type in a number (and the application waited for the user to type a number…and press enter to let the application know the user had finished typing).

program Project1;

{$mode objfpc}{$H+}

uses

Classes

{ add your units here };

Var

myint : integer;

Begin

writeln('hello world’);

writeln(‘type in a number and press enter’);

read(myint);

end.

Output “ Writeln” outputs the contents of the brackets and then goes onto a new line. “ Write” outputs the contents of the brackets but does not go onto a new line. Note that the new line occurs at the end of the output if it is a “writeln”. On the right: Top: code extract Bottom: Output writeln(‘hello world’); write(‘1’); write(‘2’); write(‘3’); writeln(‘4’); write(‘5’); writeln(‘’); writeln(‘6’); writeln(‘7’); hello world 1234 5 6 7

“ Writeln” outputs the contents of the brackets and then goes onto a new line.

“ Write” outputs the contents of the brackets but does not go onto a new line.

Note that the new line occurs at the end of the output if it is a “writeln”.

On the right:

Top: code extract

Bottom: Output

writeln(‘hello world’);

write(‘1’);

write(‘2’);

write(‘3’);

writeln(‘4’);

write(‘5’);

writeln(‘’);

writeln(‘6’);

writeln(‘7’);

hello world

1234

5

6

7

Output part 2 “ Writeln” can also output the contents of variables. For this example “myint” is an integer variable. Here we see text in single quotes. Here a variable is referenced Next we output both in one command. Note that you need to use the comma to separate elements. writeln(‘your integer:’); writeln(myint); writeln(‘your number:’, myint);

“ Writeln” can also output the contents of variables.

For this example “myint” is an integer variable.

Here we see text in single quotes.

Here a variable is referenced

Next we output both in one command. Note that you need to use the comma to separate elements.

writeln(‘your integer:’);

writeln(myint);

writeln(‘your number:’, myint);

Input The first thing about taking an input from a user is “what is the computer going to do with the input”. In short this depends on what the input is going to be used for. If you are going to perform mathematics then you need the computer to realise that you are giving it a number or “Integer” (data types will be covered later). program Project1; {$mode objfpc}{$H+} uses Classes { add your units here }; Begin end.

The first thing about taking an input from a user is “what is the computer going to do with the input”.

In short this depends on what the input is going to be used for.

If you are going to perform mathematics then you need the computer to realise that you are giving it a number or “Integer” (data types will be covered later).

program Project1;

{$mode objfpc}{$H+}

uses

Classes

{ add your units here };

Begin

end.

Input part 2 Variables are defined in a separate section before the main code as shown. The variable “myint” is first named. Then you put in a colon as a seperator. Finaly the data type (here it is “intiger” for whole numbers). Then the semi colon. program Project1; {$mode objfpc}{$H+} uses Classes { add your units here }; Var myint : integer; Begin end.

Variables are defined in a separate section before the main code as shown.

The variable “myint” is first named.

Then you put in a colon as a seperator.

Finaly the data type (here it is “intiger” for whole numbers).

Then the semi colon.

program Project1;

{$mode objfpc}{$H+}

uses

Classes

{ add your units here };

Var

myint : integer;

Begin

end.

Input part 3 Variable declaration all happens in the “var” section. The layout is: <variable_name> : <data_type> ; You can declare multiple variables of the same type using a comma to separate them. program Project1; {$mode objfpc}{$H+} uses Classes { add your units here }; Var myint : integer; thisno, thatno : integer; result: real; Begin end.

Variable declaration all happens in the “var” section.

The layout is:

<variable_name> : <data_type> ;

You can declare multiple variables of the same type using a comma to separate them.

program Project1;

{$mode objfpc}{$H+}

uses

Classes

{ add your units here };

Var

myint : integer;

thisno, thatno : integer;

result: real;

Begin

end.

Input part 4 Now we have somewhere to store out input we need to get it. First ask the user to enter something (and what data type they are to enter). Then tell the computer to read the input. As this example keeps the question and input on one line you need to write a blank “writeln” to the screen to move down to a new line. Now output some text and the number input. program Project1; {$mode objfpc}{$H+} uses Classes { add your units here }; Var myint : integer; Begin write(‘Give number: ‘); read(myint); writeln(‘’); writeln(‘got: ‘, myint); end.

Now we have somewhere to store out input we need to get it.

First ask the user to enter something (and what data type they are to enter).

Then tell the computer to read the input.

As this example keeps the question and input on one line you need to write a blank “writeln” to the screen to move down to a new line.

Now output some text and the number input.

program Project1;

{$mode objfpc}{$H+}

uses

Classes

{ add your units here };

Var

myint : integer;

Begin

write(‘Give number: ‘);

read(myint);

writeln(‘’);

writeln(‘got: ‘, myint);

end.

Input part 5 Finally don’t forget that you need to keep the command window open. We do this by asking the user to type in a number then press enter. Begin write(‘Give number: ’); read(myint); writeln(‘’); writeln(‘got: ’, myint); writeln(‘’); writeln(‘give num then press enter’); read(myint); end.

Finally don’t forget that you need to keep the command window open.

We do this by asking the user to type in a number then press enter.

Begin

write(‘Give number: ’);

read(myint);

writeln(‘’);

writeln(‘got: ’, myint);

writeln(‘’);

writeln(‘give num then press enter’);

read(myint);

end.

Exercise A Have a go at altering the output text adding extra text and outputting variables. Ask the user for two numbers and display them as follows: Give me the first number: 4 Give me the second number: 3 The numbers in reverse order are: 3 4 Input by user Input numbers shown in reverse order

Have a go at altering the output text adding extra text and outputting variables.

Ask the user for two numbers and display them as follows:

Give me the first number: 4

Give me the second number: 3

The numbers in reverse order are:

3 4

Data (variable) types Pascal supports FOUR standard variable types, which are Integer (whole numbers e.g. 3 6 294) Char (character e.g. ‘b’ ‘n’ ‘4’ ‘&’) Boolean (true or false) real (floating point numbers with decimal point/fractions) Standard Pascal does not make provision for the string data type, but most modern compilers do. Strings covered later.

Pascal supports FOUR standard variable types, which are

Integer (whole numbers e.g. 3 6 294)

Char (character e.g. ‘b’ ‘n’ ‘4’ ‘&’)

Boolean (true or false)

real (floating point numbers with decimal point/fractions)

Standard Pascal does not make provision for the string data type, but most modern compilers do. Strings covered later.

Variable Declaration Variable declaration before application code starts. Declare an integer, character real/floating point number. Start the application. Set the variables. Output the contents of the variables. End the application var number1: integer; letter : char; money : real; begin number1 := 34; letter := 'Z'; money := 32.345; writeln( ‘number: ’, number1 ); writeln( ‘letter: ’, letter ); writeln( ‘money: ’, money ); end.

Variable declaration before application code starts.

Declare an integer, character real/floating point number.

Start the application.

Set the variables.

Output the contents of the variables.

End the application

var

number1: integer;

letter : char;

money : real;

begin

number1 := 34;

letter := 'Z';

money := 32.345;

writeln( ‘number: ’, number1 );

writeln( ‘letter: ’, letter );

writeln( ‘money: ’, money );

end.

Mathematics The main use of computers and their for programming in the early days (just before they made the first computer game) was for scientific and mathematic calculations. Mathematics in Pascal uses the following symbols: Div is used when you want an integer result for division. All the other symbols are the same for all numerical data types Be careful about your data type / Divide (possible decimal point answer) Div Divide (whole number result) * multiply - Subtract + Add

The main use of computers and their for programming in the early days (just before they made the first computer game) was for scientific and mathematic calculations.

Mathematics in Pascal uses the following symbols:

Div is used when you want an integer result for division. All the other symbols are the same for all numerical data types

Be careful about your data type

Mathematics examples Addition Subtraction Multiplication Division (integer) Division (real) Myint := thisint + thatint; Myint := thisint - thatint; Myint := thisint * thatint; Myint := thisint div thatint; MyReal := thisint / thatint;

Addition

Subtraction

Multiplication

Division (integer)

Division (real)

Myint := thisint + thatint;

Myint := thisint - thatint;

Myint := thisint * thatint;

Myint := thisint div thatint;

MyReal := thisint / thatint;

Exercise B Write code to take two numbers input. Add them together displaying the result. Multiply them displaying the result. Divide them displaying the result. Subtract them displaying the result.

Write code to take two numbers input.

Add them together displaying the result.

Multiply them displaying the result.

Divide them displaying the result.

Subtract them displaying the result.

User defined Data types Often it is important to define your own data type to provide only a set number of possibilities Useful for effective usage of memory (RAM) when working with a string that can only be one of a small number of choices. Good for preventing errors (only allowed data items can be used). Known as Enumerated variables which are defined by the programmer. You first create the set of symbols, and assign to them a new data type variable name.

Often it is important to define your own data type to provide only a set number of possibilities

Useful for effective usage of memory (RAM) when working with a string that can only be one of a small number of choices.

Good for preventing errors (only allowed data items can be used).

Known as Enumerated variables which are defined by the programmer.

You first create the set of symbols, and assign to them a new data type variable name.

Enumerated Variables Type beverage = ( coffee, tea, cola, soda, milk, water ); colour = ( green, yellow, blue, black, white ); Var drink : beverage; chair : colour; drink := coffee; chair := green; if chair = yellow then drink := tea; Define beverage as being one of the named items Define colour as being one of the named items Define drink as a beverage Define chair as colour (even though this is only one possible attribute) Assign values to the variables

Type

beverage = ( coffee, tea, cola, soda, milk, water );

colour = ( green, yellow, blue, black, white );

Var

drink : beverage;

chair : colour;

drink := coffee;

chair := green;

if chair = yellow then drink := tea;

Strings Often a single character is insufficient for any/most text based work. Characters can be put together or strung together to allow for words and other text objects to be stored. Strings aren’t a standard data type but are included here as they are common. And are included with most compilers. Strings historically use arrays (covered later).

Often a single character is insufficient for any/most text based work.

Characters can be put together or strung together to allow for words and other text objects to be stored.

Strings aren’t a standard data type but are included here as they are common. And are included with most compilers.

Strings historically use arrays (covered later).

String example Starting code as normal Declare string variable Begin application Assign string Output string variable Output string from code Read an input (to hold application window open till enter pressed). program Project1; {$mode objfpc}{$H+} uses Classes { add your units here }; var mystr : string; begin mystr:= 'fred'; write (mystr); writeln (' is cool'); readln; //takes input end.

Starting code as normal

Declare string variable

Begin application

Assign string

Output string variable

Output string from code

Read an input (to hold application window open till enter pressed).

program Project1;

{$mode objfpc}{$H+}

uses

Classes

{ add your units here };

var

mystr : string;

begin

mystr:= 'fred';

write (mystr);

writeln (' is cool');

readln; //takes input

end.

Constants The last type of variable to look at now is one that doesn’t change (more will be seen later such as Arrays). What is the point of a variable that doesn’t change? Things like pi and other mathematical values don’t ever change but you may need to define them for your application. Things like VAT rate that rarely change (this isn’t the best example) Why not use a normal variable? Secures your data from errors (code mistakes will show up when they try to change the value of pi [more useful than you realise at first]).

The last type of variable to look at now is one that doesn’t change (more will be seen later such as Arrays).

What is the point of a variable that doesn’t change?

Things like pi and other mathematical values don’t ever change but you may need to define them for your application.

Things like VAT rate that rarely change (this isn’t the best example)

Why not use a normal variable?

Secures your data from errors (code mistakes will show up when they try to change the value of pi [more useful than you realise at first]).

Constants example Normal stuff Constant declaration Name Data type Value Begin application Output text & constant Read a line to keep application open End application program Project1; {$mode objfpc}{$H+} uses Classes { add your units here }; const pi : real = 3.141 ; begin writeln ('pi is:', pi); readln; //takes any character end.

Normal stuff

Constant declaration

Name

Data type

Value

Begin application

Output text & constant

Read a line to keep application open

End application

program Project1;

{$mode objfpc}{$H+}

uses

Classes

{ add your units here };

const

pi : real = 3.141 ;

begin

writeln ('pi is:', pi);

readln; //takes any character

end.

Conditions & Iteration Sometimes the computer has to make decisions based on what is happening. For this we use conditions e.g.: If Case Often in code it is useful/necessary to use iteration to repeat an instruction 2 or more times (potentially infinitely). For this we use iteration e.g.: While For

Sometimes the computer has to make decisions based on what is happening. For this we use conditions e.g.:

If

Case

Often in code it is useful/necessary to use iteration to repeat an instruction 2 or more times (potentially infinitely). For this we use iteration e.g.:

While

For

Often in life we have to make simple decisions like: If hungry then eat If thirsty then drink If bored with lesson then talk to the person next to you In computer programs we need to make decisions and for these we use the “IF” statement. If   exp1   Then begin Statment1; Statment2; end End ; If this then that Statements to be executed This “begin” and “end” marks the start and end of the subsection of code. This end marks the “end” of the “if” statement. This is a logical expression/test with a true or false outcome.

Often in life we have to make simple decisions like:

If hungry then eat

If thirsty then drink

If bored with lesson then talk to the person next to you

In computer programs we need to make decisions and for these we use the “IF” statement.

If   exp1   Then begin

Statment1;

Statment2;

end

End ;

The If..then statement Start off as previously with a new program. We will need to create an integer variable and get an input from the user (see previous slides for details on that). Don’t forget that we don’t want the window to close before we have finished. program Project1; {$mode objfpc}{$H+} uses Classes { add your units here }; Begin end.

Start off as previously with a new program.

We will need to create an integer variable and get an input from the user (see previous slides for details on that).

Don’t forget that we don’t want the window to close before we have finished.

program Project1;

{$mode objfpc}{$H+}

uses

Classes

{ add your units here };

Begin

end.

The If..then statement 2 The first thing we want to do is get the program to make a simple decision for us. To make life easy all we want to do is output a line of text if the number entered is 10. Any ideas? program Project1; {$mode objfpc}{$H+} uses Classes { add your units here }; Var myint : integer; Begin write(‘Give number: ‘); read(myint); writeln(‘type in a number and press enter’); read(myint); end.

The first thing we want to do is get the program to make a simple decision for us.

To make life easy all we want to do is output a line of text if the number entered is 10.

Any ideas?

program Project1;

{$mode objfpc}{$H+}

uses

Classes

{ add your units here };

Var

myint : integer;

Begin

write(‘Give number: ‘);

read(myint);

writeln(‘type in a number and press enter’);

read(myint);

end.

The If..then statement 3 Can you see how the comparison works? If the value in “myint” is equal to 10 then the statement(s) between the extra “begin” and “end” are executed. Any other value to “myint” and nothing happens. begin write(‘Give number: ‘); read(myint); if myint = 10 then begin writeln(‘Ten’); end end; writeln(‘type in a number and press enter’); read(myint); end;

Can you see how the comparison works?

If the value in “myint” is equal to 10 then the statement(s) between the extra “begin” and “end” are executed.

Any other value to “myint” and nothing happens.

begin

write(‘Give number: ‘);

read(myint);

if myint = 10 then begin

writeln(‘Ten’);

end

end;

writeln(‘type in a number and press enter’);

read(myint);

end;

The If..then..else statement Sometimes you want to do one of two things depending on the situation e.g.: if tired then stay in and watch DVD else go clubbing . Once again this is common in programming. Be careful with the semi colons (don’t use on these subroutines) if myint = 10 then begin writeln(‘Ten’); end Else begin writeln(‘not ten’); end end;

Sometimes you want to do one of two things depending on the situation e.g.: if tired then stay in and watch DVD else go clubbing .

Once again this is common in programming.

Be careful with the semi colons (don’t use on these subroutines)

if myint = 10 then begin

writeln(‘Ten’);

end

Else begin

writeln(‘not ten’);

end

end;

The If..then..else if statement Occasionally we are fussy beyond belief and we let a single thing control our life e.g.: if very tired then go to bed else if a bit tired watch DVD else go clubbing . if myint = 10 then begin writeln(‘Ten’); end Else if myint <10 then begin writeln(‘Less than Ten’); end Else begin writeln(‘more than Ten’); end end;

Occasionally we are fussy beyond belief and we let a single thing control our life e.g.: if very tired then go to bed else if a bit tired watch DVD else go clubbing .

if myint = 10 then begin

writeln(‘Ten’);

end

Else if myint <10 then begin

writeln(‘Less than Ten’);

end

Else begin

writeln(‘more than Ten’);

end

end;

Exercise C Write an application (using if) to take a number input and output if the number is: “smaller than 100” “Between 100 and 200” “Bigger than 200”

Write an application (using if) to take a number input and output if the number is:

“smaller than 100”

“Between 100 and 200”

“Bigger than 200”

Messy ifs If you are going to use lots of ifs things can get messy in your code. Imagine the code to convert decimal numbers to text. if myint=10 then begin writeln(‘Ten’); end Else if myint=9 then begin writeln(‘Nine’); end … Else begin writeln(‘Only numbers from 1 to 10’); end end;

If you are going to use lots of ifs things can get messy in your code.

Imagine the code to convert decimal numbers to text.

if myint=10 then begin

writeln(‘Ten’);

end

Else if myint=9 then begin

writeln(‘Nine’);

end



Else begin

writeln(‘Only numbers from 1 to 10’);

end

end;

Case Case can be used to replace a lot of ifs. Start the case similar to the if. Case can only be used for equality and not: < (less than) > (more than) <> (not equal to) case Value of Case-Instance Case-Instance Case-Instance ... Case-Instance end;

Case can be used to replace a lot of ifs.

Start the case similar to the if.

Case can only be used for equality and not:

< (less than)

> (more than)

<> (not equal to)

case Value of

Case-Instance

Case-Instance

Case-Instance

...

Case-Instance

end;

Case part 2 Our if statement can be solved like this: I have used a lot of careful spacing to keep the appearance of this easy to read. Try adding this code to your application. case myint of 10 : begin writeln(‘Ten’); end; 9 : begin writeln(‘Nine’); end; … 0 : begin writeln(‘Zero’); end end;

Our if statement can be solved like this:

I have used a lot of careful spacing to keep the appearance of this easy to read.

Try adding this code to your application.

case myint of

10 : begin

writeln(‘Ten’);

end;

9 : begin

writeln(‘Nine’);

end;



0 : begin

writeln(‘Zero’);

end

end;

Case part 3 Often you may be given something that doesn’t fit what your conditions are. In these cases we use “otherwise”. case myint of 10 : begin writeln(‘Ten’); end; … 0 : begin writeln(‘Zero’); end; otherwise begin writeln(‘0 – 10 only'); end end;

Often you may be given something that doesn’t fit what your conditions are. In these cases we use “otherwise”.

case myint of

10 : begin

writeln(‘Ten’);

end;



0 : begin

writeln(‘Zero’);

end;

otherwise begin

writeln(‘0 – 10 only');

end

end;

Exercise D Rewrite the following if statements as a Case statement. You will have to get an input to store in “flag” from the user. Don’t forget to produce an output of “number”. if flag = 1 then begin number := 10; end; else if flag = 2 then begin number := 20 ; end; else if flag = 3 then begin number := 40 ; end; else begin writeln(‘ERROR’); end end;

Rewrite the following if statements as a Case statement.

You will have to get an input to store in “flag” from the user.

Don’t forget to produce an output of “number”.

if flag = 1 then begin number := 10; end;

else if flag = 2 then begin number := 20 ; end;

else if flag = 3 then begin number := 40 ; end;

else begin writeln(‘ERROR’); end

end;

For statement Repeats an action a specified number of times i is an intiger. for i := 1 to 10 do begin //count from 1 till 10 write(i, ‘ ’); end; Produces: 1 2 3 4 5 6 7 8 9 10 Start number End number Count up to

Repeats an action a specified number of times

i is an intiger.

for i := 1 to 10 do begin //count from 1 till 10

write(i, ‘ ’);

end;

Produces:

1 2 3 4 5 6 7 8 9 10

Exercise E Using for write an application to produce the output: 1 2 3 4 5 6 7 8 Using for write an application to produce the output: 1 22 333 4444 55555

Using for write an application to produce the output:

1 2 3 4 5 6 7 8

Using for write an application to produce the output:

1

22

333

4444

55555

While statement Repeats instructions while a condition is met see example below. One advantage of this is that the number of times the instruction is to be repeated doesn’t have to be specified when the loop starts, it continues till the condition is met. while myint < 20 do begin writeln(‘Still not 20.. Adding 1'); myint := myint + 1; end; Repeat this while “myint” is less than 20

Repeats instructions while a condition is met see example below.

One advantage of this is that the number of times the instruction is to be repeated doesn’t have to be specified when the loop starts, it continues till the condition is met.

while myint < 20 do begin

writeln(‘Still not 20.. Adding 1');

myint := myint + 1;

end;

Exercise F Write a while loop to display the following output: A B C D E F Write a while loop to produce the below output: 1 2 3 4 5 6 Write a while loop to ask a user to enter a number till they enter a number over 20

Write a while loop to display the following output:

A B C D E F

Write a while loop to produce the below output:

1 2 3 4 5 6

Write a while loop to ask a user to enter a number till they enter a number over 20

Records A record is a collection of data items/variables. Essentially this is like a record in a database. An example record could be a person with attributes which you can look at, change or manipulate e.g. name, height, age, gender.

A record is a collection of data items/variables.

Essentially this is like a record in a database.

An example record could be a person with attributes which you can look at, change or manipulate e.g. name, height, age, gender.

Record example part 1 Define a record similar to other enumerated data types. Define the data types within the record. End the type definition Declare two variables of type “Person” Type Person = record Name : string; Age : integer; City, State : String;   end; var fred : Person; garry: Person;

Define a record similar to other enumerated data types.

Define the data types within the record.

End the type definition

Declare two variables of type “Person”

Type

Person = record

Name : string;

Age : integer;

City, State : String;

  end;

var

fred : Person;

garry: Person;

Record example part 2 Begin application Assign some variables Output the text strings Output the two ages added together Read a character to keep application open begin fred.Name := 'fred'; garry.Name:= 'gary'; fred.Age := 20; garry.Age := 30; write(fred.name, ' and '); write(garry.name); write(' combined age: '); write(fred.Age + garry.Age); readln; //takes any character end. fred and garry combined age: 50 Output:

Begin application

Assign some variables

Output the text strings

Output the two ages added together

Read a character to keep application open

begin

fred.Name := 'fred';

garry.Name:= 'gary';

fred.Age := 20;

garry.Age := 30;

write(fred.name, ' and ');

write(garry.name);

write(' combined age: ');

write(fred.Age + garry.Age);

readln; //takes any character

end.

Exercise G Write an application to create 3 records storing the following aspects of people: Name Age Gender Nationality Ask a user to enter this information Output the name of the oldest person

Write an application to create 3 records storing the following aspects of people:

Name

Age

Gender

Nationality

Ask a user to enter this information

Output the name of the oldest person

Arrays Suppose you wanted to read in 5000 integers and do something with them. How would you store the integers? You could use 5000 variables… Int1, int2, int3, int4 ……… int5000 : integer; Slow to type and wrist ache by about int1248 And that’s before assigning values An array contains several storage spaces, all the same type. You refer to each storage space with the array name and with an id number. The type definition is: type noarray = array [1..50] of integer;

Suppose you wanted to read in 5000 integers and do something with them. How would you store the integers?

You could use 5000 variables…

Int1, int2, int3, int4 ……… int5000 : integer;

Slow to type and wrist ache by about int1248

And that’s before assigning values

An array contains several storage spaces, all the same type. You refer to each storage space with the array name and with an id number. The type definition is:

type

noarray = array [1..50] of integer;

Array example Type definition Variable declaration type noarray = array [1..10] of integer; var myarray : noarray; i : integer; Continues next slide…

Type definition

Variable declaration

type

noarray = array [1..10] of integer;

var

myarray : noarray;

i : integer;

Continues next slide…

Array example part 2 Start application Assign variables to array locations 1 - 5 begin myarray[1] := 6; myarray[2] := 3; myarray[3] := 10; myarray[4] := 14; myarray[5] := 16; Continues next slide…

Start application

Assign variables to array locations 1 - 5

begin

myarray[1] := 6;

myarray[2] := 3;

myarray[3] := 10;

myarray[4] := 14;

myarray[5] := 16;

Continues next slide…

Array example part 3 Use for loop to assign remaining variables Note: not starting from 1 Note use of “i” to address array location Output array contents using for loop readln to prevent application from closing. for i:= 6 to 10 do begin myarray[i]:= 1; end; for i:=1 to 10 do begin write('myarray pos: '); write(i); write(': '); write(myarray[i]); writeln(''); end; readln; //takes any character end.

Use for loop to assign remaining variables

Note: not starting from 1

Note use of “i” to address array location

Output array contents using for loop

readln to prevent application from closing.

for i:= 6 to 10 do begin

myarray[i]:= 1;

end;

for i:=1 to 10 do begin

write('myarray pos: ');

write(i);

write(': ');

write(myarray[i]);

writeln('');

end;

readln; //takes any character

end.

Array example output myarray pos: 1: 6 myarray pos: 2: 3 myarray pos: 3: 10 myarray pos: 4: 14 myarray pos: 5: 16 myarray pos: 6: 1 myarray pos: 7: 1 myarray pos: 8: 1 myarray pos: 9: 1 myarray pos: 10: 1

myarray pos: 1: 6

myarray pos: 2: 3

myarray pos: 3: 10

myarray pos: 4: 14

myarray pos: 5: 16

myarray pos: 6: 1

myarray pos: 7: 1

myarray pos: 8: 1

myarray pos: 9: 1

myarray pos: 10: 1

Exercise H Use an array to take in 10 numbers from a user. Output the largest number Output the smallest number Output the average number

Use an array to take in 10 numbers from a user.

Output the largest number

Output the smallest number

Output the average number

Multi dimensional arrays So far we have seen arrays with one direction (1 – 10 in the example). You can have more than one dimension if you wish. This is good for tables, grids and games. type StatusType = (X, O, Blank); BoardType = array[1..3,1..3] of StatusType; var Board : BoardType; Board[1,1]:= ‘X’

So far we have seen arrays with one direction (1 – 10 in the example).

You can have more than one dimension if you wish.

This is good for tables, grids and games.

type

StatusType = (X, O, Blank);

BoardType = array[1..3,1..3] of StatusType;

var

Board : BoardType;

Board[1,1]:= ‘X’

More dimensions If you have a need or are just completely mad an Array can have more dimensions than you can draw. All you have to do is add more commas in the declaration: Myarray : [1..10, 1..10, 1..10…] of arraytype; This idea was used/discussed in the cult film “cube 2: hypercube” See right for a tesseract (hypercube) multi dimensional square

If you have a need or are just completely mad an Array can have more dimensions than you can draw.

All you have to do is add more commas in the declaration:

Myarray : [1..10, 1..10, 1..10…] of arraytype;

This idea was used/discussed in

the cult film “cube 2: hypercube”

See right for a tesseract

(hypercube) multi dimensional

square

Procedures & Functions Procedures and Functions are stand alone code that can be “called” from any other code to perform a task. Functions always return a value (of a predefined type). Both can (and often do) take arguments (data items) eg: Procedure DoSomething (Para : String);   begin     Writeln (’Got parameter : ’,Para);     Writeln (’Parameter in upper case : ’,Upper(Para));   end; Procedures are used for buttons in Lazarus. Argument variable name use within this function Data type

Procedures and Functions are stand alone code that can be “called” from any other code to perform a task.

Functions always return a value (of a predefined type).

Both can (and often do) take arguments (data items) eg:

Procedure DoSomething (Para : String);   begin     Writeln (’Got parameter : ’,Para);     Writeln (’Parameter in upper case : ’,Upper(Para));   end;

Procedures are used for buttons in Lazarus.

Procedures & Functions (comparison) Taken from AQA mark scheme: function returns a value // function has a (data) type // function appears in an expression // function appears on the RHS (Right Hand Side) of an assignment statement; procedure does not have to return a value // procedure forms a statement on its own;

Taken from AQA mark scheme:

function returns a value // function has a (data) type //

function appears in an expression //

function appears on the RHS (Right Hand Side) of an assignment statement;

procedure does not have to return a value //

procedure forms a statement on its own;

Function example Take 2 numbers and add them together returning the result (It is trivial but demonstrates the idea). function myadd(x, y : integer) : integer ; begin myadd := x + y; end; var num1, num2, num3: integer; Standard variable declaration Define that this is a function Give it a name Data & data types to be passed to function (names for internal use) all within brackets. Data type of return value Begin & end of function The return of the function is decided by assigning a value to a variable, which has to be the name of the function.

Take 2 numbers and add them together returning the result (It is trivial but demonstrates the idea).

function myadd(x, y : integer) : integer ;

begin

myadd := x + y;

end;

var

num1, num2, num3: integer;

Function example part 2 Call the function begin num1 := 2; num2 := 3; num3 := myadd(num1, num2); writeln (‘solution: ’, num3); end.

Call the function

begin

num1 := 2;

num2 := 3;

num3 := myadd(num1, num2);

writeln (‘solution: ’, num3);

end.

Exercise I Write an application that takes in two numbers Using a procedure produce a welcome message Using a function add the two numbers together outputting the result Using a function multiply the two numbers outputting the result

Write an application that takes in two numbers

Using a procedure produce a welcome message

Using a function add the two numbers together outputting the result

Using a function multiply the two numbers outputting the result

Binary converter example This application converts from decimal to binary and from binary to decimal. Simple but uses lots of aspects of programming in Pascal.

This application converts from decimal to binary and from binary to decimal.

Simple but uses lots of aspects of programming in Pascal.

program binary(input,output); uses Classes; procedure main;forward; // tell compiler that procedure //exists as it is called before it is declared in code const //Define constants (these don't change) {these allow for the application to be easily converted to

  • perform different conversions} eight : integer =128; //value of highest column bit : integer =8; //how many bit binary to work with lastcol : integer =1; //what the value of the last column is maxno : integer =255; //what the largest number to convert is

    program binary(input,output);

    uses

    Classes;

    procedure main;forward; // tell compiler that procedure

    //exists as it is called before it is declared in code

    const //Define constants (these don't change)

    {these allow for the application to be easily converted to
  • perform different conversions}

    eight : integer =128; //value of highest column

    bit : integer =8; //how many bit binary to work with

    lastcol : integer =1; //what the value of the last column is

    maxno : integer =255; //what the largest number to convert is

    procedure tobinary; Var //variables only local to procedure number:integer; column:integer; row:integer; Begin //begin procedure column:=eight; number:=maxno+1; {set number to one more than the maximum allowed to invoke the below loop} while (number >maxno) or (number <0) do //gets run first time begin writeln ('the number must be between ',maxno,' and 0'); write ('enter the number to convert to binary : '); readln (number); //takes input from 1 - 255 end; writeln ('your number has been converted to ',bit,' bit binary');

    procedure tobinary;

    Var //variables only local to procedure

    number:integer;

    column:integer;

    row:integer;

    Begin //begin procedure

    column:=eight;

    number:=maxno+1; {set number to one more than the maximum allowed to invoke the below loop}

    while (number >maxno) or (number <0) do //gets run first time

    begin

    writeln ('the number must be between ',maxno,' and 0');

    write ('enter the number to convert to binary : ');

    readln (number); //takes input from 1 - 255

    end;

    writeln ('your number has been converted to ',bit,' bit binary');

    write (number,'='); while (column >=lastcol) do //while not on the last column begin if (number >= column) then begin write ('1'); number:=number-column; end else begin write ('0'); end; column:=column div 2 end; writeln (''); //put in line break end; //procedure

    write (number,'=');

    while (column >=lastcol) do //while not on the last column

    begin

    if (number >= column) then

    begin

    write ('1');

    number:=number-column;

    end

    else

    begin

    write ('0');

    end;

    column:=column div 2

    end;

    writeln (''); //put in line break

    end; //procedure

    procedure tonumber; Var //local variables column:integer; number:integer; binary:integer; Begin //procedure column:=eight; number:=0; writeln ('enter the numbers from left to right'); while (column >=lastcol) do begin write ('enter the number in the ',column,' column : '); readln (binary); if (binary = 1) or (binary = 0) then begin number:=number+(column*binary); column:=column div 2 end else begin writeln ('error/...you must enter a value of 1 or 0'); end; end; writeln ('the total of the binary entered is : ',number); end; //procedure

    procedure tonumber;

    Var //local variables

    column:integer;

    number:integer;

    binary:integer;

    Begin //procedure

    column:=eight;

    number:=0;

    writeln ('enter the numbers from left to right');

    while (column >=lastcol) do

    begin

    write ('enter the number in the ',column,' column : ');

    readln (binary);

    if (binary = 1) or (binary = 0) then

    begin

    number:=number+(column*binary);

    column:=column div 2

    end

    else

    begin

    writeln ('error/...you must enter a value of 1 or 0');

    end;

    end;

    writeln ('the total of the binary entered is : ',number);

    end; //procedure

    procedure main; Var //internal variable answer:char; begin writeln ('if you want to convert a number to binary type b'); writeln ('if you want to convert binary to a number type n'); readln (answer); if (answer = 'b') or (answer = 'B') then tobinary //run tobinary procedure else if (answer = 'n') or (answer = 'N') then tonumber //run tonumber procedure else //give error message writeln ('error/... you have to type in b or n') end;

    procedure main;

    Var //internal variable

    answer:char;

    begin

    writeln ('if you want to convert a number to binary type b');

    writeln ('if you want to convert binary to a number type n');

    readln (answer);

    if (answer = 'b') or (answer = 'B') then

    tobinary //run tobinary procedure

    else if (answer = 'n') or (answer = 'N') then

    tonumber //run tonumber procedure

    else //give error message

    writeln ('error/... you have to type in b or n')

    end;

    Var //application wide variable reply:char; Begin //application main; //call main procedure writeln ('please type any key then press enter to quit'); readln; //prevent window from closing end. //application

    Var //application wide variable

    reply:char;

    Begin //application

    main; //call main procedure

    writeln ('please type any key then press enter to quit');

    readln; //prevent window from closing

    end. //application

    Var //application wide variable reply:char; Begin //application main; //call main procedure writeln ('please type any key then press enter to quit'); readln; //prevent window from closing end. //application

    Var //application wide variable

    reply:char;

    Begin //application

    main; //call main procedure

    writeln ('please type any key then press enter to quit');

    readln; //prevent window from closing

    end. //application

    Lazarus & GUI After some time of looking at command line programming it feels evident that anything reflecting the type of application that you are used to using feels 100 million miles away. Fortunately you don’t have to write all the code to draw the pretty pictures and boxes on the screen. The GUI components have been held back to keep things simple. Now on to Windows, Icons, Menus and Pointers for the WIMPs out there.

    After some time of looking at command line programming it feels evident that anything reflecting the type of application that you are used to using feels 100 million miles away.

    Fortunately you don’t have to write all the code to draw the pretty pictures and boxes on the screen.

    The GUI components have been held back to keep things simple.

    Now on to Windows, Icons, Menus and Pointers for the WIMPs out there.

    First GUI application Since we have covered the code basics most of this is just point and click. The aim is to make an application to do the following: Take two inputs Provide a button to add them together displaying the result in a third box Provide a button to subtract them displaying the result in a third box Provide a button to divide them displaying the result in a third box Provide a button to divide them displaying the result in a third box

    Since we have covered the code basics most of this is just point and click.

    The aim is to make an application to do the following:

    Take two inputs

    Provide a button to add them together displaying the result in a third box

    Provide a button to subtract them displaying the result in a third box

    Provide a button to divide them displaying the result in a third box

    Provide a button to divide them displaying the result in a third box

    Appearance addbtn subbtn multbtn divbtn output1 input2 input1 Starting code on next slide (all created by Lazarus)

    Starting code on next slide (all created by Lazarus)

    Starting code unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, StdCtrls, Buttons; Type { TForm1 } TForm1 = class(TForm) addbtn: TButton; Label1: TLabel; subbtn: TButton; multbtn: TButton; divbtn: TButton; input1: TEdit; input2: TEdit; output1: TEdit; private { private declarations } public { public declarations } end; var Form1: TForm1; implementation { TForm1 } initialization {$I unit1.lrs} end.

    unit Unit1;

    {$mode objfpc}{$H+}

    interface

    uses

    Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, StdCtrls, Buttons;

    Type

    { TForm1 }

    TForm1 = class(TForm)

    addbtn: TButton;

    Label1: TLabel;

    subbtn: TButton;

    multbtn: TButton;

    divbtn: TButton;

    input1: TEdit;

    input2: TEdit;

    output1: TEdit;

    private

    { private declarations }

    public

    { public declarations }

    end;

    var

    Form1: TForm1;

    implementation

    { TForm1 }

    initialization

    {$I unit1.lrs}

    end.

    Drag & drop Click on button to select “button” Drag and drop button on form Object inspector used to change properties

    Edit properties Change “text” property to change the default contents Look at other properties for ideas Commonly used properties are displayed under “favourites” Don’t forget to find the “name” property to give each item a memorable name (see the slide with the boxes & buttons labelled for ideas Events are used for things like “on click”

    Make a button work Select the button you want to give a function to. Go to the “Events” section of the object browser. Find “OnClick” and select it Click the button with three dots to the end of it Lazarus will create code in the source editor. All we are interested in is between: procedure TForm1.addbtnClick(Sender: TObject); begin And the: End;

    Select the button you want to give a function to.

    Go to the “Events” section of the object browser.

    Find “OnClick” and select it

    Click the button with three dots to the end of it

    Lazarus will create code in the source editor. All we are interested in is between:

    procedure TForm1.addbtnClick(Sender: TObject);

    begin

    And the:

    End;

    Code to make things happen Declare some local variables (between the procedure declaration and the “begin”. var num1, num2, num3 : integer; Copy the contents of the two input boxes to the first to integers: num1 := strtoint(input1.Text); num2 := strtoint(input2.Text); Now we are ready to do some maths work Use a function to convert string to integer Just like calling the contents of a record

    Declare some local variables (between the procedure declaration and the “begin”.

    var

    num1, num2, num3 : integer;

    Copy the contents of the two input boxes to the first to integers:

    num1 := strtoint(input1.Text);

    num2 := strtoint(input2.Text);

    Now we are ready to do some maths work

    Maths & Output num3 := num1 + num2; //normal Pascal addition Output1.Text := inttostr(num3); Just like setting contents of record Function to convert integer to string

    num3 := num1 + num2; //normal Pascal addition

    Output1.Text := inttostr(num3);

    Compile and run Your application will now add two numbers together. To extend the application just repeat the steps to add functionality to the other buttons. Tip… you may wish to use real numbers for the division result (or any others). In which case you need to use these functions: Floattostr() Strtofloat()

    Your application will now add two numbers together.

    To extend the application just repeat the steps to add functionality to the other buttons.

    Tip… you may wish to use real numbers for the division result (or any others). In which case you need to use these functions:

    Floattostr()

    Strtofloat()

    Going further GUI programming is a combination of normal Pascal programming and manipulating the properties of objects (which behave just like records). Manipulating objects (or rather instances of objects) is all about changing properties. Providing you supply the correct data type the world is your oyster.

    GUI programming is a combination of normal Pascal programming and manipulating the properties of objects (which behave just like records).

    Manipulating objects (or rather instances of objects) is all about changing properties. Providing you supply the correct data type the world is your oyster.

    More information Further tuition (online instructions etc…) can be found here: http://www.taoyue.com/tutorials/pascal/ Lazarus is available from here: http://www.lazarus.freepascal.org/ Lazarus tutorials & more: http://wiki.lazarus.freepascal.org/Lazarus_Tutorial

    Further tuition (online instructions etc…) can be found here:

    http://www.taoyue.com/tutorials/pascal/

    Lazarus is available from here:

    http://www.lazarus.freepascal.org/

    Lazarus tutorials & more:

    http://wiki.lazarus.freepascal.org/Lazarus_Tutorial

Add a comment

Related presentations

Related pages

COMP 20: Web Programming - tuftsdev.github.io

COMP 20: Web Programming Tufts University Department of Computer Science, Fall 2016 Instructor. Ming Chow, mchow@cs.tufts.edu; Office Hours: Wednesdays ...
Read more

Computer programming - Wikipedia

Computer programming (often shortened to programming) is a process that leads from an original formulation of a computing problem to executable computer ...
Read more

Intro to Programming - UNC Comp 110

Spring UTA Application Form. Wednesday, November 16th. Help introduce programming to your fellow Tar Heels by joining the COMP110 Undergraduate Teaching ...
Read more

Programming Camps | Code Classes Kids & Teens | iD Tech

Summer coding camp with app development & programming courses for kids & teens. Learn with Minecraft, Java, C++, HTML5, iOS, Xcode & more. View courses.
Read more

Programming Competition,Programming Contest,Online ...

Programming Competition: Join Online Programming Contest. CodeChef hosts Online Programming Competition, Programming Contest and Computer Programming
Read more

Comp105 -- Programming Languages

Topics. In rough chronological order: Abstract syntax and operational semantics; Functional programming with lists and recursion; First-class and higher ...
Read more

Programming language - Wikipedia

A programming language is a formal computer language designed to communicate instructions to a machine, particularly a computer. Programming languages can ...
Read more

Welcome to Python.org

Official site for the interpreted, interactive, object-oriented, extensible programming language. Includes news, documentation, free downloads, and ...
Read more

MyProgrammingLab | Pearson

MyProgrammingLab Sign In Register: Student Register: Educator Support Educator Training & Support Student Support System Requirements Educators ...
Read more