0% found this document useful (0 votes)
4K views

PASCAL - GR 11

Pascal is a general-purpose, procedural programming language developed in the 1970s. It supports structured programming and data types. The document discusses Pascal's overview, history, features, environments, and basic program structure.

Uploaded by

shamili shamy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4K views

PASCAL - GR 11

Pascal is a general-purpose, procedural programming language developed in the 1970s. It supports structured programming and data types. The document discusses Pascal's overview, history, features, environments, and basic program structure.

Uploaded by

shamili shamy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 111

PASCAL

Programming Language

By
Sisira Palihakkara
Pascal Overview

 Pascal is a general-purpose, high-level


language that was originally developed by
Niklaus Wirth in the early 1970s.

 Pascal is a Procedural Language.

 It was developed for teaching programming


as a systematic discipline and to develop
reliable and efficient programs.
Facts about Pascal

 The Pascal language was named for Blaise


Pascal, French mathematician and pioneer in
computer development.

 Niklaus Wirth completed development of the


original Pascal programming language in
1970.
Features of the Pascal Language?

 Easy to learn.

 Structured language.

 It produces transparent, efficient and reliable


programs.

 It can be compiled on a variety of computer


platforms.
Features of the Pascal Language?

 Pascal is a strongly typed language.


 It offers extensive error checking.
 It offers several data types like arrays,
records, files and sets.
 It offers a variety of programming structures.
 It supports structured programming through
functions and procedures.
 It supports object oriented programming.
Environment

 There are several Pascal compilers and


interpreters available for general use.
 Turbo Pascal: provides an IDE and compiler
for running Pascal programs on DOS,
Windows
 Free Pascal: it is a free compiler for running
Pascal and Object Pascal Programs
Turbo Pascal 7
Turbo Pascal 7 IDE

Menu Bar
Project Name

Close Button
Window Switch
Button
Code Window

Bottom
Menu
Row, Column
Number Scroll Bars
Turbo Pascal 7 IDE

 Pascal IDE is a centralized control center


from which you can do three main jobs.
 Keying in your programs.
 Debugging.
 Compiling
 It provides
 Pull-down menus
 On screen help.
 Fairly sophisticated debugging facilities.
Hot Keys in Pascal
Key / Key Combination Function
Alt + X Exit
F2 Save
F9 Make
Ctrl + F9 Run
Alt + F9 Compile
Alt + F5 User Screen
Values & data Types

 There are 5 main data types.


1. Integer (Whole Numbers)
75, 2016, 3
2. Real (fractions - A single-precision floating point value. )
23.56, 4.01,0.78
3. String (Stores an array of characters. )
“Name’, ‘Total’
4. Boolean (logical)
True, False
5. Character (individual letters)
‘A’, ‘x’, ‘ y ‘
Variables (Identifiers)

 Variables are temporary storage locations in


memory.
Variable Naming Rules
 Variable name must begin with a letter or an
underscore ( _ ) [not didits]
 Can not use any control(special ) characters.
(!,@,#,$,%,^,&,*,-)
 No spaces between letters
 Reserved words cannot be used
 Eg: program, begin, end etc.
Variable Declaration
 All variables must be declared before we use them in Pascal
program.
 All variable declarations are followed by the var keyword.
 A declaration specifies a list of variables, followed by a colon
(:) and the type.
 Syntax
var
variableList : type;
Eg var
age, weekdays : integer;
taxRate, netIncome: real;
choice, isReady: boolean;
initials, grade: char;
name, surname : string
Variable Initialization
 Variables are assigned a value with a colon and the equal sign,
followed by a constant expression.
variableName := value
 By default, variables in Pascal are not initialized with zero. They may
contain rubbish values.
 So it is a better practice to initialize variables in a program.
 Variables can be initialized in their declaration.
The initialization is followed by the var keyword
var
variableName : type = value;
Ex.
age: integer = 15;
taxrate: real = 0.5;
grade: char = 'A';
name: string = 'John Smith';
Constants

 A constant is an entity that remains unchanged


during program execution.
 Pascal allows only constants of the following
types to be declared:
Ordinal types
Set types
Pointer types (but the only allowed value is Nil).
Real types
Char
String
Declaring Constants

 Syntax for declaring constants is as follows:


const
identifier = constantValue;

validAge = 21;
e=2.7182818;
velocityLight = 3.0E+10;
Operator = '+';
president = 'Johnny Depp';
Operators
 An operator is a symbol that tells the compiler to
perform specific mathematical or logical manipulations.
 Pascal allows the following types of operators:

Arithmetic operators
Relational operators
Boolean operators
Bit operators
Set operators
String operators
Arithmetic Operators
Assume variable A holds 10 and variable B holds 20, then:

Operator Description Example

+ Addition A + B  30

- Subtraction A – B  10
* A * B  200
Multiplication

div Divides numerator by denominator B div A  2


Mod Modulus Operator and remainder after an B mod A  0
integer division
Relational Operators

Operator Description Example

= Equals to (A = B) is not true.

<> Not equals to (A <> B) is true

> Greater than (A > B) is not true.

< Less than (A < B) is true.

>= Greater than or equals to (A >= B) is not true.

<= Less than or equals to (A <= B) is true.


Boolean Operators
Operator Description Example

Boolean AND operator. If both the


and operands are true, then condition (A and B) is false.
becomes true.

It is similar to the AND operator,


and then however, it guarantees the order in (A and then B) is false.
which the compiler evaluates the logical
expression. Left to right and the right
operands are evaluated only when
necessary

Boolean OR Operator. If any of the two


or operands is true, then condition (A or B) is true.
becomes true.
Boolean Operators cont…
Operator Description Example

Boolean AND operator. If both the


or else operands are true, then condition (A or else B) is true.
becomes true.

Boolean NOT Operator. Used to reverse


not the logical state of its operand. If a not (A and B) is true.
condition is true, then Logical NOT
operator will make it false.
Operators Precedence in Pascal
Priority order Operator High

1 not

2 * / div mod and


3 + - or
4 = <> < <= > >=
5 or else and then Low
Program Structure

 A Pascal program basically consists of the following


parts:
 Program name
 Uses command
 Type declarations
 Constant declarations
 Variables declarations
 Functions declarations
 Procedures declarations
 Main program block
 Statements and Expressions within each block
 Comments
Program Structure

 Every Pascal program generally have


a heading statement,
a declaration and
an execution part
strictly in that order.
Program Structure
program {name of the program}
uses {comma delimited names of libraries you use}
const {global constant declaration block}
var {global variable declaration block}

function {function declarations, if any}


{ local variables }
begin
...
end;
procedure { procedure declarations, if any}
{ local variables }
begin
...
end;

begin { main program block starts}


...
end. { the end of main program block }
Basic Program Structure

program {name of the program}


const {global constant declaration block}
var {global variable declaration block}
begin { main program block starts}
...
end. { the end of main program block }
Program Header
 Gives the name of the program and makes the official beginning of the
program for the Pascal Compiler.

Program sample (input, output);


Begin
write (‘Welcome’);
End.

In this example sample is the program header and starts with the keyword
“Program”.
Input and output words are parameters showing that the program produces input
and output. It is optional.
Constant Declaration Section

 Constants are the non-changing vales of a


program.
 Constants can be either simple or complex
expressions.
 Declared using the reserved word “CONST”.

Program sample(input, output);


Const basic = 5000;
Variable Declaration Section
 Declare the names and data type s of variables that you use in
the program.
 The variable declaration section is declared using the reserved
word “VAR”.
Eg:
Program sample(input, output);
Var
adno : integer;
name : string;
Begin
statement1;
statemant2;
End.
Program Body

 This the last section of a Pascal program and


the statements written between two key
words “Begin” and “end” and ending with a
period.
 The main body of the program should show
only the overall structure of what happens in
the program leaving all the subroutines.
Program Body

Program example1(input , output);


Const
No1 = 10;
No2 = 20;
Var
x,y : integer;
Begin
x:= No1;
y := N02;
write (“Total =“ , x + y);
End.
Simple Input Output Functions
 Read()
Reads and Inputs from the keyboard and cursor stays in the same
line.
 Raedln()
Reads and Inputs from the keyboard and move cursor to the next
line.
 Write()
Writes the message on the screen and the cursor stays in the same
line
 Writeln()
Writes the message on the screen and move cursor to the next
line.
Case Sensitivity

 Pascal is NOT a case sensitive language.


Ex. variables
 Name
 name
 NAME
have same meaning in Pascal
Pascal Hello World Example

 Following Pascal program that would print


the text "Hello, World!":

program HelloWorld;
uses crt;
(* Here the main program block starts *)
Begin
Clrscr;
writeln('Hello, World!');
readkey;
end.
Parts of a Pascal program:

 The first line program HelloWorld; indicates the name


of the program.
 The second line ; uses crt; is a preprocessor command,
which tells the compiler to include the crt library before
going to actual compilation.
 The next lines are the main program block.
Every block in Pascal is enclosed within a begin
statement and an end statement.
However, the end statement indicating the end of the
main program is followed by a full stop (.) instead of
semicolon (;).
Parts of a Pascal program:

 The begin statement of the main program block is


where the program execution begins.
 The lines within (*...*) will be a comment in the
program.
 The statement writeln('Hello, World!'); causes the
message "Hello, World!" to be displayed on the
screen.
 The statement readkey; allows the display to
pause until the user presses a key. It is part of the
crt library.
Selection Control structures
- Decision Making

 Simple selection
Types Selection Control structures
if-then Statement

Syntax:-

Where condition is a Boolean expression and S is a simple or compound


statement.
Example:

 If the boolean expression condition evaluates to true, then the block of code
inside the if statement will be executed.

 Pascal assumes any non-zero and non-null values as true, and if it is either
zero or null, then it is assumed as false value.
Flow Diagram for If .. then
Example – If - then
else Statement

 An if-then statement can be followed by an optional


else statement, which executes when the Boolean
expression is false.
 Syntax:

 In the if-then-else statements, when the test


condition is true, the statement S1 is executed and S2
is skipped; when the test condition is false, then S1 is
bypassed and statement S2 is executed.
Flow diagram
else Statement example

 If the boolean expression condition evaluates


to true, then the if-then block of code will be
executed, otherwise the else block of code
will be executed.
Example – If .. Then…else
else if Statement
 An if-then statement can be followed by an
optional else if-then-else statement, which is
very useful to test various conditions using
single if-then-else if statement.
 Once an else if succeeds, none of the remaining
else if's or else's will be tested.
 No semicolon (;) is given before the last else
keyword, but all statements can be compound
statements.
else if Statement syntax
if-then-
else if-then-else Statement example
Nested if Statement

 We can use one if or else if statement inside


another if or else if statement(s).
 Pascal allows nesting to any level, however, if
depends on Pascal implementation on a
particular system.
 Syntax:
Nested if Statement
 You can nest else if-then-else in the similar way as you have
nested if-then statement.
 Please note that, the nested if-then-else constructs gives
rise to some ambiguity as to which else statement pairs with
which if statement.
 The rule is that the else keyword matches the first if keyword
(searching backwards) not already matched by an else
keyword.
 Syntax:
Example
Case Statement
 You have observed that if-then-else statements
enable us to implement multiple decisions in a
program. This can also be achieved using the case
statement in simpler way.
 Syntax:
Rules for using ase statement
 The expression used in a case statement must have an
integral or enumerated type
 You can have any number of case statements within a
case. Each case is followed by the value to be compared
to and a colon.
 The case label for a case must be the same data type as
the expression in the case statement, and it must be a
constant or a literal.
 The compiler will evaluate the case expression. If one of
the case label's value matches the value of the
expression, the statement that follows this label is
executed. After that, the program continues after the
………Contd.

 If none of the case label matches the


expression value, the statement list after the
else or otherwise keyword is executed. This
can be an empty statement list. If no else part
is present and no case constant matches the
expression value, program flow continues
after the final end.
 The case statements can be compound
statements (i.e., a Begin ... End block).
Flow Diagram of Case Statement:
Example:

 The following example illustrates the


concept:
Case Else Statement

 The case-else statement uses an else term


after the case labels, just like an if-then-else
construct.
 Syntax:
Flow Diagram of
Case Else Statement
Example
The following example illustrates the concept:
Nested Case Statements

 It is possible to have a case statement as part


of the statement sequence of an outer case
statement.
 Even if the case constants of the inner and
outer case contain common values, no
conflicts will arise.
Syntax:

 The syntax for a nested case statement is as


follows:
Example

 The following program illustrates the


concept.
Loops
 There may be a situation, when you need to
execute a block of code repeatedly

 A loop statement allows us to execute a


statement or group of statements multiple times
Loops
Following is the general form of a loop statement
Loops in Pascal
Pascal programming language provides the following
types of loop constructs to handle looping
requirements.
while-do loop
 A while-do loop statement allows repetitive
computations till the test condition is satisfied.
In other words, it repeatedly executes
statement/s as long as a given condition is
true.
 Syntax:
while-do loop

 Group of statements can be defined within


BEGIN ... END block.
 Example

When the condition becomes false, program control passes to


the line immediately following the loop.
while-do loop Flow Diagram:

The loop is never executed, if the condition is tested and the result is false, the
loop body will be skipped and the first statement after the while loop will be
executed.
while-do loop Sample
For-do LOOP
 A for-do loop allows you to write a loop that needs to
execute a specific number of times.
 Syntax:

 Where, the variable-name specifies a variable of


ordinal type, called control variable or index variable;
initial_value and final_value values are values that the
control variable can take; and S is the body of the for-
do loop that could be a simple statement or a group of
statements.
 Example:
The flow of control in a for-do loop:
 The initial step is executed first, and only once. This step
allows you to declare and initialize any loop control variables.
 Next, the condition is evaluated. If it is true, the body of the
loop is executed. If it is false, the body of the loop does not
execute and flow of control jumps to the next statement just
after the for-do loop.
 After the body of the for-do loop executes, the value of the
variable in increased or decreased.
 The condition is now evaluated again. If it is true, the loop
executes and the process repeats itself (body of loop, then
increment step, and then again condition). After the
condition becomes false, the for-do loop terminates.
Flow Diagram for-do loop
Example: for-do loop
Repeat-Until Loop

 Unlike for and while loops, which test the


loop condition at the top of the loop, the
repeat ... until loop in Pascal checks its
condition at the bottom of the loop.
 A repeat ... until loop is similar to a while
loop, except that a repeat ... until loop is
guaranteed to execute at least one time.
 Syntax:
Example: Repeat-Until Loop

Notice that the conditional expression appears at the end


of the loop, so the statement(s) in the loop execute once
before the condition is tested.
If the condition is true, the flow of control jumps back up
to repeat and the statement(s) in the loop execute again.
This process repeats until the given condition becomes
false.
Flow Diagram Repeat-Until Loop
Example: Repeat-Until Loop
Nested Loops

 Pascal allows using one loop inside another


loop. Following section shows few examples
to illustrate the concept.
 The syntax for a nested for-do loop
statement in Pascal is as follows:
Nested Loops

 The syntax for a nested while-do loop


statement in Pascal is as follows:
Nested Loops

 The syntax for a nested repeat ... until loop


Pascal is as follows:
Nested Loops

 A final note on loop nesting is that you can


put any type of loop inside of any other type
of loop.
 For example, a for loop can be inside a while
loop or vice versa.
Example: Nested for Loop

 The following program uses a nested for loop


to find the prime numbers from 2 to 50:
Arrays in Pascal
 Pascal programming language provides a data structure
called the array, which can store a fixed-size sequential
collection of elements of the same type.
 An array is used to store a collection of data, but it is
often more useful to think of an array as a collection of
variables of the same type.
 Instead of declaring individual variables, such as
number1, number2, ..., and number100, you declare one
array variable such as numbers and use numbers[1],
numbers[2], and ..., numbers[100] to represent
individual variables.

Arrays in Pascal
 A specific element in an array is accessed by an index.
 All arrays consist of contiguous memory locations. The lowest
address corresponds to the first element and the highest address
to the last element.
 Please note that if you want a C style array starting from index 0,
you just need to start the index from 0, instead of 1.
Declaring Arrays
 To declare an array in Pascal, a programmer may
either declare the type and then create variables of
that array or directly declare the array variable.
 The general form of type declaration of one-
dimensional array is:

Where,
 array-identifier indicates the name of the array type.
 index-type specifies the subscript of the array; it can be
any scalar data type except real
 element-type specifies the types of values that are going
to be stored.
Example Arrays

 Now, velocity is a variable array of vector


type, which is sufficient to hold up to 25 real
numbers.

 To start the array from 0 index, the


declaration would be:
Types of Array Subscript
 In Pascal, an array subscript could be of any scalar
type like, integer, Boolean, enumerated or
subrange, except real. Array subscripts could have
negative values too. For example,

 Let us take up another example where the


subscript is of character type:
…..types of Array Subscript

 Subscript could be of enumerated type:


Initializing Arrays

 In Pascal, arrays are initialized through


assignment, either by specifying a particular
subscript or using a for-do loop.
 For example:
Accessing Array Elements

 An element is accessed by indexing the array


name. This is done by placing the index of the
element within square brackets after the
name of the array. For example:

 The above statement will take the first


element from the array named alphabet and
assign the value to the variable a.
Example

 The example , which will use all the above-


mentioned three concepts viz. declaration,
assignment and accessing arrays:
Subprograms
 A subprogram is a program unit/module that performs
a particular task.
 These subprograms are combined to form larger
programs.
 This is basically called the 'Modular design.' A
subprogram can be invoked by a subprogram /program,
which is called the calling program.
 Pascal provides two kinds of subprograms:
 Functions: these subprograms return a single value.
 Procedures: these subprograms do not return a value
directly.
Functions
 A function is a group of statements that together perform a
task. Every Pascal program has at least one function, which
is the program itself, and all the most trivial programs can
define additional functions.
 A function declaration tells the compiler about a function's
name, return type, and parameters. A function definition
provides the actual body of the function.
 Pascal standard library provides numerous built-in functions
that your program can call. For example, function
AppendStr() appends two strings, function New()
dynamically allocates memory to variables and many more
functions.
Defining a Function:
 In Pascal, a function is defined using the function keyword.
The general form of a function definition is as follows:

 A function definition in Pascal consists of a function header,


local declarations and a function body. The function header
consists of the keyword function and a name given to the
function.
The parts of a function:

 Arguments: The argument(s) establish the linkage between


the calling program and the function identifiers and also called
the formal parameters.
 A parameter is like a placeholder. When a function is invoked,
you pass a value to the parameter.
 This value is referred to as actual parameter or argument.
 The parameter list refers to the type, order, and number of
parameters of a function.
 Use of such formal parameters is optional.
 These parameters may have standard data type, user-defined
data type or subrange data type.
 The formal parameters list appearing in the function statement
could be simple or subscripted variables, arrays or structured
variables, or subprograms.
….the parts of a function:
 Return-Type: All functions must return a value, so all
functions must be assigned a type. The function-type is the
data type of the value the function returns. It may be
standard, user-defined scalar or subrange type but it cannot
be structured type.

 Local declarations: Local declarations refer to the


declarations for labels, constants, variables, functions and
procedures, which are application to the body of function
only.
……the parts of a function:

 Function Body: The function body contains a


collection of statements that define what the function
does. It should always be enclosed between the
reserved words begin and end. It is the part of a
function where all computations are done. There must
be an assignment statement of the type - name :=
expression; in the function body that assigns a value
to the function name. This value is returned as and
when the function is executed. The last statement in
the body must be an end statement.
An example showing how to define a
function in pascal:
Function Declarations:
 A function declaration tells the compiler about a function
name and how to call the function. The actual body of the
function can be defined separately.
 A function declaration has the following parts:

 For the above-defined function max(), following is the


function declaration:

 Function declaration is required when you define a function


in one source file and you call that function in another file. In
such case, you should declare the function at the top of the
file calling the function.
Calling a Function:
 While creating a function, you give a definition of what
the function has to do. To use a function, you will have
to call that function to perform the defined task. When a
program calls a function, program control is transferred
to the called function. A called function performs
defined task, and when its return statement is executed
or when it last end statement is reached, it returns
program control back to the main program.
 To call a function, you simply need to pass the required
parameters along with function name, and if function
returns a value, then you can store returned value
Example to show the usage:
Procedure
 Defining a Procedure:
 In Pascal, a procedure is defined using the procedure
keyword. The general form of a procedure definition is
as follows:

 A procedure definition in Pascal consists of a header,


local declarations and a body of the procedure. The
procedure header consists of the keyword procedure
and a name given to the procedure.
The parts of a procedure:
 Arguments: The argument(s) establish the linkage between
the calling program and the procedure identifiers and also
called the formal parameters. Rules for arguments in
procedures are same as that for the functions.
 Local declarations: Local declarations refer to the declarations
for labels, constants, variables, functions and procedures,
which are applicable to the body of the procedure only.
 Procedure Body: The procedure body contains a collection of
statements that define what the procedure does. It should
always be enclosed between the reserved words begin and end.
It is the part of a procedure where all computations are done.
Sample Program for Procedures

This source code is for a procedure called findMin().

This procedure takes 4 parameters x, y, z and m and stores


the minimum among the first three variables in the variable
named m.
Procedure Declarations:
 A procedure declaration tells the compiler about a
procedure name and how to call the procedure.
The actual body of the procedure can be defined
separately.
 A procedure declaration has the following syntax:

 Please note that the name of the procedure is


not associated
Calling a Procedure:

 While creating a procedure, you give a definition


of what the procedure has to do.
 To use the procedure, you will have to call that
procedure to perform the defined task.
 When a program calls a procedure, program
control is transferred to the called procedure.
 A called procedure performs the defined task,
and when its last end statement is reached, it
returns the control back to the calling program.
Calling a Procedure
 To call a procedure, you simply need to pass the required
parameters along with the procedure name as shown below:
Procedure
A procedure is defined using
the procedure keyword. The general form of a
procedure definition is as follows:

procedure name(argument(s): type1, argument(s): type 2, ... );


< local declarations >
begin < procedure body > end;

A procedure definition in Pascal consists of


a header, local declarations and a body of the
procedure.
Procedure - Example
procedure findMin(x, y, z: integer; var m: integer);
(* Finds the minimum of the 3 values *)
begin
if x < y then
m := x
else
m := y;
if z <m then
m := z;
end; { end of procedure findMin }
Procedure - Example
This procedure takes 4 parameters x, y, z
and m and stores the minimum among the
first three variables in the variable named
m. The variable m is passed by reference
Procedure - Example
program exProcedure;
var
a, b, c, min: integer;
procedure findMin(x, y, z: integer; var m: integer);
(* Finds the minimum of the 3 values *)

begin
if x < y then
m:= x
else
m:= y;

if z < m then
m:= z;
end; { end of procedure findMin }

begin
writeln(' Enter three numbers: ');
readln( a, b, c);
findMin(a, b, c, min); (* Procedure call *)

writeln(' Minimum: ', min);


end.

You might also like