Sunteți pe pagina 1din 20

Programming Languages and Techniques I

1
Federal University of Paraíba
Algorithms and PASCAL
Professor: Gilberto Farias de Sousa Filho
JOAO PESSOA / PB MARCO DE 2005
Programming Languages and Techniques I
2
Chapter 1
ALGORITHMS
1.1. CONCEPT
The word algorithm, at first glance, it seems strange. Although it has name unkn
own, we make use of algorithms constantly in our daily life: the way a person ta
kes a bath is an algorithm. Other algorithms are often found: • • • • • instruct
ions for using an appliance, a recipe for preparing a dish; guide to completing
the declaration of income tax, the rule for determining maximum and minimum of f
unctions by successive derivatives ; how water bills, electricity and telephone
are calculated monthly, etc.
Several concepts for the algorithm. We chose some to be presented here: "A finit
e set of rules that provides a sequence of operations to solve a specific type o
f problem [Knuth]" orderly sequence, and unambiguous, the steps that lead to sol
ving a given problem [ TREMBLAY] "Procedure for calculating or solving a group o
f similar problems, which stipulates, in general, without limitation, the formal
rules for obtaining the result or the solution of the problem" [Aurelius]
1.2. WHY WE NEED ALGORITHMS?
Here's what some important people for Computer Science, said about the algorithm
: "The notion of algorithm is basic to all computer programming." [Knuth - Stanf
ord University Professor, author of the collection "The art of computer programm
ing"] "The central concept of programming and computer science is the concept of
algorithm." [WIRTH - Professor, University of Zurich, author of several books i
n the area and responsible for creating programming languages like Algol, Pascal
and Modula-2] The importance of the algorithm is in fact terms that specify a s
equence of logical steps to the computer can perform any task, because it alone
had no choice, just do what we order. With an algorithmic tool, we can design a
solution to a given problem, regardless of a specific language and even the comp
uter itself.
1.3. FEATURES
Every algorithm must present some basic characteristics: • • • • • have an end,
not give rise to double reading (not ambiguous); ability to receive data (s) of
entry from the outside world, to generate output information to the outside worl
d to the environment of the algorithm, to be effective (all steps specified in t
he algorithm must be reached in a finite time).
Programming Languages and Techniques I
3
Programming Languages and Techniques I
4
1.4. FORMS OF REPRESENTATION
Algorithms can be represented, among other ways, by: 1.4.1. NARRATIVE DESCRIPTIO
N It is used to describe the Portuguese algorithms. EXAMPLE: Recipe for Cake: Ar
range butter, eggs, 2 pounds of pasta, etc.. Mix ingredients Pour the mixture in
to the cake pan Bring the pan to the oven Wait 20 minutes Remove pan from oven C
ool Prove ADVANTAGES: • Portuguese is well known to us; DISADVANTAGES: • vaguene
ss; • unreliability (the vagueness entails distrust) • Extension (usually writte
n as much to say little). 1.4.2. FLOWCHART use of graphic symbols to represent a
lgorithms. In the flow chart symbols are standardized for initiation, data entry
, calculations, data output, order, etc..
Calculation
Decision EXAMPLE
Entry
Output Explanation
Start / End
Home Read NUM
Top of the algorithm
Input number
DOUBLE <- NUM * 2
Calculation of double the number
Write DOUBLE End ADVANTAGES: • One of the best known tools; • Pictures speak lou
der than words; • Standard global
Presentation of results
End of algorithm
DISADVANTAGES: • It makes the solution of the problem is already tied to physica
l devices; • Little attention to data, not offering features to describe them or
represent them;
Programming Languages and Techniques I
5
• complicates itself as the algorithm grows. 1.4.3. LANGUAGE algorithm consists
in defining a pseudolinguagem programming, whose commands are in Portuguese, to
represent algorithms. EXAMPLE: Algorithm CALCULA_DOBRO early Read 2 * IN A DOU
BLE IN DOUBLE Write order
ADVANTAGES: • Physical independence of the solution (only logical) • Uses the Po
rtuguese as a base; • You can define what and how data will be structured; • Pas
sage almost immediate algorithm to any one programming language.€DISADVANTAGES:
• Requires the definition of a language not for real work • Not standardized.
1.5. AN ENVIRONMENT FOR WRITING ALGORITHMS
Describe a hypothetical machine for which write our algorithms. Our hypothetical
computer displays the following organization: Central Processing Unit (2) Arith
metic and Logic Unit (1) Input Device (3) Control Unit (5) Output Device
(4) Main Memory
Convention:
path of data path control signals
Each of the constituent parts of the figure above has the following meanings: (a
) Input device (keyboard): It is the means by which the data that will be worked
by the algorithm will be introduced in our hypothetical computer, (2) Logic Uni
t arithmetic (ALU): Party responsible for mathematical operations and logical as
sessments, (3) Control Unit: It exerts control over other parts of our computer.
It is a real manager who distributes tasks to other units, (4) Memory: Stores t
he algorithm to be executed and data to be used by it. All data supplied to the
computer and the results of its operations are stored in memory;
Programming Languages and Techniques I
6
(5) Output Device (video and printer): It is the means that are available for pr
esentation of results. 1.5.1. OPERATION OF OUR COMPUTER All computers, regardles
s of their sizes, are conceptually similar to the layout of the previous figure
(there are some differences, but not discussed here the special cases). Briefly,
we can say that there are four (4) basic operations that any computer can perfo
rm: a) input and output operations: read data from the keyboard and write data o
n the screen are examples of these operations. They are used to enter data in th
e memory of our computer and display data that is already stored there;
b) arithmetic operations: they are used in performing mathematical operations (a
ddition, subtraction, multiplication and division), c) logical and relational op
erations: they have applicability in comparison, tests on logical conditions (2>
6 "X = Y?)
d) moving data between the various components: the arithmetic operations are per
formed in the Arithmetic Logic Unit, requiring the transfer of data to that driv
e and turn the final result to be stored in memory.
Chapter 2
PASCAL PROGRAMMING LANGUAGE
3.1. INTRODUCTION
To store an algorithm in a computer memory and he can then command the operation
s to be performed, it needs to be programmed, ie which is transcribed into a lan
guage the computer can understand, directly or indirectly .
3.1.1. PROGRAMMING LANGUAGES Language is a way of communication that follows a s
hape and structure with interpretable meaning. Therefore, language is a finite s
et of words, commands and instructions written in order to guide the completion
of a task by the computer. Logically, the language we use in our daily life is d
ifferent from the language used by the machine. The machine works only with code
numbers (machine language) based on the numbers 0 and 1 (binary system), which
represent electrical impulses, absent and present. Thus, any programming languag
e must be situated between two extremes: the natural language of man (very clear
, but slow) and machine language (very fast but complex). This is the concept of
language-level: high level to the closest of human language, low level to the m
ost similar to machine language.
3.1.2. TRANSLATION For one computer can "understand" a program written in a high
-level language, it becomes a necessary means of translation between the languag
e used in the program and machine language. This medium can be of two types: the
compiler and interpreter.
Programming Languages and Techniques I
7
Compiler - translates programs written in high level language (source program) t
o an equivalent program written in machine language (object program).
Source Program Ling. High Level COMPILER
Program Object Ling. Low
Executive TION
Results
Interpreter - translates and sends them to execution, instruction by instruction
and the program remains in the form source.
Source Program Ling. High Level INTERPRETING
IMPLEMENTATION
Results
Examples of programming languages: Pascal, C, CLIPPER, BASIC, COBOL, etc..
Programming Languages and Techniques I
8
3.1.3. LANGUAGE PASCAL programming language PASCAL is designed to be an educatio
nal tool, that in the early 70s by Professor. Niklaus Wirth, University of Zuric
h.€It was named for its founder in honor of the great mathematician Blaise Pasca
l, inventor of one of the first logical machines known. Was based on some struct
ured languages existing at the time, and ALGOL PLI. Despite its initial purpose,
the PASCAL began to be used by programmers of other languages, becoming, to the
surprise of his own Niklaus, a commercial product. However, only the end of 198
3 was that the American company Borland International released TURBO PASCAL. Tur
bo Pascal is a program that contains, besides the PASCAL compiler, a complete pr
ogramming environment, with program editor, debugger, error-help system, etc.. W
e will study the following are key items that make up the language PASCAL.
3.2. BASIC ELEMENTS
3.2.1. Identifiers are names chosen to represent constants, variables, types, fu
nctions, procedures, units, programs and fields of a record. To define an identi
fier, we should note the following: • can have any length, but only 63 / 1 chara
cters are significant, • must have a letter as first character; • after the firs
t letter can only contain letters, digits or underscore ( _) • can not contain s
paces; • uppercase and lowercase letters are indifferent; • identifiers can not
be repeated; • can not be a reserved word. 3.2.2. Reserved words are words that
have a predetermined direction in language and can not be used as identifiers. A
BSOLUTE AND ARRAY BEGIN CASE CONST DIV downto ELSE END OF FILE EXTERNAL FUNCTION
GOTO IF FORWARD FOR IMPLEMENTATION IN INLINE LABEL INTERRUPT INTERFACE MOD NIL
NOT OF RECORD OR PACKED PROGRAM REPEAT PROCEDURE SET SHL SHR STRING UNIT THEN TO
TYPE UNTIL VAR WHILE WITH USES XOR
Programming Languages and Techniques I
9
3.3. TYPES OF DATA
3.3.1. SIMPLE INTEGER - Involves the integers. In version 5.0 of Turbo Pascal, t
here are also other types of integers: SHORTINT, BYTE, WORD and LongInt. Type SH
ORTINT BYTE INTEGER WORD LongInt Minimum -32 768 -128 0 0 -2147483648 Maximum 12
7 255 65 535 3276 7 2147483647 Bytes occupied January 1 2 2 4
Examples: -45, 1, 138, 0, -2 REAL - covers the actual numbers. In version 5.0, t
here are also other types of real numbers: SINGLE, DOUBLE, EXTENDED and COMP. RE
AL SINGLE DOUBLE EXTENDED COMP Minimum 2.9 x 10-39 1.5 x 10-45 5.0 x 3.4 x 10-32
4 10-4932 -263 + a maximum value 1.7 x 1038 3.4 x 1038 1.7 x 1.1 x 10 308 104 93
2 263-1 Bytes busy April 6 8 10 8 significant digits 7-8 15-16 11-12 19-20 19-20
Examples: 4.5, -32.0, .5, 7.8E3, 21E +3 315E-3-CHAR - represents a single charac
ter, enclosed by single quotes ('). Most computers use the ASCII chart to repres
ent all characters available. Examples: 'A', 'B', 'a', '1 ',' @ ',' BOOLEAN - re
presents a logical value. Uses only two logical constants: TRUE (true) and false
(false).
3.3.2. STRUCTURED STRING - formed by a set of elements of type CHAR. characters.
Examples: 'ragged', 'Data Processing', '123 'discuss in more detail the type st
ring in a chapter specially devoted to this purpose. Other types of structured d
ata are: ARRAY, RECORD, FILE, SET and TEXT and will be introduced later in the b
ook. The maximum size is 255
3.3.3. DEFINED BY THE USER Pascal allows programmers, besides using the predefin
ed types in the language, can also create new data types. This becomes very usef
ul when dealing with complex data structures, but also helps make the program mo
re readable. This subject, by their complexity, will be discussed later.
Programming Languages and Techniques I
10
3.4. Arithmetic Expressions
They are expressions where we use integers or real as operands and arithmetic op
erators, always giving numerical values as a result. 3.4.1. Arithmetic Operators
Arithmetic operators represent the most common operations in mathematics. They
are: Operator + * / DIV MOD EXAMPLES: 1 +2 Expression 5.0 - 1 2 * 1.5 5 / 2 5 DI
V February 5 MOD 2 Result 3 4.0 3.0 2.5 2 1 Operation Addition Subtraction Multi
plication Division Remainder of Integer Division Real Operands Integer Division
, Real, Integer, Real, Integer, Real, Integer, Real Results Integer Integer Inte
ger, Real, Integer, Real, Integer, Integer Integer Real Real
3.4.2. PRIORITY In an arithmetic expression, the evaluation order of operators o
bey the following table: Priority 1st 2nd COMMENTS: a) When there is an expressi
on of operators with the same priority, execution is from left to right. b) If n
ecessary change the order of priority, you should use parentheses. The words in
parentheses have priority. If there are nested parentheses,€the execution order
is the innermost to the outermost. EXAMPLES: 2 + 3 / 2 = 2 + 1.5 = 3.5 (2 +3) /
2 = 5 / 2 = 2.5 * Operators / DIV MOD + -
3.4.3. FUNCTIONS AND PROCEDURES Default Number subprograms are ready available t
o users, to calculate the most common mathematical functions. Function ABS (X) F
RAC (X) TRUNC (X) ROUND (X) SQR (X) SQRT (X) LN (X) EXP (X) Purpose Absolute Val
ue Part Fractional Part Full Value Rounded to square Logarithms Exponential Squa
re Root argument type Integer, Real Real Real Real Integer, Real, Integer, Real
Real Real result of the same type of argument Real Integer Integer argument the
same as Real Real Real
Programming Languages and Techniques I
11
Since there is an operator in Pascal or a specific function for the operation of
potentiation, we can get it using the function LN (X) and EXP (X). To calculate
the value of XN is sufficient to use: EXP (LN (X) * N) EXAMPLES: Expression ABS
(-2.5) ABS (8) FRAC (5234) TRUNC (2.78) ROUND (2.78) SQR (2) SQR (1.5 ) SQRT (4
) SQRT (2.25) EXP (LN (2) * 3) Income 2.5 8 0,234 2 3 4 2.25 2.0 1.5 8
3.5. LOGICAL EXPRESSIONS
The logical operations may be considered statements that will be tested by compu
ter, resulting in a true or false value. Are used with relational operators and
logical.
3.5.1. Relational operators are used to compare two expressions of any type, ret
urning a logical value (TRUE or FALSE) as a result of the operation. Operator =>
<> = <= <> Operation equal greater less or more or less different
Note: the logical operations can only be made with respect to values of the same
type. EXAMPLES: Expression 1 = 2 'A' = 'a' 5> 2 3 <3 = TRUE <FALSE 'JOAO'> 'JOS
E' 2 + 3 <> 5 'comp' <> 'COMP' '11 '<'4 'Result FALSE FALSE FALSE FALSE FALSE TR
UE TRUE TRUE TRUE
3.5.2. Logical operators are used to combine logical expressions. Operator and o
r not Operation not (negation) and (conjunction) or (disjunction)
Programming Languages and Techniques I
12
The truth table (below) shows the result of each logical operator, with given va
lues for the logical expressions A and B: B TRUE TRUE FALSE FALSE TRUE FALSE TRU
E FALSE TRUE FALSE A and B or B FALSE FALSE FALSE TRUE TRUE TRUE NOT A FALSE FAL
SE TRUE TRUE FALSE TRUE FALSE NOT B TRUE
3.5.3. PRIORITY In a logical expression, the evaluation order of operators follo
ws the table below: Priority 1st 2nd 3rd 4th Operators AND OR NOT> <> = <=
=
<>
Because the order of precedence of logical operators is greater than the relatio
nal operators, parentheses should always be used when writing a complex logical
expression. For example: (A> B) OR (B = C)
SUGGESTED EXERCISES
P3.13. What is the result of arithmetic expressions below, knowing that the valu
es of X, Y and Z are, respectively, 1, 2 and 5? a) b) c) d) e) div Y mod Z Y X +
Y + Z / 3 FRAC (X / Z) + ROUND (Z / y) * TRUNC (Z / Y) SQRT (Z + X * Y div Y) Z
- ABS (X - SQR (Y))
P3.14. What are Predefined Functions? P3.15. Write the result of the following f
unctions: a) b) c) d) e) f) g) h) i) j) k) l) ABS (-4) ABS (5.2) FRAC (23.0) FRA
C (-3.1) TRUNC (1.8) TRUNC (2.2) ROUND (1.8) ROUND (2.2) SQR (1.0) SQR (10) SQRT
(25) SQRT (9.0)
P3.16. Type the expression to calculate the value of 25. P3.17. Fill in the Trut
h Table below: A B TRUE TRUE FALSE FALSE TRUE FALSE TRUE FALSE BA or B and not A
not B
Programming Languages and Techniques I
13
P3.18. Write the result of the following comparisons: a) b) c) d) e) f) g) 3 = 3
.0 'a' <= 'A' '' = '' 'HOME' <> 'home' FALSE = FALSE 'JOAQUIM '<' JOSE ''22'> '2
00 '
P3.19. What is the result of logical expressions below, knowing that the values
of A and B are, respectively, TRUE and FALSE? a) b) c) d) not A and B A and not
B or not (not (A or B) and (A or B)) A or B and not A or B not (A or B) and (not
A or not B)
3.6. FORMAT OF A PASCAL PROGRAM
Pascal is a highly structured language that has a rigid set, although its progra
m structure is flexible. Each section or part of a program in Pascal must appear
in proper sequence and automatically be correct, otherwise an error occurs. Mor
eover, in Pascal there specific rules for the use of space, broken lines, requis
itions, and so commands can be written in free format in almost all the styles i
n which the programmer wishes to use. A program written in Pascal has the follow
ing format: PROGRAM <identifier>; <bloco>. The <bloco>, in turn, is divided into
six areas, where only the latter is mandatory and should follow the sequence be
low.€They are: • Area of declaration of use of units • Area declaration of const
ants Area • • Area type declaration of variable declarations • Area declaration
procedures and functions • Area Command NOTE: In Turbo Pascal, the clause PROGRA
M and the correct sequence of statements, are not mandatory.
3.6.1. DECLARATION OF USE OF UNITS A Pascal program can make use of some units t
hat are available in standard Turbo System, such as CRT, DOS, PRINTER, GRAPH, et
c.. The area of the declaration of use of units has the following format: EXAMPL
E USES: USES CRT, PRINTER; <drive> ... , <drive>;
Programming Languages and Techniques I
14
3.6.2. DECLARATION OF CONSTANT serves to associate names to the constants used i
n the program. Has the following format: CONST <identifier> <value> ;...;< ident
ifier => = <value>; SAMPLE: WHITE CONST = ''; PI = 3.1416; MAX = 10; OK = TRUE;
3.6.3. DECLARATION OF TYPES serves to define new types and data structures. Not
detail this topic by now be the subject of the next chapters ..
3.6.4. DECLARATION OF VARIABLES serves to associate types with variables used in
the program. Has the following format: VAR <lista-de-identificadores>: <type>;
... <lista-de-identificadores>: <type>; Where: <lista-de-identificadores> <type>
is a list of variable names for the same type, separated by commas. is the name
of one of the predefined types in the language or created by the programmer.
EXAMPLE: VAR X, Y, Z: REAL; I, J: INTEGER; FOUND: BOOLEAN; LETTER: CHAR, WORD, P
HRASE: STRING;
3.6.5. STATEMENT OF PROCEDURES AND FUNCTIONS In this area are defined procedures
and functions used by the program. It is also an issue that will be detailed la
ter.
3.6.6. AREA COMMANDS This is the area where it is inserted into the algorithm of
the program. Commands are separated by the delimiter point semicolon. The gener
al form is: BEGIN <command>; ... ; <command> END
Programming Languages and Techniques I
15
3.7. COMMENTS
A comment is used to increase the clarity of a program, although not analyzed by
the computer. Should be written in braces (comment)
EXAMPLE: Program REAJUSTE_SALARIO; (Purpose: Calc. the readjustment of salary 20
%) Uses Crt; Const IND = 0.20; Var () index of readjustment
Current salary SAL_ATUAL (), (SAL_NOVO new salary), (INCREASE ReRaise): Real;
Begin clrscr; (clears screen) (read the current salary) write ('Enter the curren
t salary'); ReadLn (SAL_ATUAL);) (computation of readjustment INCREASE: * = SAL_
ATUAL IND; SAL_NOVO: = SAL_ATUAL + INCREASE; ( Display results) writeln ('New Sa
lary =', SAL_NOVO: 10:2); ReadKey; End
SUGGESTED EXERCISES
P3.20. What is the basic form of a Pascal program? P3.21. What areas can exist i
n a block of Pascal? Which one is it mandatory? P3.22. What is the purpose of th
e following areas: a) b) c) d) e) f) Declaration of Use of Units Constants Decla
ration Declaration Declaration Type Variable Declaration Procedures and Function
s Area Commands
P3.23. Give an example for each of the following areas: a) Declaration of Use of
Units b) Declaration of Constants c) Declaration of Variables P3.24. What is th
e purpose of a commentary in a program? How should it be written?
Programming Languages and Techniques I
16
Chapter 4
CONTROLS BASIC LANGUAGE PASCAL
4.1. ALLOCATION
The assignment statement has the form: <identifier>: = <expression> In the assig
nment statement, variable and expression must be the same type, except in the fo
llowing cases: a) the variable being real, the expression can be integer b) the
variable is string, the expression can be char EXAMPLES: Var IRSC IRCS Begin End
::::: =: =: =: = Integer, Real, String, Char, 5, I. 'A', C
4.2. INPUT
An input command serves to request that the program data at the time that it is
running. These data will be stored in variables in memory. In general the unit o
f input is the keyboard, can also be an auxiliary memory such as Winchester. Con
sidering the standard input unit, the keyboard, the command would be: READ (<ide
ntificador-1> ,...< identifier-n>) or ReadLn (<identificador-1> ,...,< identifie
r-n>) READ with the cursor stays on the same line after running the command; Rea
dLn with the cursor moves to the next line. Note: In Turbo Pascal, the READ comm
and should only be used for reading files. So for reading variables, we should a
lways use the command ReadLn.
EXAMPLES: 1) If the program should ask the three notes of a student, we would ha
ve: ReadLn (NOTE 1, NOTE2, Note3) ... At the time of execution of the command ab
ove,€the program shows the user's screen and the cursor appears waiting typing o
f the three values that must be separated by at least one blank space.
Programming Languages and Techniques I
17
3.5 will be stored in the variable NOTE 1, the 7.0 and 8.2 in NOTE2 Note3. 2) If
the program should request the name and salary of an employee would: ReadLn (NA
ME); ReadLn (SALARY); ...
4.3. OUTPUT
A command used to exit the program shows the user the desired results. The outpu
t unit is the standard video monitor and can also be a printer or an auxiliary m
emory such as disk. Considering the standard unit of output, the video monitor,
the command would be: WRITE (<expressão-1> ,...,< expression-n>) or ... WriteLn
(<expressão-1> ,...,< expression-n>) WRITE With the cursor stays on the same lin
e after running the command; WriteLn with the cursor moves to the next line. EXA
MPLE: A: = 1, B: = 2; writeln ('Sum of' A 'and' B '=', A + B) ...
In the case of variables of type REAL values are shown in exponential notation i
n a field of 16 positions, unless a format is specified. EXAMPLE: MEDIA: = (8.0
+ 2.0) / 2 writeln (MEDIA) (exit → 5.0000000000E +00) writeln (MEDIA: 5:2); ou
tput → (5:00)
On formatting, if the variable is real specify the total positions held and the
amount of decimal places. If whole, only the total number of positions.
If we wish the output is through the printer and not the video monitor, we must
specify the beginning of the list of output parameter LST and unity with the PRI
NTER USES. EXAMPLE: Uses PRINTER,::: writeln (LST, 'Media =' MEDIA: 5:2);
In the instant data request, we can use along with the READ or ReadLn a command
output in order to send messages to guide the user in data entry. EXAMPLES: writ
eln ('Enter Name'); ReadLn (NAME), writeln ('Enter the third Notes:'); ReadLn (N
OTE 1, NOTE2, Note3) writeln ('Enter the employee's salary'); ReadLn (salary);
Programming Languages and Techniques I
18
SUGGESTED EXERCISES
P4.01. Exemplifies the use of the command assignment. P4.02. What is the purpose
of a command input? Give examples. P4.03. What is the difference between comman
ds and ReadLn READ? P4.04. What is the purpose of a command output? Give example
s. P4.05. What is the difference between commands and WRITE WriteLn? P4.06 How c
an we direct the output from one program to the printer? Give examples. P4.07. H
ow can we assist users in data entry? Illustrate. P4.08. Write the commands need
ed to: a) read the name of a person b) read the three notes of a student c) read
the weight and height of a person P4.09. Write a program in Pascal to calculate
and display the value of xy, and the data base (x) and exponent (y). P4.10. Wri
te a program to read the name and surname of a person and write them in the foll
owing manner: last name followed by a comma and the name. Example: input: "Anton
io", "Smith" output: Soares, Antonio
4.4. CONTROLS FOR DECISION
Decision-making structures (conditional) are used to make a decision based on th
e evaluation result of a control condition and selects one or more possible acti
ons (commands) to be executed by the computer. In Pascal, there are three types
of decision-making structure: The IF command, which can be used in two ways: sim
ple or compound, and the CASE command, which is used for a selective decision.
4.4.1. SIMPLE DECISION (IF-THEN) Used when you want to perform an action (a comm
and or command sequence) if a certain condition is true. The decision structure
simple Pascal is the IF, and should be used as follows: IF THEN <condition> <com
mand> this case, the <command> only be executed if the result <condition> the va
lue TRUE. The <condition> must be a logical expression. The <command> can be a s
imple command or a control compound. A compound statement is formed by two or mo
re commands, separated by a semicolon and delimited by BEGIN and END. EXAMPLE: P
rogram EXEMPLO_DE_DECISAO_SIMPLES; (Read an integer and display it if it is posi
tive)
Programming Languages and Techniques I
19
Var N: integer; Begin ReadLn (N) if N> 0 then writeln (N) End
In the above example, the WRITE command is only executed if the condition N> 0 i
s true. Otherwise, no action is taken.
4.4.2. COMPOUND DECISION (IF-THEN-ELSE) Used when you want to run one of two com
mands (or one of two sequences of commands) depending on the result of a conditi
on. The decision framework consists of Pascal is also the IF, but executed with
the following syntax: <condition> IF THEN ELSE <comando1> <comando2> this case,
if the <condition> result in the value TRUE, will run the <comando1> , otherwise
it will run the <comando2>. Here again,€<condition> to be a logical expression,
and <comando1> <comando2> and should be a simple command or a control compound.
EXAMPLE: Program EXEMPLO_DE_DECISAO_COMPOSTA; (Reads and determine whether a nu
mber is greater than zero or not) var N: integer; Begin redln (N) if N> 0 then w
riteln (N, 'is greater than zero') else writeln (N , 'is not greater than zero "
) End
In this example, the message that appears depends on the result of logical expre
ssion N> 0. If true, it executes the WRITE command that follows the word THEN. O
therwise, it executes the WRITE that follows the word ELSE. In no event will run
the two commands. In more complex algorithms, it is common to use nested IF's,
ie a structure as having IF <command> another structure IF.
Programming Languages and Techniques I
20
EXAMPLE: Program EXEMPLO_DE_IFS_ANINHADOS; (Determine if a number is higher, low
er or equal to Var N: integer; Begin ReadLn (N) if N> 0 then writeln (N, 'is gre
ater than zero') else if N <0 then writeln (N, 'is less than zero') else writeln
(N, 'equals zero ") End zero)
It may be noted that several lines of this program ended without point-colon, be
cause the point-colon is only used to separate commands and / or structures.
One should be careful when using nested IF's, because the ELSE clause is always
related to the last IF. If within a program, we need to get around this fact, we
can do it with the delimiters BEGIN and END. EXAMPLE: Algorithmic Language is C
OND1 COND2 If so then command1 else if Command2 LANGUAGE PASCAL COND1 COND2 then
begin if command1 then end else Command2
4.4.3. MULTIPLE DECISION (CASE-OF) Used when you want to run one of several comm
ands (or one of several sequences of commands) depending on the result of an exp
ression. The structure of selection (multiple decision) is the Pascal CASE, and
obeys the following syntax: CASE OF <expression> <lista-de-constantes-1>: <coman
do-1>; <lista-de-constantes-2> : <comando-2>; ... [ELSE <comando-n>] END <expres
sion> must result in scalar type (other than the REAL and STRING). The <lista-de
constantes-x> must contain one or more constants (comma separated), and should b
e the same type of <expression>. The <comando-x> a command can be simple or comp
ound. The results are compared with each <expression> constant <lista-de-constan
te> to check equality. If the equality is verified, the corresponding <command>
runs and finished structure. If no equality is verified, the corresponding <comm
and> ELSE (optional) will run.
Programming Languages and Techniques I
21
EXAMPLE: Program EXEMPLO_DE_DECISAO_MÚLTIPLA; (simulator a basic calculator inte
ger) Uses CRT; Var X, Y: integer; OP: char; Begin clrscr; write ('Enter the oper
ands'); ReadLn (X, Y), write ('Enter the operator:'); ReadLn (OP) OP case of '+'
: writeln (X + Y) '-': writeln (X - Y);'*',' x ',' X ' : writeln (X * Y) '/': wr
iteln (X div Y) else writeln ('invalid operation') end (case); ReadKey; End In t
his example, the message that appears depends on the contents of the variable OP
. If set to one of the constants specified, will run the corresponding command W
riteLn. If no constant is equal to the contents of OP, will run from the WriteLn
ELSE. We can also write the same program without using up the CASE structure, o
nly using nested IF's. EXAMPLE: Program EXEMPLO_DE_DECISAO_MÚLTIPLA_2; (simulato
r a basic calculator integer) Uses CRT; Var X, Y: integer; OP: char; Begin clrsc
r; write ('Enter the operands'); ReadLn (X, Y), write ('Enter the operator:'); R
eadLn (OP) if OP = '+' then writeln (X + Y) else if OP = '-' then writeln (X - Y
) else if (OP ='*') or (OP = x) or (OP = 'X') then writeln (X * Y) else if OP =
'/' then writeln (X div Y) else writeln ('op.inválida'); ReadKey;
Programming Languages and Techniques I
22
End
SUGGESTED EXERCISES
P4.16. What decision-making structures exist in Pascal? P4.17. In what situation
s is more appropriate to use the CASE structure-OF? P4.18. In what situations we
can not use the CASE structure-OF? P4.19. Controls (i) and (ii) are equivalent?
Explain your answer. (I) A: = B = C (ii) if B = C then A: = True Else A: = FALS
E
P4.20. Note the following program: Program Nó_no_juizo; Var L1, L2, L3: char; Be
gin ReadLn (L1, L2, L3) (should be typed only the letters V or F) if L1 = 'V' th
en write ('A' ) else if L2 = 'V' then if L3 = 'V' then write ('B') else begin wr
ite ('C'), write ('D') end; write ('E'); End Now answer the following questions:
a) b) c) d) If read V, V and F, which will be written by the program? If read F
, V and F, which will be written by the program? If read F, V and V€what will be
written by the program? What values should be read to be written only 'E'?
P4.21. Write a program to read a positive integer and determine if it is even or
odd. P4.22. Want to calculate the income tax of a taxpayer. For this, write a p
rogram that: a) read the following information from the taxpayer: SSN, name, ann
ual income, withholding tax, pension contributions, medical expenses, number of
dependents;
b) is reduced by the amount of R $ 1,080.00 for each dependent, c) calculating t
he total value of deductions: pension contributions + + deduct medical expenses
of dependents, d) calculation of the calculation basis: annual income - total de
ductions; e) based on the table below: Basis to 10800.00 from 10800.01 to 21600.
00 21600.00 tax rate above 15% 25% Exempt Portion to Deduct 1620.00 3780.00
Calculation of tax due: (calculation base x tax rate) - plot to deduce
Programming Languages and Techniques I
23
f)
will be no tax payable if the difference between the tax payable and tax deducte
d at source is positive, otherwise there will be a tax refund.
g) displays all the read data and calculated.
4.5. REPEATING COMMANDS
Besides allowing the change in execution sequence to a set of commands of a prog
ram, the control structures of a language, have the resources to repeat the exec
ution of a set of commands. In Pascal, there are three types of repetition struc
ture: with a test at the beginning (WHILE), with a test at the end (REPEAT) and
automatic (FOR). 4.5.1. REPEAT TEST WITH NO HOME (WHILE-DO) WHILE The control st
ructure allows a simple or compound command is executed repeatedly while a contr
ol condition is TRUE. The general form of the WHILE is: WHILE THE <condition> <c
ommand> The <condition> must be a logical expression. The <command> can be a sim
ple command or a control compound. How the test is performed <condition> early i
n the loop, <command> runs zero or more times, depending on the evaluation of <c
ondition>. EXAMPLE: Program EXEMPLO_DE_WHILE; write the integers (100-100) var N
: integer; Begin N: = 1, while N <= 100 do begin writeln (N), N: = N + 1 End End
In this example, WriteLn command is executed repeatedly while the variable N ha
s a value equal to or less than 100. The program will output the sequence of who
le numbers 1-100. 4.5.2. REPEAT TEST WITH NO END (REPEAT-UNTIL) The control stru
cture REPEAT command allows a simple or compound is performed repeatedly until a
control condition is FALSE. The general form of the REPEAT: REPEAT UNTIL <comma
nd> <condition> The <condition> must be a logical expression. The <command> can
be a simple command or a control compound. There is no need of the delimiters BE
GIN and END in the command compound in a REPEAT. How the test is performed <cond
ition> the end of the loop, <command> runs one or more times, depending on the e
valuation of <condition>. EXAMPLE: Program EXEMPLO_DE_REPEAT; (write núm. intege
rs 1-100)
Programming Languages and Techniques I
24
Var N: Integer; Begin N: = 1; repeat writeln (N), N: = N + 1 Until N> 100 End
The previous example is equivalent to the example of WHILE, where the WriteLn co
mmand will be executed repeatedly until the variable N has a value greater than
100. The structure REPEAT is also widely used to repeat a program several times,
until the user wishes to get out of it. EXAMPLE: Program EXEMPLO_DE_REPEAT_2; (
averaging two numbers given repeatedly) Uses CRT; Var N1, N2, MEDIA: real; RESP:
char; Begin clrScr; repeat write ('Enter two numbers:'); ReadLn (N1 , N2); MEDI
A: = (N1 + N2) / 2; writeln (MEDIA), write ('Do you want to repeat the program (
y / n)? "); RESP: = ReadKey; until (RESP =' N ') or (RESP = 'n') End
Programming Languages and Techniques I
25
4.5.3. AUTO REPEAT (FOR) FOR A control structure allows a simple command or comp
osite is repeated a specific number of times. Its general form is: FOR <var>: =
<vi> TO THE <vf> <command> <var> Where is a control variable of type integer, wh
ich will initially <vi> and the initial value will be increased from a value aft
er each iteration of the loop. The replay will be finalized when the content exc
eeds the value <var> <vf> end. The <command> also can be simple or compound. Ano
ther form of the structure is as follows: FOR <var>: = <vi> downto <vf> OF <comm
and> this case, the control variable is decremented <var> value of 1 after each
iteration of the loop and will repeat terminated when the content is below the v
alue <var> <vf> end. EXAMPLE: Program EXEMPLO_DE_FOR; writes the integers (100-1
00) var N: integer;€Begin for N: = 1 to 100 of writeln (N) End Note, the above e
xample, it was not necessary to use a command to assign an initial value of the
variable N or also another command to increase it with the value 1 . This is don
e automatically by the FOR structure. The FOR repetition structure is especially
suitable for when the number of repetitions is known in advance. Otherwise, we
use the WHILE or REPEAT, depending on the case.
EXERCISES RESOLVED
R4.01. Write a program that reads a set 100 integers and display the average val
ue of them. R4_01 Program; Var N, sum, count: integer;
Begin SUM: = 0; for CONT = 1 to 100 do begin ReadLn (N) SUM = SUM + N end; write
ln (SOMA) End
Programming Languages and Techniques I
26
R4.02. Write a program that reads a set of integers and display the average valu
e of them. Note: The exit condition of the bond will be reading the value 0 (fla
g). Program MEDIA_NUMEROS; Var N, CONT, SOMA, MEDIA: integer;
Begin SUM: = 0; CONT = 0; ReadLn (N), while N <> 0 do begin SUM = SUM + N; CONT
= CONT + 1; ReadLn (N) end; MEDIA: = SUM div CONT; writeln (MEDIA); End
SUGGESTED EXERCISES
P4.32. What are the existing structures of repetition in Pascal? P4.33. What is
the main difference between the WHILE-DO and REPEAT-UNTIL? P4.34. In what situat
ions is more appropriate to use the FOR structure? P4.35. In what situations we
can not use the FOR structure? P4.36. Write a Pascal program that reads a set of
100 positive integers, and determine the amount of even numbers and odd numbers
contained therein. P4.37. Given the following program snippet: ReadLn (N) A: =
1; I: = 2; while I <= N-1 do begin R: = R * 2, I: = I + 1 end; write (R) , rewri
te it using: a) the FOR command b) the command REPEAT
Programming Languages and Techniques I
27
P4.59. Write a Pascal program that displays the options menu below:
OPTIONS: 1 - SALUTE 2 - Bronco 3 - congratulations 0 - END The program should re
ad the user's choice and display for each option, its message: 1 - Hi, How are y
ou? 2 - Let's study more. 3 - My Congratulations! 0 - End of service. While the
option is other than 0 (zero) is due to continue presenting the options. Note: U
se structure as repeating the command REPEAT and how the command structure condi
tional CASE. P4.60. Make a program that reads three integer values (N, X, Y) and
show all numbers multiples of N between X and Y. P4.61. A number is, by definit
ion, a cousin if he has no divisors except 1 and itself. Write a program that re
ads a number and determine whether or not it is prime. P4.62. Make a program tha
t reads two integer values (X and Y) and show all the primes between X and Y.
Programming Languages and Techniques I
28
Chapter 5
ARRAYS
Homogeneous composite variables, which are known as arrays, represent sets of el
ements of the same type, represented by a single name. The arrays may vary in th
eir size, ie the amount of rates required for the individualization of each set.
The one-dimensional array is also known as vector, while the two-dimensional ar
ray is called a matrix. EXAMPLES: Vector V = 4 7 2 5 3 M = Matrix 3 0 2 8 2 5 1
4 9 5 7 3 T = 3 0 2 8 2 5 7 1 4 9 3 5 7 3 dimensional Array 6 0 9 1 3 2 4 5 8 5
0 1 2 3
Each element of the arrays can be referenced through indexes. Examples: V [1] =
4 V [2] = 7 V [5] = 3 M [1,1] = 3 M [2,3] = 4 M [3.1] T = 2 [1.1, 1] T = 3 [2,3,
2] T = 9 [1,2,3] = 3
5.1. VECTORS
Vectors are arrays that require only an index to distinguish one element of the
set. Statement: To define a variable of type vector, use the following syntax: l
ist-of-identifier: ARRAY [index index-initial-final ..] OF type where: list-of-c
ontent-identifiers initial content-type are the final names of variables to be d
eclared, it is the lower limit of the range of content, it is the upper limit of
the range of the index, is the type of components of variable
The rate-initial-final and the index must be the same scalar type (integer, char
acter or boolean).
EXAMPLE: To declare a variable composed of eight elements numeric name NOTE. var
NOTE: array [1 .. 8] of real;
will cause to come into being a set of eight elements of type real, individualiz
ed by the indices 1, 2, 3, ..., 8. note [1] note [2] note [3] note [4] note [5]
footnote [6] note [7] note [8]
Other examples of statements of vectors:
Programming Languages and Techniques I
29
var
AGE: array [1 .. 20] of integer; NAME: array [1 .. 30] of string; QUANT: array [
'A' .. 'Z'] of integer; REVENUE, EXPENDITURE: array [90 .. 96 ] of real; VECTOR:
array [-5 .. 5] of char;
To process every individual components of a vector, it is advisable to use the F
OR structure, so we can vary the index of vector.
EXERCISES RESOLVED
R5.01. Given a vector A defined as A: array [1 .. 100] of integer;
a) fill it with the value 30;
for I: = 1 to 100 of A [I]: = 30;
b) fill it with the integers 1,2,3 ,..., 100.
for I: = 1 to 100 of A [I]: = I; R5.02. Making a program that reads a vector A c
ontaining 30 integers, calculate and display: a) the greatest element b) the pos
ition (index) of the largest element.
Program R5_02, const N = 30; (number of elements of the vector) var A: array [1
.. N] of integer; I, POS, MAJOR: integer; begin (read) for the vector I: = 1 to
N ReadLn (A [I]);) (initialization of variables LARGEST: = A [1]; POS: = 1; (com
parison of elements with variable GREATER) for I: = 2 to N do if A [I]> MORE GRE
ATER then begin: = A [I]; POS: = I end;) (view of the results writeln (LARGEST,
POS); end.
Programming Languages and Techniques I
30
R5.03. Making a program to view 20 numbers, average them and display the numbers
that are above average. Program R5_03, const N = 20, (number of elements of the
vector) var NUM: array [1 .. N] of real; I, SUM: integer; MEDIA: real; begin (i
nitialization) variable SUM SUM: = 0; (read) and the sum of the numbers for I: =
1 to N do begin ReadLn (NUM [I]), SUM: = SUM + NUM [I] end;) (averaging MEDIA:
= SUM / N; (display numbers larger than average) for I: = 1 to N do if NUM [I]>
MEDIA then writeln (NUM [I]); end.
R5.04. Making a program that: a) read an array of 100 integers VET b) read an in
teger NUM, c) determines and displays the position of NUM within VET. If NUM is
not found within VET, display the value 0 (zero). Program R5_04, N = const 100:
(number of elements of the vector) var VET: array [1 .. N] of integer; NUM, I, P
OS: integer; begin (Reading data) for I: = 1 to N ReadLn (VET [I]); ReadLn (NUM)
;) (positioning POS: = 0; for I: = 1 to N do if VET [I] = POS then NUM: = I;) (w
riteln result display (POS); end.
Programming Languages and Techniques I
31
SUGGESTED EXERCISES
P5.01. Define and exemplify his words: a) Array b) Vector c) Mother d) and index
) Element or Component P5.02. Give the number of elements in each of the vectors
given below: a) VET: array [-5 .. 5] of integer; b) NAME: array [0 .. 20] of st
ring; c) CONT: array ['A '..' Z '] of integer; d) NOTE: array [1 .. 50] of real;
P5.03. Given the following vector:
1 2 3 4 5 6 7 8
VET =
7
4
1
5
8
2
3
6
what its contents after running the following commands: for I: = 8 downto 5 do b
egin AUX: = VET [I]; VET [I]: = VET [8-i +1]; VET [8-I + 1]: = AUX end; P5.04. G
iven a vector A containing 100 elements integers, generate and display a vector
B whose elements are in reverse order of A. Example:
February 1, 1999 100
A = B =
23 26
37 20
... ...
20 37
26 23
P5.05. Given two vectors A and B containing 20 elements each integers, generate
and display a vector C of the same size whose elements are the sum of its parts
A and B. Example:
January 2 March 19 20
A = B = C =
23 30 53
37 32 69
30 46 76
... ... ...
45 33 88
35 42 77
P5.06. Given two vectors A and B containing 25 elements each integers, generate
and display an array of 50 elements C, whose elements are the merge of the eleme
nts of A and B. Example:
January 2 March 24 25
A = B =
1
23 30
2
37 32
April 3
30 46
May 6
... ... 30 46 ...
38 43
47
55 49
48 49 50
C =
23
30
37
32
38
43
55
49
Programming Languages and Techniques I
32
P5.07. A basketball team has 12 players. Want to be a program that, given the na
me and height of the players, determine: a) the name and height of the tallest p
layer, b) the average height of the team, c) the amount of players taller than a
verage, listing the name and height of each. P5.08. Making a program in Pascal t
o correct multiple-choice tests. Each test has 10 questions and each question is
worth 1 point. The first set of data to be read will be the template for the co
rrection of proof. Other data are the numbers of students and their responses, a
nd the last number of fictitious student, will be 0 (zero). The program should c
alculate and print: a) for each student, their number and note b) the percentage
of approval, knowing that the pass mark is 6. c) a note that had the highest ab
solute frequency, ie the note that appeared as many times (assuming the absence
of ties). The data structure for this program to be:
NOTE NUMBER FEEDBACK
REPLIES
APPROVED
TOTAL
FREQUENCY
MORE
Percent
5.2. MATRICES
Arrays are arrays that need two indices to distinguish one element of the set. T
he first index represents the rows and second columns. Statement: To define a va
riable of type array, use the following syntax: list-of-identifier: ARRAY [.. ín
dice1 índice1-initial-final índice2-initial-final índice2 ..] OF type
where: list-of-identifiers índice1-initial-final índice1 índice2 índice2-initial
-final type are the names of variables to be declared, it is the lower limit of
the range of first index, it is the upper limit of the range the first index, it
is the lower limit of the range of second index, is the upper limit of the rang
e of second index, is the type of components of variable
índice1 the initial-and final-índice1 must be the same scalar type (integer, cha
racter or boolean). The índice2-starter must also be the same type of scale índi
ce2-final. EXAMPLE: Declare an array M of 4 rows by 3 columns, consisting of ele
ments numeric integers.
Programming Languages and Techniques I
33
var M: array [1 .. 4.1 .. 3] of integer; will exist to pass a data structure cal
led M grouped with 4x3 = 12 integer elements, addressable by a pair of indices,
with the first indicating line and the other column. m11 m21 m12 m22 m32 M31 M41
M42 M13 M43 m23 m33
M =
Other examples of array declarations: var M1: array [1 .. 4.80 .. 90] of real; M
2: array ['A' .. 'AND', 0 .. 10] of string; M3: array [ -3 .. 3.1 .. 3] of char;
EXERCISES RESOLVED
R5.05. Making a program to read a 3 x 5 array of integers and write it after hav
ing multiplied each element by 2. R5_05 Program; const NL = 3;) (number of rows
NC = 5;) (number of columns K = 2;) (var multiplication factor for M: array [1 .
. NL, NC 1 ..] of integer; I , J: integer; reading begin (array) for I: = 1 to N
L for the J: = 1 to CN begin write ('element of the line,' I, 'column' J ':'); R
eadLn (M [I, J]) end, () is calculated by multiplying I: = 1 to NL for the J: =
1 to CN M [I, J]: = M [I, J] * K; ( view of the resulting array) writeln ('Resul
t'); for I: = 1 to NL do begin for J: = 1 TO NC write (M [I, J], ''); writeln en
d;
Programming Languages and Techniques I
34
end.
Programming Languages and Techniques I
35
R5.06. Given an array of 4 x 5 elements integers, calculate the sum of every row
, every column and all its elements. Note: Use an array to store the result of t
he sum of each row and one for the sum of each column. R5_06 Program; const NL =
4;) (number of rows NC = 5;) (number of columns var M: array [1 .. NL, NC 1 ..]
of integer; L: array [1 .. NL] of integer, C: array [1 .. CN] of integer; I, J,
SUM: integer; reading begin (array) for I: = 1 to NL for the J: = 1 to CN begin
write ('element of line, 'I,' column 'J': '); ReadLn (M [I, J]) end; (calculati
ng the sum of each row) for I: = 1 to NL do begin L [I ]: = 0; for J: = 1 to CN
L [I]: = L [I] + M [I, J] end; (calculating the sum of values in each column) fo
r J: = 1 TO NC do begin C [J]: = 0; for I: = 1 to NL C [J]: = C [J] + M [I, J] e
nd; (calculating the sum of all elements of the array SUM) : = 0; for I: = 1 to
NL for the J: = 1 to CN SUM: = SUM + M [I, J];) (view the results for I: = 1 to
NL's writeln ('Sum of line, 'I,': ', L [I]) for J: = 1 TO NC writeln (' Sum of C
olumn 'J': 'C [J]), writeln (' Sum of Matrix: ', SUM); end.
5.3. Multidimensional arrays
Pascal allows the creation of multidimensional arrays, which require multiple in
dexes to be handled. The way of using this type of array follows the same logic
matrices, differing only in the number of indices.
Programming Languages and Techniques I
36
SUGGESTED EXERCISES
P5.09. Give the number of elements in each of the following matrices given below
: a) MAT: array [1 .. 3.1 .. 4] of integer; b) CC: array [0 .. 2.1 .. 3] of stri
ng c) BAD: array ['A' .. 'E', -1 .. 1] of integer; d) NOTE: array [90 .. 98.0 ..
1] of real; P5.10. Since the matrices M and R below: M = OERAQ * E * I * ISTSR
=
what is the content of R after running the commands: for I: = 1 to 4 for J: = 1
to 4 R [J, I]: = M [I, J]; AUX: = R [1, 1] R [1,1]: = R [4.4], R [4.4]: = AUX, A
UX: = R [2,2], R [2,2]: = R [3, 3] R [3,3]: = AUX; P5.11. Given two matrices A a
nd B, with 2 x 3 integer elements each, generate and display a matrix C of the s
ame size as result of the sum of the matrix A to matrix B. P5.12. Make a program
that reads a matrix of order 3 x 5 elements of integers, calculate and display:
a) the largest matrix element, b) the sum of the matrix elements, c) the averag
e of the matrix elements; P5.13. Given a square matrix of order N, of elements i
ntact, displaying the main diagonal elements, ie elements where i = j. Note: N i
s read (N ≤ 10). P5.14. Given a matrix A with 3 x 4 integer elements, generate a
nd display a matrix B which is the transposed matrix of A. P5.15. Make a program
that reads the name and the three grades of 50 students in a class and: a) calc
ulate: the arithmetic average of each student, the situation of each student, (i
f approved average greater than or equal to 7.0) the number of students approved
, the overall average class, the name and situation of each student;€the number
of students passed, the overall average class, the name and average students wit
h average or above average general class.
b) display:
⇒ Use arrays to store name, and middle position, and an array to store the notes
.
Programming Languages and Techniques I
37
P5.16. The table below shows the amount of sales by manufacturers of vehicles du
ring the period 1993-1998 in thousand units. Manufacturer / Year Fiat Ford GM Wo
lkswagen Make a program that: a) read the table data, b) determine and display t
he manufacturer that sold more in 1996, c) determines and displays the year of h
ighest overall volume of sales. d) determines and displays the average annual sa
les for each manufacturer during the period. 1993 204 195 220 254 1994 223 192 2
22 262 1995 230 198 217 270 1996 1997 257 203 231 284 290 208 245 296 322 228 28
0 330 1998
P5.17. Make a program that assembles a three-dimensional array 5 x 7 x 3, where
the contents of each element equals the sum of its contents. P5.18. Make a progr
am that reads and store in a three-dimensional array containing the values of th
e annual turnover of a company specified month to month and also by the subsidia
ry. See the structure below the array:
YEAR 1997 YEAR 1996 YEAR 1995 YEAR 1994 MONTH January February March April May J
une July August September October November December 1 TOTAL BRANCH BRANCH BRANCH
2 3 TOTAL TOTAL TOTAL TOTAL
After reading the data do the following: a) calculate the totals of the rows and
columns in each year, b) create a new page containing the consolidation of data
, ie the sum of each year (month by month and by subsidiary), c) displays all th
e read data and calculated.

S-ar putea să vă placă și