Vous êtes sur la page 1sur 89

Inst.

Waheed Al-Sayer 1
1
.
Inst. Waheed Al-Sayer 2
Computer Components
Each computer must
consists of TWO distinct
parts, Hardware and
Software.
Hardware is the part the
can be touched and seen.
Software is the part that
can be seen but not
touched.
We will learn how to
create the Software part.
Inst. Waheed Al-Sayer 3
Storage
Si Pi You and Eye O
read (CPU and IO)
Computers execute
instructions given to
them by the programmer.
The main executer is the
CPU. It takes input from
the user and produces
results.
The CPU uses temporary
memory to store data and
intermediate results.
The computer uses the
Hard disk storage to store
permanent data.
Input
CPU
Memory
Output
Instructions
and Data
Questions
and Results
Inst. Waheed Al-Sayer 4
Software Categories
BIOS (Basic Input Output System) the first
program the computer runs, it talks to the
hardware and the OS.
O/S (Operating System) the main file
management and application handling software.
Applications: Word Processing, Spreadsheets,
Games.
Development Software: Software to write
software's with.
Custom software: Specially made software for
small amount of users like ourselves.
Inst. Waheed Al-Sayer 5
Programming Languages
Computers first language is
00000s and 11111s.
Then came assembly it
simplified how programs are
written and it is still the most
powerful language ever. Only
a few programmers know the
language.
Then the flow of computer
languages started. Today with
hundreds of languages
available, some are designed
for specific tasks.
Pascal and Basic are the most
targeted towards education.
0100100101001001000110
.model small
.stack
.data
message db "Hello world", "$"
.code
main proc
mov ax,seg message
mov ds,ax

mov ah,09
lea dx,message
int 21h

mov ax,4c00h
int 21h
main endp
end main
program MyFirstProgram;
begin
writeln(Hello world.);
end.
Inst. Waheed Al-Sayer 6
What every language needs

Almost all languages consists of:
Syntactical Grammar
Data Types
Data Structures
Control Structures
Inst. Waheed Al-Sayer 7
Writing Programs to Solve Problems
To solve a problem we must define three parts:
Input Processing Output
Data Results
Inst. Waheed Al-Sayer 8
Program Flow
Source
Code
Compiler Editor
Machine
Language
No Errors
Syntax
Errors
Linker
EXE
program
Run-Time/Logical
Error
Inst. Waheed Al-Sayer 9
Platforms
Pascal
program
Solaris
compiler
a.out (Solaris)
AmigaDOS
compiler
a.out (AmigaDOS)
Windows
compiler
a.out (Windows)
Inst. Waheed Al-Sayer 10
Reading the problem
Input
Certain words indicate input, so what comes after these words is usually input: get,
read, prompt the user for, input, accept, given, knowing
Types of input variables should be known.
We use the statement Read or Readln to get input from the user.
Processing
You should know what to do with the input given.
Processing is finding output from input using actions.
Write formulas clearly indicating input variables
Output
Certain words indicate output, so what comes after these words will be output:
display, show, calculate, compute, output, tell, print.
All output should be labeled.
Output of type Real should be formatted.
We use the statement Write or Writeln to show output to the user.
Inst. Waheed Al-Sayer 11
Main components of a Pascal
program
program name;
const
constant = value;

var
variable : type;
begin
statement;
end.
Header
Declarations
Statements
Inst. Waheed Al-Sayer 12
Header
Documentation
Describe the program
Describe the owner
Show updates/versions/dates
For example
Program name
Real program name
{ Area of Circle
Written by: Waheed Alsayer
ver. 1.0
1/10/2005}
Inst. Waheed Al-Sayer 13
Comments
Used to explain program lines in plain
English
Use the following to write comments:
Start a line with //
Put a comment between (* and *)
Put a comment between { and }
Inst. Waheed Al-Sayer 14
Identifiers
Naming Rules:
Must begin with a letter.
Must not contain any special characters
( _ underscore is allowed).
Must not be a reserved word or a standard
identifier.
Case insensitive
Self documenting
Inst. Waheed Al-Sayer 15
Reserved Words
Have a predefined meaning in Pascal that cannot be changed
and array begin case const div do downto else
end file for forward function goto if in label
mod nil not of or packed procedure program record
repeat set then to type until var while while
Inst. Waheed Al-Sayer 16
Standard Identifiers
Have a predefined meaning in Pascal that SHOULD NOT
be changed
Predefined constants
false
true
maxint
Predefined types
Boolean, Char, Integer, Real, Text
Predefined files
input
output
Inst. Waheed Al-Sayer 17
Standard Identifiers (2)
Predefined functions

abs arctan
chr
cos eof eoln
exp ln odd ord pred round
sin sqr sqrt succ trunc
Inst. Waheed Al-Sayer 18
Standard Identifiers (3)
dispose get new pack page
put read readln reset rewrite
unpack write writeln
Predefined procedures
Inst. Waheed Al-Sayer 19
Declaration Temporary Program
Storage
To read information, to calculate formulas,
and to produce results we need places to
keep data.
There are two types of temporary data
storage: Constants, and Variables.
Inst. Waheed Al-Sayer 20
Memory
Constants
Cannot change the constant value
const PI = 3.14;
PI := 3;
Can be used in any operation or write
statements.

Fixed areas in memory
Const constant_name = value;
3.14
PI
Inst. Waheed Al-Sayer 21
Purpose Of Named Constants

Makes the program easier to understand & maintain
populationChange := (0.1758 0.1257) * currentPopulation;



const
BIRTH_RATE = 0.1758;
DEATH_RATE = 0.1257;
begin
populationChange := (BIRTH_RATE DEATH_RATE) * currentPopulation;


Inst. Waheed Al-Sayer 22
Variables
Variables are used to store information temporarily.
As a program runs, it holds values temporarily in
memory.
Variables are names that the program associates with
specific locations in memory.
The value to which the program refers in these areas can
change throughout a session of program operation.
Each variable has a specific type, that indicates how much
memory the data requires and the operations that can be
performed on that kind of data.
Inst. Waheed Al-Sayer 23
Data Types
Integer 4 bytes
-2147483648 .. 2147483647 (Lowest and Highest)
-Maxint .. Maxint (Special names of the above values)
It is used to store whole numbers only. For example: Count,
no_of_students, turns. So when we define a variable of type
integer it can store numbers of any value up to the maxint.
Real 8 bytes
10E-38 .. 10E38
Numbers with fractions. We use decimal point to separate
whole and fractions.
Inst. Waheed Al-Sayer 24
Data Types
Char 1 byte )1 ANSI character(
NUL .. DEL, taking in 'a' ..'z
We can store only one character in a variable of this type. Usually used to
store codes like Maritial status, Grade level, Day/Night.
String[n] n+1 bytes with zero-numbered byte contain the size of the string.
Any number of characters (up to 255) can be stored in a variable of type
string. It is used to store name, addresses, telephone numbers!.
Boolean 1 byte
True or False
This type is used as an indicator, for 2 values only like yes/no, Black/White
or any similar values.
Inst. Waheed Al-Sayer 25
Variables
Changeable areas in memory
Var variable_name : data_type;
Memory
age
var age : integer;
Must be self documenting
Must be of correct type to match
the data
age := 20;
20
Inst. Waheed Al-Sayer 26
Assignment
a := 32;

Assignment means is given the value of.
Thus the previous content of the left hand side is lost.

NOTE: It is important to make variable names and other identifiers
as meaningful to the human as possible. If this cannot be done use
internal documentation in the form of comments.
Inst. Waheed Al-Sayer 27
What happens when use variables

Var Count: integer;

Begin

Count := 0;

Count := Count + 1;

End.
Memory
0
+ 1
1
Count


Inst. Waheed Al-Sayer 28
Type Compatibility
Integer Real
Char String




Inst. Waheed Al-Sayer 29
Arithmetic Operators
Operation Operator Operand
Types
Result Type Example
Sign Identity

+ (unary) Integer, Real Integer, Real + X
Sign Negation

- (unary) Integer, Real Integer, Real - X
Multiplication * Integer, Real Integer, Real X * Y
Division / Integer, Real Real X / Y
Integer Division

div Integer Integer X div Y
Modulo Division

mod Integer Integer X mod Y
Addition + Integer, Real Integer, Real X + Y
Subtraction - Integer, Real Integer, Real X - Y
Inst. Waheed Al-Sayer 30
Calculate non-divisible values

The regular division operator will produce
fractions. But some times we need just the
whole part of the result.
So DIV is the solution. The result of the
DIV is a whole number.
Inst. Waheed Al-Sayer 31
DIV and MOD
Examples:
How many computers per
students. And what are the
remaining computers?
8 div 4 -> 2
7 div 4 -> 1
6 div 4 -> 1
5 div 4 -> 1
4 div 4 -> 1
3 div 4 -> 0
2 div 4 -> 0
1 div 4 -> 0
0 div 4 -> 0
8 mod 4 -> 0
7 mod 4 -> 3
6 mod 4 -> 2
5 mod 4 -> 1
4 mod 4 -> 0
3 mod 4 -> 3
2 mod 4 -> 2
1 mod 4 -> 1
0 mod 4 -> 0
Inst. Waheed Al-Sayer 32
Math Expressions to Pascal Expressions

Conversion of a math expression

x := Sqr( (y+r) / Sqrt(y) )
2
|
|
.
|

\
|
+
=
y
r y
x
Inst. Waheed Al-Sayer 33
Expression conversion exercise
Convert these math expressions to Pascal
r y
y
x

=
2
r y
y
x

=
r y
y
y r x

+ =
3
) (
r y
r y
y
x

=
Inst. Waheed Al-Sayer 34
Percentage Calculations
Percentage formula is used to calculate the
increase or decrease of a certain amount.
Formula used:
New Amount := Old Amount (Old Amount * Percentage);
+ is used for increase, - is used for decrease.
Example:
Increase Salary by 10%
Salary := Salary + (Salary * 0.1);
Decrease Temp by 3.5%
Temp := Temp (Temp * 0.035);
Inst. Waheed Al-Sayer 35
Showing Output
write statement will print parameters on screen
and keep the cursor at the end of output.
writeln statement will print the parameters on
screen then puts the cursor on the next line.
To write more than one item separate it with a
comma.
Examples:
Write; Write(Hello);
Write(Age , 20); Writeln(Age : , age);
Writeln(Salary = , new_salary:9:3);
Inst. Waheed Al-Sayer 36
Formatting Output
Formatting of output (Real Numbers)
Field width: The computer will insert enough spaces to ensure that
the information can be displayed.
Decimal places: For real numbers the data will be displayed in
exponential/scientific form.
Syntax:
write or writeln (data: Field width for data: Number decimal places for data);
Example
num := 12.34;
writeln(num);
writeln(num:5:2);
Inst. Waheed Al-Sayer 37
Formatting Output (2)
If the field width doesnt match the actual size of the field
Field width too small extra spaces will be added for numerical variables but
not for other types of data.
Examples:
num := 123456;
writeln(num:3);
writeln('123456':3);
Field width too large the data will be right justified (extra spaces will be put
in front of the data).
Examples:
num := 123;
writeln(num:6);
writeln('123':6);
Inst. Waheed Al-Sayer 38
Formatting Output (3)
If the number of decimal places doesnt match the actual
number of decimal places.
Set number of decimal places less than the actual number of decimal
places number will be rounded up.
Example:
num1 := 123.4567
writeln (num1:6:2);
Set number of decimal places greater than the actual number of decimal
places number will be padded with zeros.
Example:
num1 := 123.4567;
writeln(num1:6:6);
Inst. Waheed Al-Sayer 39
Formatting Output: A Larger
Example
Type and run the following example:
var num1 : integer;
num2 : real;
begin
num1 := 123;
num2 := 123.456;
writeln('Auto formatted by Pascal ', num1, num2);
writeln('Manual format ':13, num1:3, num2:7:3);
writeln('Manual not enough ':13, num1:2, num2:6:3);
writeln('Manual too much ':16, num1:4, num2:8:4);
end.
Inst. Waheed Al-Sayer 40
Getting Data from outside the
program
To get information from the user we use read
and readln statements.
Syntax:
read (name of variable);
or
readln (name of variable);


Inst. Waheed Al-Sayer 41
Memory Screen
What happens when process data

Var X: integer;

Begin
Write(Enter X:);
Readln (X);

X := SQR(X);
Writeln(Square X=, X);
End.
4
4
4
X
Enter X: 16
Square X=
16
Inst. Waheed Al-Sayer 42
Getting Input
Examples:
var num1 : integer;
num2 : integer;
------
read (num1);
read (num2);
var num1,
num2 : integer;
-----
read (num1, num2);

var name : string;
age : integer;
begin
readln (name, age);
writeln( name, age);
End.
var name : string;
age : integer;
begin
readln (age, name);
writeln(age, name);
End.
Inst. Waheed Al-Sayer 43
Input: Read Vs. Readln
Both:
Reads each value entered into the keyboard and matches it
to the corresponding variable in the list.
Read
If the user inputs additional values before hitting return
they will remain in the keyboard buffer memory.
Readln
Any additional values entered before the return will be
discarded
Inst. Waheed Al-Sayer 44
Read Example
Type and run this example
var numb1, numb2 : integer;
begin
writeln('Please enter two numbers separated by
a space');
read( numb1 );
read( numb2 );
writeln;
writeln('Numb1 is ', numb1 , ' Numb2 is ',
numb2 )
end.
Inst. Waheed Al-Sayer 45
Input: Read Vs. Readln (An Example)
Type and run this example:
var num1 : integer;
num2 : integer;
begin
write('Type in an integer: ');
read(num1);
write('Type in an integer: ');
read(num2);
writeln('You typed in the following numbers:');
writeln('First: ', num1, ' Second: ', num2);
End.
Inst. Waheed Al-Sayer 46
Input: Read Vs. Readln (An example (2))
Type and run this example:
var num1 : integer;
num2 : integer;
begin
write('Type in an integer: ');
readln(num1);
write('Type in an integer: ');
readln(num2);
writeln('You typed in the following numbers:');
writeln('First: ', num1, ' Second: ', num2);
End.
Inst. Waheed Al-Sayer 47
Another Input Example
Type and run the following example:
var ch1 : char;
in1 : integer;
re1 : real;
begin
write('Enter an integer, a character and a real number on one line (no spaces): ');
read(in1);
write(in1, '-');
read(ch1);
write(ch1, '-');
read(re1);
writeln(re1);
End.
Inst. Waheed Al-Sayer 48
Self Test
Ohm's law states that the voltage (V) in a circuit is equal to
the current flowing in amperes (I) multiplied by the
resistance in the circuit (R) [ V = I * R ]. Write a program
to enter in the values of resistance and current, displaying
the voltage which would exist.
Write a program which inputs two resistance values, and
then displays their sum value when placed in series and
then in parallel. [ The total series resistance is R1 + R2,
whilst the parallel resistance is (R1 * R2) / (R1 + R2) ]
Inst. Waheed Al-Sayer 49
Answer 1
Ohm's law states that the voltage (V) in a circuit is equal to
the current flowing in amperes (I) multiplied by the
resistance in the circuit (R) [ V = I * R ]. Write a program
to enter in the values of resistance and current, displaying
the voltage which would exist.
Var I, R, V : real;
Begin
// input
Write(Enter Amperes and Resistance : );
Readln( I, R);
// processing
V := I * R;
// output
Writeln(Voltage = , V:4:1);
End.
Inst. Waheed Al-Sayer 50
Answer 2
Write a program which inputs two resistance values,
and then displays their sum value when placed in
series and then in parallel. [ The total series
resistance is R1 + R2, whilst the parallel resistance
is (R1 * R2) / (R1 + R2) ]
Var R1, R2, Series, Parallel : real;
Begin
// input
Write(Enter Resistance 1 and Resistance 2 : );
Readln( R1, R2);
// processing
Series := R1 + R2;
Parallel := (R1 * R2) / (R1 + R2);
// output
Writeln(Resistance in Series = , Series:4:1);
Writeln(Resistance in Parallel = , Parallel:4:1);
End.
Inst. Waheed Al-Sayer 51
Functions
Function name follows the naming standard
Functions takes a value called a parameter
function_name result
Functions return a single value
Check page 94 for a list of functions
(parameter)
Inst. Waheed Al-Sayer 52
Working with Characters/Strings
Add two strings together (Concatenation operation) +

Returns the character whose ASCII value is n Chr(n)

Returns the ASCII value (ordinal position)
of the character chr Ord(ch)

Returns the preceding ASCII value Pred(ch)

Returns the succeeding ASCII value Succ(ch)

Inst. Waheed Al-Sayer 53
Examples
Abc + def => Abcdef

Chr(66( => B

Ord)D( => 68

Pred)D( => C

Succ)B( => C
Inst. Waheed Al-Sayer 54
Good Program Formatting
Use meaningful identifiers.
Job_Type instead of XYZ.
Use proper indentation.
Good Bad
Begin Begin
Salary := 50.430; Salary := 50.430;
Writeln (Salary); Writeln (Salary);
End. End.
Use Constants for fixed numbers.
Use comments for blocks of logic, and lines of
code.
Inst. Waheed Al-Sayer 55
Yes/No Questions /
A computer can answer any question?
(Almost any question).
The computer will answer you in a Yes/No
form. Yes is True, and No is False.
The trick is to form the right question.
Have you played the Guess Who? game?
Inst. Waheed Al-Sayer 56
Guess Who? Asking the right
question
Inst. Waheed Al-Sayer 57
Boolean Expression
The result of a Boolean Expression is only
TRUE or FALSE.
A Boolean Expression must have a
comparison operator like (>, <, >=, <=, =,
< >) between two similar type operands.
Operands could be a math expression but
must be enclosed parentheses .
(Salary > 100.0) (Age = 20) ((Salary 20.0) >= 200.0)
Inst. Waheed Al-Sayer 58
Relational Operators
Operator In English
> Greater Than
< Less Than
= Equal
>= Greater Than or Equal
<= Less Than or Equal
<> Not Equal
Notice the
order >=
and not =>
Inst. Waheed Al-Sayer 59
Boolean Expressions
We can store the result of a Boolean expression in
a Boolean variable
Const
Limit = 25.0;
Var
Temperature : real;
Result1 : Boolean;
Begin
Write ( Enter the temperature :);
Readln (Temperature);
Write ( Temperature is greater than , Limit:4:1,
(True/False)? );
Result1 := Temperature > Limit;
Writeln ( Result1 );
End.
Inst. Waheed Al-Sayer 60
Knowing Odd/Even numbers using
MOD /
An Even number is a number that is
divisible by 2 with no remainder
An Odd number is a number that is NOT
divisible by 2 and has a remainder
So we can use the expression:
(Num mod 2) = 0 to check for even number
If the result is TRUE then Num is EVEN.
If the result is FALSE then Num is ODD
Inst. Waheed Al-Sayer 61
What is a Leap Year?
A Leap year is a year with 29 days in the month
February.
A Leap year is divisible by 4.
To know if a year is a leap year we use MOD.
The Boolean expression to test if a year is leap:
(Year MOD 4) = 0
Notice the parentheses around the math
expression.
Inst. Waheed Al-Sayer 62
Simple IF statement
Why?:
To execute some statements and not others, or
To protect certain statements from execution, we use IF statement.
Statement after then will run when the Boolean expression
is TRUE.
Statement after then will NOT run when the Boolean
expression is FALSE.
All variables in the Boolean expression must be known and
available BEFORE running the IF statement.
A Boolean expression is also call condition.
IF (Boolean expression) then
statement;
Inst. Waheed Al-Sayer 63
IF statement flow diagram
This diagram
shows how an
IF statement is
represented
using a flow
chart
X > 0.0
Product :=
Product * X
True
False
IF (X > 0.0) THEN
Product := Product * X;
Inst. Waheed Al-Sayer 64
IF example !
Type in and run the following program and
discuss each step, then run it with different
values:




Now change the condition.

Var X : Real;
Begin
Write(Enter a number : ); Readln(X);
IF (X >= 0.0) THEN
Writeln(X is Greater than 0.0);
End.
Inst. Waheed Al-Sayer 65
IF example 2
! 2
Type in and run the following program and
discuss each step, then run it with different
values:




Now change the condition.

Var Ch : Char;
Begin
Write(Enter a letter : ); Read(ch);
IF (Ch = I) THEN
Writeln(I know you hit me!);
End.
Inst. Waheed Al-Sayer 66
Exercise
Write a program that will read any name. If it is
your name show a message, if it is not your name
show another message.
Write a program that will read an employee
salary per hour and hours worked. Then calculate
the employee salary. If it is below 300.000 then
add 10.000. If it is above or equal 300.000 then
add 5.000. Finally, show the new employee salary.
Inst. Waheed Al-Sayer 67
IF with Compound statements
When we need more than one statement
after then we use Compound statement.
Compound statements means adding
begin/end to THEN.
Example:
IF (X > Y) then
Begin
Temp := X;
X := Y;
Y := Temp;
End;
Compound statement
Inst. Waheed Al-Sayer 68
IF with TWO alternatives
IF statement with two alternatives:
Write(Enter Grade ); Readln(grade);
IF (grade >= 60) then
Writeln(Pass)
Else
Writeln(Fail);
Writeln(Done);
Semicolon ; is not allowed
before ELSE.
We can use compound statement
after ELSE.

Inst. Waheed Al-Sayer 69
Nested IF statements (many
alternatives)
Nested IF is used to code decisions for more
than two alternatives. (p. 161)
Example:

If (X > 0) then
NumPos := NumPos + 1
Else
If (X < 0) then
NumNeg := NumNeg + 1
Else
NumZero := NumZero + 1;
Alternative 1
Alternative 2
Alternative 3
If statement 1
If statement 2
Inst. Waheed Al-Sayer 70
IF (Nested vs. Sequence) 1
Nested IF executes
only one alternative.
Nested IF used for
related conditions.
Nested IF is more
efficient.
Sequence IF could
execute more than one
alternative.
Sequence IF used for
non-related conditions.
Sequence IF needs
more processing.

Inst. Waheed Al-Sayer 71
IF (Nested vs. Sequence) 2
If (X > 0) then
NumPos := NumPos + 1
Else
If (X < 0) then
NumNeg := NumNeg + 1
Else
NumZero := NumZero + 1;

If (X > 0) then
NumPos := NumPos + 1;
If (X < 0) then
NumNeg := NumNeg + 1;
If (X = 0) then
NumZero := NumZero + 1;

Inst. Waheed Al-Sayer 72
Sequence of Ranges
Upper Limit
To check a sequence
of ranges using lower
or upper limits the
sequence has to be
connected.
Connected sequence:
0-59, 60-69, 70-79,
80-89, 90-100
Disconnected
sequence: 20-30, 35-
40, 50-60

Example of checking the upper limit of each range
IF (grade < 0) then
writeln(Error in grade)
Else
IF (grade <= 59) then
writeln(F)
Else
IF (grade <= 69) then
writeln(D)
Else
IF (grade <= 79) then
writeln(C)
Else
IF (grade <= 89) then
writeln(B)
Else
IF (grade <= 100) then
writeln(A)
Else
Writeln(Error in grade);
0
59
69
79
89
100
Inst. Waheed Al-Sayer 73
Sequence of Ranges
Lower Limit
Complete the if
statement.
Similar to checking
the upper limit, we
check the lower end
of each range.
The order has to be
revered.
0
59
69
79
89
100
Complete the Example of checking the lower limit
IF (grade > 100) then
writeln(Error in grade)
Else
IF (grade ) then
writeln(A)
Else
IF (grade ) then
writeln(B)
Else
IF (grade ) then
writeln(C)
Else
IF (grade ) then
writeln(D)
Else
IF (grade ) then
writeln(F)
Else
Writeln(Error in grade);
Inst. Waheed Al-Sayer 74
Joining Boolean expressions

There are two methods to join different
Boolean expressions:
AND is used when BOTH expressions must be
TRUE for the result to be TRUE
OR is used when ONE of the expressions is
TRUE, the result is TRUE.
The result of joining Boolean expressions is
always either TRUE or FALSE.
(Salary > 100.0) and (hours < 5)
Inst. Waheed Al-Sayer 75
Truth Tables
X Y X and Y X or Y Not X
T T T T F
T F F T F
F T F T T
F F F F T
Inst. Waheed Al-Sayer 76
English Conditions
Plain English conditions can be converted to
Boolean expressions.
For example N is in the range between X and Y inclusive:
(N >= X) and (N <= Y)
Inclusive means that the start and end values
are included in the range.
Exclusive mean that the start and end values are
out of the range.
Inst. Waheed Al-Sayer 77
CASE statement
Simpler method of writing multiple alternative nested IF
statement.
All conditions must relate to a single variable.
The variable used after case must be of type ordinal (types:
Integer, Char, Boolean).
To converted an IF statement, the IF statement has to be nested.
To catch all other values we use else at the end of the case
statement.
case variable of
values : statement;
values : statement
else statement;
end;
Inst. Waheed Al-Sayer 78
CASE statement Examples (1)
write(Enter a number between 1 and 10 --> );
Readln(Num);
case Num of
1, 3, 5, 7, 9 : Writeln(Num, is odd.);
2, 4, 6, 8, 10: Writeln(Num, is even.);
end;
write(Enter the sale value -->);
Readln(Value);
case Value of
24, 40, 50..90 : Writeln(Value is too high.);
25, 41..49 : Writeln(Value is correct.);
end;
Inst. Waheed Al-Sayer 79
CASE statement Examples (2)
write(Enter M for mom, or D for dad --> );
Readln(MomOrDad);
case MomOrDad of
M, m : Writeln(Hello Mom, you are the best.);
D, d : Writeln(Hello Dad , you are the best.);
end;
write(Enter your age -->);
Readln(Age);
case Age of
0..25 : Writeln(You are still young.);
26..99 : Writeln(You are too old.)
else Writeln(Wrong answer);
end;
Inst. Waheed Al-Sayer 80
Loops
A loop executes a set of statements a number of
times.
The variable used in the loop called a control
variable.
There are three parts of a loop that must exists for
a loop to succeed:
Initialize the control variable
Test the control variable
Update the control variable
Inst. Waheed Al-Sayer 81
WHILE loop example
I := 1;
While (I <= 5) do begin
writeln( I );
I := I + 1;
End;
Initialize I to 1
Test if I > 5
Update I, add 1 to I
Write a loop to:
Print the numbers from 10 to 20.
Print the characters from a to g.
Print odd numbers from 5 to 19.
Print even numbers from 4 to 20.
Print the numbers from -15 to 0
Print the characters from g to a.
Print the numbers from 15 to 0.
Print every other character from a to z.
Print multiplication table for the 5.
Inst. Waheed Al-Sayer 82
Using loops to find results
Find SUM of a sequence of numbers:
Generated by the loop.
Entered by the user.
Finding AVERAGE of a sequence of
numbers.
Finding the Highest and Lowest values of a
sequence of numbers.
Finding other results (Sum of Squares).
Inst. Waheed Al-Sayer 83
Loop types
Counter Controlled loop
Known number of loops
Starts and ends with a known value
Event Controlled loop
An unknown number of loops
The condition checks for a certain event that determines the termination of
the loop
Sentinel Controlled loop
An unknown number of loops
The condition checks for the final value which is called a sentinel
Inst. Waheed Al-Sayer 84
Loop Types (Counter Loop)
Loops that are based on a
counter.
The start and end values of
the counter are known
before the loop starts.
The loop increments the
control variable (counter)
by a fixed value.
The control variable
(counter) can be numeric
or character.
I := 0;
While (I < 5) do begin
Writeln(I = , I);
I := I + 1;
End;
Inst. Waheed Al-Sayer 85
Loop Types (Event Loop)
Event loops are the general loop
that is based on an event .
Counter Loop can be considered
an Event Loop, and the event is
reaching the end/final value.
The event controls the
termination of the loop.
The number of times the loop
loops is unknown.
Sometimes there can be two
events that control the
termination of the loop.
Write(Enter the balance );
Readln(Balance);
While (Balance > 0) do begin
Write(Enter the item cost );
readln(item_cost);
Balance := Balance item_cost;
End;
Inst. Waheed Al-Sayer 86
Loop Types (Event Loop) (2)
Another example of
an event loop is to
control a menu.
This is similar to
menus.
Writeln(1 Sum);
Writeln(2 Factorial);
Writeln(------------);
Write(Select a number or 0 to exit: );
Readln(choice);
While (choice <> 0) do begin
case choice of
1 : begin
Write(Enter two numbers );
Readln(no1, no2);
Writeln(The sum of , no1, and , no2, is ,
no1 + no2);
end;
2 : begin
fact := 1;
Write(Enter a number );
Readln(no1);
while (no1 < = 1) do begin
fact := fact * no1;
no1 := no1 1;
end;
Writeln(The factorial of , no1, = , fact);
end;
End;
Writeln(1 Sum);
Writeln(2 Factorial);
Writeln(------------);
Write(Select a number or 0 to exit: );
Readln(choice);
End;
Inst. Waheed Al-Sayer 87
Loop Types (Sentinel Loop)
The loop reads a set of
values.
A special value
(sentinel) terminates
the set of values.
The special value
should not be in the list
of values, it should be
a unique value.
All values must be of
the same type.
Sum := 0;
Write(Enter the list of values );
Readln(value);
While (value <> 0) do begin
Sum := Sum + value;
Write(Enter another value or 0 to stop );
readln(value);
End;
Inst. Waheed Al-Sayer 88
Repeat Loop
Repeat loop is opposite of While loop.
In While loop we check then we execute
In Repeat loop we execute first then we
check.
The same three parts exist in a Repeat loop.
I := 1;
Repeat
Writeln(I);
I := I + 1;
Until (I > 5);
Inst. Waheed Al-Sayer 89
For loop
FOR loop is the simplest of the three loops.
All three parts of a loop are in the first line.
Initialize (i:=1) start from 1
Test (5) until you reach 5
Update (to ) increment by 1 (+1)
It only accepts an ordinal (integer/char) Control
Variable.
It increments the control variable by one only.
To decrement by one use downto instead of
to.
For i:=1 to 5 do
Writeln(I);
For i:=5 downto 1 do
Writeln(I);

Vous aimerez peut-être aussi