SlideShare a Scribd company logo
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
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
Lazarus 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.
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.
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
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.
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.
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.
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.
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.
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
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);
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.
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.
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.
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.
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.
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
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.
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.
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
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;
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.
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.
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
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).
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.
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]).
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.
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
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.
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.
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 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;
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;
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;
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”
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;
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 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;
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;
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;
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
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
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
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
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.
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;
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:
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
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;
Array example 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…
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.
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
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
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’
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
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 & 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;
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.
Function example part 2 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
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.
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');
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  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
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.
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
Appearance addbtn subbtn multbtn divbtn output1 input2 input1 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.
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;
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
Maths & Output num3 := num1 + num2;  //normal Pascal addition Output1.Text := inttostr(num3); Just like setting contents of record Function to convert integer to string
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()
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.
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

More Related Content

DOCX
CBSE Class 12 Computer practical Python Programs and MYSQL
PDF
Computer Practical
DOCX
Computer Science Practical File class XII
PDF
Cs practical file
PPTX
Introduction to Python Programming
PDF
Object Oriented Programming Using C++ Practical File
PDF
Python-02| Input, Output & Import
PPTX
Python programming workshop session 1
CBSE Class 12 Computer practical Python Programs and MYSQL
Computer Practical
Computer Science Practical File class XII
Cs practical file
Introduction to Python Programming
Object Oriented Programming Using C++ Practical File
Python-02| Input, Output & Import
Python programming workshop session 1

What's hot (20)

PPTX
Python programming –part 3
PPTX
Docase notation for Haskell
PPTX
Algorithm analysis and design
PPTX
Python for Beginners(v2)
PPTX
Rx workshop
PPTX
Python programming- Part IV(Functions)
PDF
Python unit 2 as per Anna university syllabus
PPTX
Programming using c++ tool
PDF
PPTX
Loops in Python
PPTX
Python for Data Science
PPTX
C++ theory
PPTX
INTRODUCTION TO FUNCTIONS IN PYTHON
PDF
Functional Programming in F#
PPTX
Operators and Control Statements in Python
PPTX
Python ppt
PPTX
Unit2 input output
PDF
Python lambda functions with filter, map & reduce function
DOCX
Data Structure in C (Lab Programs)
PPTX
Python programming –part 7
Python programming –part 3
Docase notation for Haskell
Algorithm analysis and design
Python for Beginners(v2)
Rx workshop
Python programming- Part IV(Functions)
Python unit 2 as per Anna university syllabus
Programming using c++ tool
Loops in Python
Python for Data Science
C++ theory
INTRODUCTION TO FUNCTIONS IN PYTHON
Functional Programming in F#
Operators and Control Statements in Python
Python ppt
Unit2 input output
Python lambda functions with filter, map & reduce function
Data Structure in C (Lab Programs)
Python programming –part 7
Ad

Viewers also liked (9)

PPT
Programming For As Comp
PPT
Programming For A2 Comp
PPT
Compilation
PPT
Compilation
PPT
Programming For A2 Comp
PDF
The compilation process
PDF
Debugger Principle Overview & GDB Tricks
PPT
Materi -bank-sentral
PPT
How a Compiler Works ?
Programming For As Comp
Programming For A2 Comp
Compilation
Compilation
Programming For A2 Comp
The compilation process
Debugger Principle Overview & GDB Tricks
Materi -bank-sentral
How a Compiler Works ?
Ad

Similar to Programming For As Comp (20)

PPTX
Programming basics
PDF
Tutorial basic of c ++lesson 1 eng ver
PPTX
C++ lecture 01
PPT
intro to programming languge c++ for computer department
PPTX
lecture 2.pptx
PPTX
C++ programming language basic to advance level
PDF
PPT
Help with Pyhon Programming Homework
PPT
keyword
PPT
keyword
PPT
Chapter2
PPTX
Input-output
PPTX
C++ Homework Help
PDF
Maxbox starter
PPT
Introduction to Procedural Programming in C++
DOC
Enrich enriching mathematics conversi biner 16 pada sisikomputerize indoensia...
PPTX
C Programming Unit-1
PDF
C basics programming ppt by Mayanka .pdf
PDF
pyton Notes1
PPT
python fundamental for beginner course .ppt
Programming basics
Tutorial basic of c ++lesson 1 eng ver
C++ lecture 01
intro to programming languge c++ for computer department
lecture 2.pptx
C++ programming language basic to advance level
Help with Pyhon Programming Homework
keyword
keyword
Chapter2
Input-output
C++ Homework Help
Maxbox starter
Introduction to Procedural Programming in C++
Enrich enriching mathematics conversi biner 16 pada sisikomputerize indoensia...
C Programming Unit-1
C basics programming ppt by Mayanka .pdf
pyton Notes1
python fundamental for beginner course .ppt

Recently uploaded (20)

PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Encapsulation theory and applications.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Machine learning based COVID-19 study performance prediction
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
DOCX
The AUB Centre for AI in Media Proposal.docx
Dropbox Q2 2025 Financial Results & Investor Presentation
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
NewMind AI Weekly Chronicles - August'25 Week I
Encapsulation theory and applications.pdf
Encapsulation_ Review paper, used for researhc scholars
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Spectral efficient network and resource selection model in 5G networks
Per capita expenditure prediction using model stacking based on satellite ima...
“AI and Expert System Decision Support & Business Intelligence Systems”
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Review of recent advances in non-invasive hemoglobin estimation
Machine learning based COVID-19 study performance prediction
MYSQL Presentation for SQL database connectivity
Diabetes mellitus diagnosis method based random forest with bat algorithm
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
20250228 LYD VKU AI Blended-Learning.pptx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
The AUB Centre for AI in Media Proposal.docx

Programming For As Comp

  • 1. Programming for AS Computing Using Pascal & Lazarus By David Halliday
  • 2. 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
  • 3. 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
  • 4. Lazarus An IDE (Integrated Development Environment) for Pascal & Delphi. A RAD (Rapid Application Development) tool. Freely available under GNU GPL. Platform independent.
  • 6. 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.
  • 7. 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.
  • 8. 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
  • 9. 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.
  • 10. 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.
  • 11. 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.
  • 12. 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.
  • 13. 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.
  • 14. 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
  • 15. 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);
  • 16. 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.
  • 17. 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.
  • 18. 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.
  • 19. 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.
  • 20. 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.
  • 21. 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
  • 22. 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.
  • 23. 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.
  • 24. 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
  • 25. 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;
  • 26. 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.
  • 27. 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.
  • 28. 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
  • 29. 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).
  • 30. 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.
  • 31. 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]).
  • 32. 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.
  • 33. 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
  • 34. 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.
  • 35. 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.
  • 36. 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.
  • 37. 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;
  • 38. 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;
  • 39. 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;
  • 40. 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”
  • 41. 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;
  • 42. 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;
  • 43. 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;
  • 44. 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;
  • 45. 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;
  • 46. 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
  • 47. 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
  • 48. 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
  • 49. 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
  • 50. 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.
  • 51. 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;
  • 52. 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:
  • 53. 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
  • 54. 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;
  • 55. Array example Type definition Variable declaration type noarray = array [1..10] of integer; var myarray : noarray; i : integer; Continues next slide…
  • 56. 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…
  • 57. 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.
  • 58. 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
  • 59. 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
  • 60. 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’
  • 61. 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
  • 62. 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
  • 63. 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;
  • 64. 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.
  • 65. Function example part 2 Call the function begin num1 := 2; num2 := 3; num3 := myadd(num1, num2); writeln (‘solution: ’, num3); end.
  • 66. 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
  • 67. 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.
  • 68. 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
  • 69. 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');
  • 70. 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
  • 71. 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
  • 72. 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;
  • 73. 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
  • 74. 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
  • 75. 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.
  • 76. 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
  • 77. Appearance addbtn subbtn multbtn divbtn output1 input2 input1 Starting code on next slide (all created by Lazarus)
  • 78. 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.
  • 79. Drag & drop Click on button to select “button” Drag and drop button on form Object inspector used to change properties
  • 80. 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”
  • 81. 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;
  • 82. 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
  • 83. Maths & Output num3 := num1 + num2; //normal Pascal addition Output1.Text := inttostr(num3); Just like setting contents of record Function to convert integer to string
  • 84. 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()
  • 85. 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.
  • 86. 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

Editor's Notes

  • #2: Details of exercises for marking and checking: Exercise A 1. Have a go at altering the output text adding extra text and outputting variables. 2. Ask the user for two numbers and display them as follows: 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. 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” Exercise D Rewrite the following if statements as a Case statement. Exercise E Using for loops write an application to produce the output(s): Exercise F Write a while loop to display the following output: Write a while loop to produce the below output: Write a while loop to ask a user to enter a number till they enter a number over 20 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 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 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