21
A/L 2011_revision. PASCAL PROGRAMMING II page 1 of 8 Basic Structure of a Pascal Program Program FirstProgram; Begin Write('Hello World. Prepare to learn PASCAL!!'); Readln; End. Input / Out Put / Assignment Program InputOutput; Var Num1, Num2, Sum : Integer; Begin {no semicolon} Write('Input number 1:'); Readln(Num1); Writeln('Input number 2:'); Readln(Num2); Sum := Num1 + Num2; {addition} Writeln(Sum); Readln; End. String Variables Program StringOut; Var name, surname: String; Begin Write('Enter your name:'); readln(name); Write('Enter your surname:'); readln(surname); Writeln('Your full name is: ',name,' ',surname); End. Two bytes meet. The first byte asks, “Are you ill?” The second byte replies, “No, just feeling a bit off.”

A/L 2011 revision. PASCAL PROGRAMMING IIPASCAL PROGRAMMING II page 3 of 8 Programming Task 1 TASK Develop a program that reads a number of inches, calculates the equivalent number

  • Upload
    others

  • View
    20

  • Download
    1

Embed Size (px)

Citation preview

Page 1: A/L 2011 revision. PASCAL PROGRAMMING IIPASCAL PROGRAMMING II page 3 of 8 Programming Task 1 TASK Develop a program that reads a number of inches, calculates the equivalent number

A/L 2011_revision. PASCAL PROGRAMMING II

page 1 of 8

Basic Structure of a Pascal ProgramProgram FirstProgram; Begin Write('Hello World. Prepare to learn PASCAL!!'); Readln; End.

Input / Out Put / AssignmentProgram InputOutput;Var Num1, Num2, Sum : Integer;Begin {no semicolon} Write('Input number 1:'); Readln(Num1); Writeln('Input number 2:'); Readln(Num2); Sum := Num1 + Num2; {addition} Writeln(Sum); Readln;End.

String Variables

Program StringOut;Var name, surname: String;Begin Write('Enter your name:'); readln(name); Write('Enter your surname:'); readln(surname); Writeln('Your full name is: ',name,' ',surname);End.

Two bytes meet. The first byte asks, “Are you ill?” The second byte replies, “No, just feeling a bit off.”

Page 2: A/L 2011 revision. PASCAL PROGRAMMING IIPASCAL PROGRAMMING II page 3 of 8 Programming Task 1 TASK Develop a program that reads a number of inches, calculates the equivalent number

A/L 2011_revision. PASCAL PROGRAMMING II

page 2 of 8

Constants Program Constants;Var surname: String; Const {the reserved word 'const' is used to initialize constants} name = 'Niranjan';Begin

Write('Enter your surname:'); readln(surname); Writeln('Your full name is: ',name,' ',surname); Readln;End.

PROGRAM= DATA + ALGORITHM

AlgorithmAn algorithm is a series of step by steps carried out to solve a problem in a finite amount of time.

Problem Solving

The stages in problem solving are as follows:

1. Decide on Data Inputs and types2. Decide on Data Outputs and types3. Decide on Data Processing to produce expected output.4. Design Data Table for the program5. Design the Algorithm for the program6. Development of software.

How many programers dose it take to change a light bulb?None – It’s a hardare problem”

Page 3: A/L 2011 revision. PASCAL PROGRAMMING IIPASCAL PROGRAMMING II page 3 of 8 Programming Task 1 TASK Develop a program that reads a number of inches, calculates the equivalent number

A/L 2011_revision. PASCAL PROGRAMMING II

page 3 of 8

Programming Task 1

TASKDevelop a program that reads a number of inches, calculates the equivalent number in centimetersand displays the number of centimeters. (Note: 1 Inch = 2.54 centimeters).

PROBLEM: InchToCentSystem

Data

NoOfInches – RealNoOfCents - Real;

AlgorithmBegin { CentToInchSystem }Display 'How many inches? 'Get NoOfInchesCalc NoOfCents as NoOfInches * 2.54Display 'Centimetres = ', NoOfCentsEnd { InchToCentSystem }

CODE

Program CentToInchSystem ;

Var NoOfInches : Real; NoOfCents : Real;

BeginWrite (‘How many Inches?’);Readln(NoOfCents);NoOfCents := NoOfInches * 2.54;Writeln ('Centimetres = ', NoOfCents);

End.

Modify this code to Convert Pounds to Kilograms

There are only 10 kinds of people in this world: those who know binary and those who don’t.

Page 4: A/L 2011 revision. PASCAL PROGRAMMING IIPASCAL PROGRAMMING II page 3 of 8 Programming Task 1 TASK Develop a program that reads a number of inches, calculates the equivalent number

A/L 2011_revision. PASCAL PROGRAMMING II

page 4 of 8

PASCAL SCREEN COMMANDS

Reserved Word Description

Clrscr CleaSumscreen

Gotoxy(int,int) Takes the cursor to the pre-defined position

Textbackground(word/int) Background colour

Textcolor(word/int) Colour of text

Readkey Reads a key; Could be assigned to a variable

Delay(int) Waits for the included time(milliseconds)

Halt(parameter) Program terminates

Programming is 10% science, 20% intelligence, and 70% is getting the intelligence to work with the science.

Page 5: A/L 2011 revision. PASCAL PROGRAMMING IIPASCAL PROGRAMMING II page 3 of 8 Programming Task 1 TASK Develop a program that reads a number of inches, calculates the equivalent number

A/L 2011_revision. PASCAL PROGRAMMING II

page 5 of 8

Read and Think Program carhire;Var PD, Dname, Cmodel : String; TotalKM, CostPD, TCostPD, Distance : Real; BeginTCostPD := 0; Writeln('This program prompts you to input the cost per litre of');Writeln('the petrol/diesel you spend in and the average distance you travel');Writeln('with your car every week. Then the computer calculates the total cost');Writeln('you spend in fuel every week.');Readln;Write('Diesel or Petrol?: ');

Readln(PD);Write('Name Of Driver: ');

Readln(Dname);Write('Car Model: ');Readln(Cmodel);Write('Cost of Diesel/Petrol: ($) ');Readln(CostPD);Writeln('Average distance you travel with your car every week: (kilometres) ');Readln(Distance);Writeln;Writeln;Writeln('Name of Driver:',Dname);Writeln('Car Model:',Cmodel);Writeln('Diesel/Petrol:',PD);Writeln('Average distance covered every week: ',Distance:1:2,'Km');Writeln('Cost of ',PD,' per liter: $',CostPD:1:2,'/litre');Writeln;TCostPD := Distance * CostPD;Writeln('Total cost of ',PD,' per week: $',TCostPD:1:2); TCostPD := 0;Writeln('Total cost of ',PD,' per week: $',(Distance * CostPD):1:2); {this}Writeln('Total cost of ',PD,' per week:$’,Distance * CostPD); {and this - without ':1:2'}readln;End.

All programmers are play writers, and all computers are poor actors.

Page 6: A/L 2011 revision. PASCAL PROGRAMMING IIPASCAL PROGRAMMING II page 3 of 8 Programming Task 1 TASK Develop a program that reads a number of inches, calculates the equivalent number

A/L 2011_revision. PASCAL PROGRAMMING II

page 6 of 8

If … Then StatementProgram ifThen;Uses Crt;Label 1; Var Sel: String; N1,N2, Total : Real; YN : Char; {this is a character variable type, which holds single characteSumONLY}Begin1:Clrscr;Total := 0; {always initialise integer/real variables}

GotoXy(4,3);Writeln('1.Addition');GotoXy(4,4);Writeln('2.Subtraction');GotoXy(4,5);

Writeln('3.Exit');GotoXy(6,8);Write('Select: ');Sel := Readkey;If Sel = '1' {action} then

Begin {more than one statement}ClrScr; Write('Input No.1:'); Readln(N1); Write('Input No.2:'); Readln(N2); Total := N1 + N2; Writeln('Addition: ',N1:2:3,' + ',N2:2:3,' = ',Total:2:3); Write('Press any key to continue...'); Readkey;Goto 1;{this leads back to the beginning of the program, otherwise the program terminates}End; {Closing the if statement(begin)}If Sel = '2' then {note that the assignment statement is not used within an if statement}

Begin ClrScr; Write('Input No.1:'); Readln(N1); Write('Input No.2:'); Readln(N2); Total := N1 - N2; Write('Subtraction: '); Write(N1:2:3,' - ',N2:2:3,' = ',Total:2:3);

Page 7: A/L 2011 revision. PASCAL PROGRAMMING IIPASCAL PROGRAMMING II page 3 of 8 Programming Task 1 TASK Develop a program that reads a number of inches, calculates the equivalent number

A/L 2011_revision. PASCAL PROGRAMMING II

page 7 of 8

Write('Press any key to continue...'); Readkey; Goto 1;End; {Closing the if statement}If Sel = '3' then

Begin ClrScr; Write('Are you sure?(Y/N)'); YN := Readkey;If YN = 'y' then Halt; {1 action, so no need of Begin..End}If YN = 'n' then Goto 1; {the goto statement is not recommended for excessive use}End;End.

REPEAT … UNTIL LOOP

Program repeatUNTIL;Uses Crt;Var YN : String;

BeginWriteln('Y(YES) or N(NO)?');Repeat {repeat the code for at least one time}

YN := Readkey ; If YN = 'y' then Halt; {Halt - exit} If YN = 'n' then Writeln('Why not? Exiting...'); Delay(1800); { wait a second plus 800 milliseconds }Until (YN = 'y') OR (YN = 'n');

End.

Page 8: A/L 2011 revision. PASCAL PROGRAMMING IIPASCAL PROGRAMMING II page 3 of 8 Programming Task 1 TASK Develop a program that reads a number of inches, calculates the equivalent number

A/L 2011_revision. PASCAL PROGRAMMING II

page 8 of 8

FOR … NEXT LOOP

Program forNext;Uses Crt;

Var Counter : Integer; {loop counter declared as integer}

BeginFor Counter := 1 to 7 do {it's easy and fast!}

writeln('for loop');Readln;

End.

DO … WHILE LOOPProgram Lesson4_Program4;Uses Crt;

Var Ch : Char;BeginWriteln('Press ''q'' to exit...');Ch := Readkey;While Ch <> 'q' do

Begin Writeln('I told you press ''q'' to exit!!'); Ch := Readkey; End;End.

IBM: I Blame Microsoft

Page 9: A/L 2011 revision. PASCAL PROGRAMMING IIPASCAL PROGRAMMING II page 3 of 8 Programming Task 1 TASK Develop a program that reads a number of inches, calculates the equivalent number

A/L 2011_revision. PASCAL PROGRAMMING II

page 9 of 8

CASEProgram caseStatement;Uses Crt;Label Return; { avoid it }Var YN : Char;BeginReturn:ClrScr;Writeln('Exiting?');YN := Readkey;Case YN of

'y' : Halt; 'n' : Begin Writeln('What are you going to do here, anyway?'); Delay(2000); Halt; End; Else Begin Writeln('Either press ''y'' for yes'); Writeln('or ''n'' for no.. please try again..'); Delay(3500); ClrScr; Goto Return; End;End; {CASE}

End. {PROGRAM}

UNTIL ANDProgram UntilAnd;Uses Crt;Var n1, n2 : string; BeginWriteln('Enter two numbers: (''0'' & ''0'' to exit)');Repeat

Write('No.1: '); Readln(n1); Write('No.2: '); Readln(n2); If (n1 = '0') AND (n2 = '0') then Halt(0);

Until (n1 = '0') AND (n2 = '0');End.

Page 10: A/L 2011 revision. PASCAL PROGRAMMING IIPASCAL PROGRAMMING II page 3 of 8 Programming Task 1 TASK Develop a program that reads a number of inches, calculates the equivalent number

A/L 2011_revision. PASCAL PROGRAMMING II

page 10 of 8

UNTIL NOTProgram UntilNOT;Uses Crt;Var n1 : String; BeginWriteln('Enter two numbers: (any number except 0 to exit)');Repeat

Write('No.1: '); Readln(n1); If not(n1 = '0') then Halt;Until not(n1 = '0');

End.

A ProcedureProgram Procedure1; Uses Crt;

Procedure DrawLine; {This procedure helps to avoid the repetition of programming steps }Var Counter : Integer;

Begintextcolor(green);For Counter := 1 to 10 do

Begin {Step [1]} write(chr(196)); {Step [2]} End; {Step [3]}End;BeginGotoXy(10,5);DrawLine;GotoXy(10,6);DrawLine;GotoXy(10,7);DrawLine;GotoXy(10,10);DrawLine;Readkey;

End.

Using Procedures …

Page 11: A/L 2011 revision. PASCAL PROGRAMMING IIPASCAL PROGRAMMING II page 3 of 8 Programming Task 1 TASK Develop a program that reads a number of inches, calculates the equivalent number

A/L 2011_revision. PASCAL PROGRAMMING II

page 11 of 8

Program Procedures2;Uses Crt;Procedure DrawLine(X : Integer; Y : Integer);{the decleration of the variables in brackets are called parameteSumor arguments}Var Counter : Integer; {normally this is called a local variable}

BeginGotoXy(X,Y); {here I use the parameters}textcolor(green);For Counter := 1 to 10 do

Begin write(chr(196)); End; End;BeginDrawLine(10,5);DrawLine(10,6);DrawLine(10,7);DrawLine(10,10);Readkey;

End.

FunctionsProgram Lesson7_Program4;Uses Crt;

Var SizeA, sizeB : Real; YN : Char; unitS : String[2];Function PythagorasFunc(A:Real; B:Real) : Real;{The pythagoras theorem}BeginPythagorasFunc := SQRT(A*A + B*B);

{Output: Assign the procedure name to the value. If you forget to assign the function to the value, you will get a trash value from the memory}

End;BeginRepeat

Writeln;

Page 12: A/L 2011 revision. PASCAL PROGRAMMING IIPASCAL PROGRAMMING II page 3 of 8 Programming Task 1 TASK Develop a program that reads a number of inches, calculates the equivalent number

A/L 2011_revision. PASCAL PROGRAMMING II

page 12 of 8

Write('Enter the size of side A : '); Readln(sizeA); Write('Enter the size of side B : '); Readln(sizeB); Repeat Write('metres or centimetres? Enter : [m or cm] '); Readln(unitS); Until (unitS = 'm') or (unitS = 'cm'); Writeln(PythagorasFunc(sizeA,sizeB),' ',unitS); Writeln; Write('Repeat? '); YN := Readkey;Until (YN in ['N','n']);

End.

File Operations – Read/Write

Program file1;Var UserFile : Text; FileName, TFile : String;BeginWriteln('Enter the file name (with its full path) of the text file:');readln(FileName);{A .txt file will be assigned to a text variable}Assign(UserFile, FileName + '.txt'); Reset(UserFile); {'Reset(x)' - means open the file x}Repeat

Readln(UserFile,TFile); Writeln(TFile);Until Eof(UserFile);Close(UserFile);Readln;

End.

File Operations – Read/Write 2

Page 13: A/L 2011 revision. PASCAL PROGRAMMING IIPASCAL PROGRAMMING II page 3 of 8 Programming Task 1 TASK Develop a program that reads a number of inches, calculates the equivalent number

A/L 2011_revision. PASCAL PROGRAMMING II

page 13 of 8

Program file2;Var FName, Txt : String[10]; UserFile : Text; BeginFName := 'Textfile';Assign(UserFile,'C:\'+FName+'.txt'); {assign a text file} Rewrite(UserFile); {open the file 'fname' for writing}Writeln(UserFile,'PASCAL PROGRAMMING');Writeln(UserFile,'if you did not understand something,');Writeln(UserFile,'please send me an email to:');Writeln(UserFile,'[email protected]');Writeln('Write some text to the file:');Readln(Txt);Writeln(UserFile,'');Writeln(UserFile,'The user entered this text:');Writeln(UserFile,Txt);Close(UserFile);

End.

File Operations – Read/Write 3

Program file3;

Var UFile : Text;BeginAssign(UFile,'C:\ADDTEXT.TXT');ReWrite(UFile); Writeln(UFile,'How many sentences, '+

+'are present in this file?');Close(UFile);

End.

File Operations – Erace

Program file4;

Var UFile : Text; { or it could be of 'file' type}BeginAssign(UFile,'C:\ADDTEXT.TXT');Erase (UFile);

End.

Page 14: A/L 2011 revision. PASCAL PROGRAMMING IIPASCAL PROGRAMMING II page 3 of 8 Programming Task 1 TASK Develop a program that reads a number of inches, calculates the equivalent number

A/L 2011_revision. PASCAL PROGRAMMING II

page 14 of 8

Reading a value from an array

Program file5;

Var myVar : Integer; myArray : Array[1..5] of Integer;

BeginmyArray[2] := 25;myVar := myArray[2];

End.

Multi Dimensional Arrays

Program file5;

Var i : Integer; myIntArray : Array[1..20] of Integer; myBoolArray : Array[1..20] of Boolean;

BeginFor i := 1 to 20 do

Begin myIntArray[i] := 0; myBoolArray[i] := false; End;End.

String operations

Program String1;Var myString : String;

BeginmyString := 'Hey! How are you?';

Page 15: A/L 2011 revision. PASCAL PROGRAMMING IIPASCAL PROGRAMMING II page 3 of 8 Programming Task 1 TASK Develop a program that reads a number of inches, calculates the equivalent number

A/L 2011_revision. PASCAL PROGRAMMING II

page 15 of 8

Writeln('The length of the string is ',byte(myString[0]));Write(myString[byte(myString[0])]);Write(' is the last character.');

End.

Position of a String

Program String2;

Var S : String;

BeginS := 'Hey there! How are you?';Write('The word "How" is found at char index ');Writeln(Pos('How',S));If Pos('Why',S) <= 0 then

Writeln('"Why" is not found.');End.

Copy Strings

Program String3;

Var S : String;

BeginS := 'Hey there! How are you?';S := Copy(S, 5, 6); { 'there!' }Write(S);

End.

Page 16: A/L 2011 revision. PASCAL PROGRAMMING IIPASCAL PROGRAMMING II page 3 of 8 Programming Task 1 TASK Develop a program that reads a number of inches, calculates the equivalent number

A/L 2011_revision. PASCAL PROGRAMMING II

page 16 of 8

Program String4;

Var S : String;

BeginS := 'Hey Niranjan! How are you?';Delete(S, 4, 4); { 'Hey! How are you?' }Write(S);

End.

INSERT

Program String5;

Var S : String;

BeginS := 'Hey! How are you?';Insert(S, ' Max', 4);Write(S);

{ 'Hey Niranjan! How are you?' }End.

Page 17: A/L 2011 revision. PASCAL PROGRAMMING IIPASCAL PROGRAMMING II page 3 of 8 Programming Task 1 TASK Develop a program that reads a number of inches, calculates the equivalent number

A/L 2011_revision. PASCAL PROGRAMMING II

page 17 of 8

JOINING STRINGS

Program String7;

Var S1, S2 : String;

BeginS1 := 'Hey!'S2 := ' How are you?';Write(Concat(S1, S2)); { 'Hey! How are you?' }

End.

Program String7;

Var S1, S2 : String;

BeginS1 := 'Hey!'S2 := ' How are you?';Write(S1 + S2); { 'Hey! How are you?' }

End.Program String8;

Var S : String; i : Integer;

BeginS := 'Hey! How are you?';For i := 1 to length(S) do

S[i] := UpCase(S[i]);Write(S); { 'HEY! HOW ARE YOU?' }

End.

Page 18: A/L 2011 revision. PASCAL PROGRAMMING IIPASCAL PROGRAMMING II page 3 of 8 Programming Task 1 TASK Develop a program that reads a number of inches, calculates the equivalent number

A/L 2011_revision. PASCAL PROGRAMMING II

page 18 of 8

Program String9;

Var S : String; i : Real;

Begini := -0.563; Str(i, S);Write(S);

End.

Program String10;

Var S : String; error : Integer; R : Real;

BeginS := '-0.563'; Val(S, R, error);If error > 0 then

Write('Error in conversion.')Else

Write(R); End.

“If cars had followed the same development cycle as the computers, a Rolls-Royce would today cost $100, give million miles per litre, and crash once a day, killing everyone inside.”(Robert X. Cringely)

Page 19: A/L 2011 revision. PASCAL PROGRAMMING IIPASCAL PROGRAMMING II page 3 of 8 Programming Task 1 TASK Develop a program that reads a number of inches, calculates the equivalent number

A/L 2011_revision. PASCAL PROGRAMMING II

page 19 of 8

Problem Solving Task 2

Develop a program to read three integeSumand calculate and display their sum and product.

Problem: SumAndProductSystem

Data Table Number1, Number2, Number3 – IntegerSum, Product - Integer Algorithm

Begin { SumAndProductSystem }Display 'Type in the first number: 'Get Number1Display 'Type in the second number: 'Get Number2Display 'Type in the third number: 'Get Number3Calc Product as Number1 * Number2 * Number3Calc Sum as Number1 + Number2 + Number3Display 'The Sum of the three numbeSumis ', SumDisplay 'The Product of the three numbeSumis ', ProductEnd. { SumAndProductSystem }

Code

Page 20: A/L 2011 revision. PASCAL PROGRAMMING IIPASCAL PROGRAMMING II page 3 of 8 Programming Task 1 TASK Develop a program that reads a number of inches, calculates the equivalent number

A/L 2011_revision. PASCAL PROGRAMMING II

page 20 of 8

Task 3

Develop a program that work out an employee's net pay. The program should accept as data input the number of hour worked, hourly rate of pay, calculate the gross pay, net pay and display the net pay. Assume that a constant tax of Rs 30 is deducted for everyone.

Task 4

Develop a program to calculate the cost of a family holiday. It should read in the number of adults and children in the party, then calculate the hotel bill at Rs 60 per adult, and Sum20 per child the fare as Rs 210 per adult and Rs 110 per child. The program should display the total holiday cost.

Task 5

Develop a program that works out the final cost of running a surprise party. The cost of the buffet is Rs 6.00 a head. Alcoholic drinks are charged at Rs 2.00 per person. Assume that everyone present has one drink. The hall is Rs 40 to hire and the band Rs 150. The algorithm should calculate the total cost and display the total cost.

TASK 6

Develop a program to read a customer's surname and forename (individually) and display forename and surname (separated by a space), eg:

Advanced Stuffhttp://techpubs.sgi.com/library/manuals/0000/007-0740-030/pdf/007-0740-030.pdf

Created by: Niranjan Meegammana, Shilpa Sayura Project.

Page 21: A/L 2011 revision. PASCAL PROGRAMMING IIPASCAL PROGRAMMING II page 3 of 8 Programming Task 1 TASK Develop a program that reads a number of inches, calculates the equivalent number

A/L 2011_revision. PASCAL PROGRAMMING II

page 21 of 8

Supported by YES & ICT @ OSIPTO, KANDY.www.shilpasayura.org