A/L 2011_revision. PASCAL PROGRAMMING

Similar documents
Getting Started With Pascal Programming

Quick Reference Guide

Macro Programming Reference Guide. Copyright 2005 Scott Martinez

Getting Started With Pascal Programming

History. used in early Mac development notable systems in Pascal Skype TeX embedded systems

Quick Reference Guide

Variable A variable is a value that can change during the execution of a program.

Functions. Systems Programming Concepts

520 Principles of Programming Languages. Arithmetic. Variable Declarations. 19: Pascal

How to Design Programs Languages

Outline. Data and Operations. Data Types. Integral Types

COMPUTER SCIENCES II Spring Term 2017 Asst.Prof.Elgin KILIÇ

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

Making Decisions In Pascal

REVIEW. The C++ Programming Language. CS 151 Review #2

DelphiScript Keywords

Making Decisions In Pascal

BEGINNING PROBLEM-SOLVING CONCEPTS FOR THE COMPUTER. Chapter 2

Functions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

AIS Cube [THE BLAZINGCORE SERIES] LANGUAGE REFERENCE

Control Structures. Outline. In Text: Chapter 8. Control structures Selection. Iteration. Gotos Guarded statements. One-way Two-way Multi-way

Pace University. Fundamental Concepts of CS121 1

{ -- FLORIDA HIGH SCHOOLS COMPUTING COMPETITION '84 } { -- PASCAL PROGRAM SOLUTIONS }

VBScript: Math Functions

AIS Cube [THE BLAZINGCORE SERIES] LANGUAGE REFERENCE

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

Basic types and definitions. Chapter 3 of Thompson

Lab Instructor : Jean Lai

Engineering Problem Solving with C++, Etter/Ingber

Chapter 7 - Notes User-Defined Functions II

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

UNIT- 3 Introduction to C++

Chapter 3 - Functions

Programming. C++ Basics

Programmers should write code that is self-documenting and split into small sections.

COMP519 Web Programming Lecture 11: JavaScript (Part 2) Handouts

Fall Semester (081) Dr. El-Sayed El-Alfy Computer Science Department King Fahd University of Petroleum and Minerals

In Delphi script, when values are assigned to variables, the colon-equal operator is used; :=

C Functions. 5.2 Program Modules in C

Downloaded from Chapter 2. Functions

What did we talk about last time? Examples switch statements

CA4003 Compiler Construction Assignment Language Definition

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from

Subprograms A Procedure with No Parameters A Procedure with One Parameter Variable Parameters in Procedures

C: How to Program. Week /Mar/05

CSCE 110 PROGRAMMING FUNDAMENTALS

1 Programming. 1.1 Analyzing a problem

Introduction to C Final Review Chapters 1-6 & 13

Making Decisions In Pascal In this section of notes you will learn how to have your Pascal programs to execute alternatives

Arithmetic and Logic Blocks

Computer Science II TURBO PASCAL

CSE123. Program Design and Modular Programming Functions 1-1

Functions and Recursion

EDIABAS BEST/2 LANGUAGE DESCRIPTION. VERSION 6b. Electronic Diagnostic Basic System EDIABAS - BEST/2 LANGUAGE DESCRIPTION

Creating a C++ Program

Chapter 2 - Introduction to C Programming

Getting Started With Pascal Programming

StudyHub+ 1. StudyHub: AP Java. Semester One Final Review

Basics of ST. Each must end with a semi-colon (";") Basic statement. Q:=IN; Q:=sin(angle); Q := (IN1 + (IN2 / IN 3)) * IN4;

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction

Chapter 2. Outline. Simple C++ Programs

Chapter 2: Overview of C. Problem Solving & Program Design in C

Chapter-8 DATA TYPES. Introduction. Variable:

Expressions. Eric McCreath

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

CSc 520. Principles of Programming Languages 11: Haskell Basics

Chapter 5 Selection Statements. Mr. Dave Clausen La Cañada High School

Ch. 7: Control Structures

Functions. Lecture 6 COP 3014 Spring February 11, 2018

Chapter 7. - FORTRAN I control statements were based directly on IBM 704 hardware

P.G.TRB - COMPUTER SCIENCE. c) data processing language d) none of the above

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Pascal Validation Suite Report

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Introduction to the C++ Programming Language

FORM 4 PASCAL PROGRAMMING 6.1 WHAT IS AN ARRAY? Unit 6: Arrays and Strings

Annex A (Informative) Collected syntax The nonterminal symbols pointer-type, program, signed-number, simple-type, special-symbol, and structured-type

1001ICT Introduction To Programming Lecture Notes

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

Fundamental of Programming (C)

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

N.B. These pastpapers may rely on the knowledge gained from the previous chapters.

MagicCalc 4.49 Product Manual

CSc 372. Comparative Programming Languages. 4 : Haskell Basics. Department of Computer Science University of Arizona

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Chapter 2.5 Writing maintainable programs

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

Language Fundamentals

CSc 372 Comparative Programming Languages. 4 : Haskell Basics

CS313D: ADVANCED PROGRAMMING LANGUAGE

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

C++ Overview. Chapter 1. Chapter 2

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

Chapter 4 - Notes Control Structures I (Selection)

Ex: If you use a program to record sales, you will want to remember data:

FORTRAN Basis. PROGRAM LAYOUT PROGRAM program name IMPLICIT NONE [declaration statements] [executable statements] END PROGRAM [program name]

ISA 563 : Fundamentals of Systems Programming

Transcription:

Pascal is a high level programming language developed by Niklaus Wirth in 1970 based on the ALGOL programming language. It was named in honor of the French mathematician and philosopher Blaise Pascal. Pascal programs saved as *.pas. Variables Constants Control Flow Procedures Functions Comments store values/data stay the same change directions sub routines sub routines returning a value notes Structure of a Pascal program PROGRAM ProgramName (FileList); uses crt; (*importing libraries) const (* Constant declarations *) type (* Type declarations *) (* Variable declarations *) (* Subprogram definitions *) (* Main Program statements *) program FirstProg; Writeln('Hello World!'); page 1 of 8

VARIABLES CONSTANTS Must with a letter Can include alphanumeric characters and underscore (_). May not contain ~! @ # $ % ^ & * ( ) + ` - = { } [ ] : " ; ' < >?,. / Value assigned to a constant at the ning of the program. It can t be changed during the program running. Const Pi = 3.1415926535897932; Gravity = 9.8; GoldenRatio = 1.6; a : real = 12; page 2 of 8

VARIABLES AND DATA TYPES Var IdentifierList1 : DataType1; IdentifierList2 : DataType2; IdentifierList3 : DataType3; The basic data types integer From -32768 to 32767 real () 3.4x10-38 to 3.4x10 38 Char string Boolean A Niranjan TRUE and FALSE IndexNumber, Age: integer Temperature :real; FirstName: string; Married: Boolean ASSIGNMENT AND OPERATIONS iable_name := expression; length := 385.38; totalarea := (37.57 * 5.93) + (38.2/2.1); page 3 of 8

OPERATORS + Addition - Subtraction * Multiplication / Division div Integer division mod Modulus (remainder division) PUNCTUATION AND INDENTATION Pascal ignores end-of-lines and spaces. punctuation (;) tells the compiler when a statement ends. program Compute; const a = 5; b = 385.3; alpha, beta : real; (* main *) alpha := a + b; beta := b / a (* main *) COMMENTS (* one line *) (* some comments go into several lines*) page 4 of 8

INPUT / OUTPUT read (Variable_List); readln (Variable_List); read (a); readln (b); read (a, b, c, d); readln (e, f); write (Argument_List); writeln (Argument_List); write (a); writeln (b,c,d); write ('Time:', time:2); program InputOutput; a, b : string; (* main *) read(a); readln(b); writeln(a) writeln(a) page 5 of 8

CONDITIONALS RELATIONAL OPERATORS: < > = <= >= <> less than greater than equal to less than or equal to greater than or equal to not equal to 5 < 7 2 > 1 4=3+1 2<=3 10>=5 A <> B IF THEN if BooleanExpression then Statement1; if A = 30 then Writeln('A is equal to 30'); IF THEN. ELSE if BooleanExpression then StatementIfTrue else StatementIfFalse; if A = 30 then Writeln('A is equal to 30') else Writeln('A is not equal to 30'); page 6 of 8

NESTED IF if Condition1 then Statement1 else if Condition2 then Statement2 if A=30 then Writeln('A is equal to 30'); else if A=50 then Writeln('A is equal to 50'); else Statement3; else Writeln('A is not 30 or 50'); CASE case selector of List1: Statement1; List2: Statement2;... Listn: Statementn; Choice := ReadKey; case Choice of 'a': Writeln('You like apples'); 'b': Writeln('You like bananas'); 'c': Writeln('You like carrots'); else Writeln('Your choice is not a, b or c'); otherwise Statement page 7 of 8

LOOPING FOR NEXT for index := Low to High do statements; sum := 0; for count := 1 to 100 do sum := sum + count; WHILE.. DO while BooleanExpression do statements; a := 5; while a < 6 do writeln (a); a := a + 1 REPEAT UNTIL repeat statement1; until BooleanExpression; a := 5; repeat a := a + 1; writeln (a); until a > 10 GOTO LABEL 10; statements; GOTO 10; page 8 of 8

BREAK and CONTINUE The Break command will exit a loop at any time. program breaktest; i: Integer; i := 0; repeat i := i + 1; break; Writeln(i); until i = 10; program breaktest; i: Integer; i := 0; repeat i := i + 1; continue; Writeln(i); until i = 10; Program 1 will not print anything because break it exits the loop before it gets there. In Program 2 continue command will jump back to the top of a loop ARRAYS X: ARRAY [1..5] of real; X[1]:=4.2; X[2]:=71.6; X[3]:=8.3; X[4]:=92.6; X[5]:=403.7; writeln (X[1]+X[2]+X[3]+X[4]+X[5]) page 9 of 8

PROCEDURES & FUNCTIONS Procedure has the same basic format as a program: procedure Name; const (* Constants *) Var (* Variables *) Begin (* Statements *) Parameters to the procedure passed in the heading procedure PrintParameters (a, b : integer; c, d : real); a := 10; b := 2; writeln (a, b, c, d) FUNCTIONS function functionname (parameter_list) : return_type; statements; BUILT IN FUNCTIONS function add1toparameter(a) : integer; add1toparameter:= a + 1 abs returns absolute value arctan returns arctan in radians cos returns cosine of a radian measure sin returns sin of a radian measure sqr returns square (power 2) sqrt returns root (power 1/2) chr character with given ASCII value round returns round to nearest integer page 10 of 8

MATH FUNTIONS ABS(-6) the absolute value of -6; gives 6 SQR(3) the square of 3; gives 9 SQRT(9) the square root of 9; gives 3.0 SIN(2) the sine of 2 radians measure COS(2) the cosine of 2 radians measure LN(9) the natural logarithm of 9; gives log e 9 ROUND(9.2) rounds a number; gives 9 Functions are used to do repetitive tasks to reduce repeating code. program AddEmUpAgain; function AddEmUp( a, b, c: integer ) : integer; AddEmUp := a + b + c; procedure PrintData( a, b, c: integer ); Writeln('The sum of a, b, and c is ', AddEmUp(a, b, c), '.'); PrintData(2, 3, 4); page 11 of 8

SAMPLE PROGRAMS Find the sum and average of five numbers program SumAverage; const NumberOfIntegers = 5; A, B, C, D, E : integer; Sum : integer; Average : real; (* Main *) A := 45; B := 7; C := 68; D := 2; E := 34; Sum := A + B + C + D + E; Average := Sum / NumberOfIntegers; writeln ('Number of integers = ', NumberOfIntegers); writeln ('Number1 = ', A); writeln ('Number2 = ', B); writeln ('Number3 = ', C); writeln ('Number4 = ', D); writeln ('Number5 = ', E); writeln ('Sum = ', Sum); writeln ('Average = ', Average) (* Main *) page 12 of 8

Input 5 numbers and print their sum and average program SumAverage; const NumberOfIntegers = 5; A, B, C, D, E : integer; Sum : integer; Average : real; (* Main *) write ('Enter the first number: '); readln (A); write ('Enter the second number: '); readln (B); write ('Enter the third number: '); readln (C); write ('Enter the fourth number: '); readln (D); write ('Enter the fifth number: '); readln (E); Sum := A + B + C + D + E; Average := Sum / 5; writeln ('Number of integers = ', NumberOfIntegers); writeln; writeln ('Number1:', A:8); writeln ('Number2:', B:8); writeln ('Number3:', C:8); writeln ('Number4:', D:8); writeln ('Number5:', E:8); writeln ('================'); writeln ('Sum:', Sum:12); writeln ('Average:', Average:10:1); page 13 of 8

SCOPE Where will the iables be visible? program ScopeDemo; A, B : integer; procedure ScopeInner; B:= 10; writeln (B); (* prints value 10 *) writeln (A); (* prints value 20 *) (* Main *) A := 20; writeln (A); (* prints value 20 *) ScopeInner; (*changes A value*) writeln (A); (* prints new value 10*) (* Main *) global iables A visible everywhere global iables can be changed inside procedures. page 14 of 8

RCURSION Recursion allows a function or procedure to call itself function Sum (num : integer) : integer; if num = 1 then Sum := 1 else Sum := Sum(num-1) + num;(* calls self again*) totalsum:=sum(10); writeln(totalsum); If we call Sum with 3 as parameter totalsum := Sum(3); 1 st call : Sum(3) becomes Sum(2) + 3. 2 nd call : Sum(2) becomes Sum(1) + 2. At 1, the recursion stops and becomes 1 and returns Sum(2) becomes 1 + 2 = 3. Sum(3) becomes 3 + 3 = 6. a becomes 6. page 15 of 8

FORWARD REFERENCING procedures/functions can only use iables and subprograms already defined before them. (this is a weakness in Pascal coding) procedure Second (parameter list); procedure First (parameter list); procedure Third (parameter list); procedure First; Second (parameter list);(*second is declared before First *) procedure Second; Third (parameter list); (* ERROR Third is not visible to Second*) page 16 of 8

Find the first 100 numbers in the Fibonacci sequence. 1 1 2 3 5 8 13 21.. program Fibonacci; Fibonacci1, Fibonacci2 : integer; temp : integer; count : integer; (* Main *) writeln ('First ten Fibonacci numbers are:'); count := 0; Fibonacci1 := 0; Fibonacci2 := 1; repeat write (Fibonacci2:7); temp := Fibonacci2; Fibonacci2 := Fibonacci1 + Fibonacci2; Fibonacci1 := Temp; count := count + 1 until count = 10; writeln; (*you can also use a FOR loop or a WHILE loop. *) (* Main *) ASSIGNMENT Modify above program to display all powers of 2 up to 200. What code would you change and why? page 17 of 8

FILE HANDLING Reading and Writing to Files read (file_iable, argument_list); write (file_iable, argument_list); rest (file_iable, 'filename' ) rewrite (file_iable, 'filename'); assign (file_iable, 'filename'); eoln (file_iable) eof (file_iable) Reads values from a file Write values to a file Opens a file for reading Opens a file for writing Assigns a filename to a iable Returns TRUE when end of line is reached Returns TRUE when end of file is reached program CopyOneByteFile; mychar : char; filein, fileout : text; assign (filein, 'c:\file1.txt'); reset (filein); assign (fileout, 'c:\file2.txt'); rewrite (fileout); read (filein, mychar); write (fileout, mychar); close(filein); close(fileout) page 18 of 8

BOOLEAN EXPRESSIONS not and or xor negation conjunction disjunction exclusive-or (~) (^) (v) NOT applied to only one value to invert it: NOT true = false NOT false = true AND gives TRUE only if both values are TRUE: TRUE and FALSE = FALSE TRUE and TRUE = TRUE OR yields TRUE if at least one value is TRUE: TRUE or TRUE = TRUE TRUE or FALSE = TRUE FALSE or TRUE = TRUE FALSE or FALSE = FALSE XOR yields TRUE if one expression is TRUE and the other is FALSE. TRUE xor TRUE = FALSE TRUE xor FALSE = TRUE FALSE xor TRUE = TRUE FALSE xor FALSE = FALSE page 19 of 8

Bubble sort moves the biggest numbers to the end of the array. Example of Sorting 5 Numbers program BubbleSort; a: array[1..5] of Integer; i, j, tmp: Integer; a[1] := 23; a[2] := 45; a[3] := 12; a[4] := 56; a[5] := 34; for i := 1 to 4 do for j := i + 1 to 5 do if a[i] > a[j] then tmp := a[i]; a[i] := a[j]; a[j] := tmp; for i := 1 to 5 do writeln(i,': ',a[i]); page 20 of 8

Programming Solution: the Towers of Hanoi Problem program TowersofHanoi; numdiscs : integer; procedure DoTowers (NumDiscs, OrigPeg, NewPeg, TempPeg : integer); (* Explanation of iables Number of discs -- number of discs on OrigPeg OrigPeg -- peg number of the tower NewPeg -- peg number to move the tower to TempPeg -- peg to use for temporary storage*) (* Take care of the base case -- one disc *) if NumDiscs = 1 then writeln (OrigPeg, ' ---> ', NewPeg) (* Take care of all other cases *) else (* First, move all discs except the bottom disc to TempPeg, using NewPeg as the temporary peg for this transfer *) Tower of Hanoi is a problem with three pegs and more than 3 disks on one peg. You have to move disks one by one from peg to peg to transfer all disks to one peg. Rules 1. Only one disk can be transferred at a time. 2. Smaller disk should always be on the top of the other. DoTowers (NumDiscs-1, OrigPeg, TempPeg, NewPeg); (* Now, move the bottom most disc from OrigPeg to NewPeg *) writeln (OrigPeg, ' ---> ', NewPeg); (* Finally, move the discs currently on TempPeg to NewPeg, use OrigPeg as the temporary peg for this transfer *) DoTowers (NumDiscs-1, TempPeg, NewPeg, OrigPeg) end (* Main *) write ('Please enter the number of discs in the tower ===> ') readln (numdiscs); writeln; DoTowers (numdiscs, 1, 3, 2) (* Main *) page 21 of 8

program Decisions; i: Integer; Writeln('Enter a number'); Readln(i); if i > 5 then Writeln('Greater than 5'); program Decisions; i: Integer; Writeln('Enter a number'); Readln(i); if i > 5 then Writeln('Greater than 5') else Writeln('Not greater than 5'); program Loops1; i: Integer; i := 0; while i <= 10 i := i + 1; Writeln('Hello'); program Loops2; i: Integer; i := 0; repeat i := i + 1; Writeln('Hello'); until i = 10; Download FREE Pascal http://www.freepascal.org Created by: Niranjan Meegammana, Shilpa Sayura Project. Supported by YES & ICT @ OSIPTO, KANDY. www.shilpasayura.org page 22 of 8