a practical introduction to pascal programming languagegiara.unavarra.es/pdfs/apitppl.pdf · a...

91

Upload: lequynh

Post on 03-Sep-2018

291 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince
Page 2: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A practical introduction toPascal programming language

Carlos Lopez-Molina

Humberto Bustince

Javier Fernandez

Dpto. Automatica y Computacion

Universidad Publica de Navarra

Pamplona, March 2013

Page 3: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince
Page 4: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming LanguageC. Lopez-Molina, H. Bustince, J. Fernandez

CC© The authors

ISBN-10: 84-695-7278-4

ISBN-13: 978-84-695-7278-8

Front illustration: Manche Menschen andern sich nieCC© C. Lopez-Molina

Pamplona, March 2013

Page 5: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince
Page 6: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

This book is distributed under the license

Creative Commonts Attribution-NonCommercial-ShareAlike 3.0 Unported

(CC BY-NC-SA 3.0)

You are free:

• To share: to copy, distribute and transmit the work, and

• To remix: to adapt the work.

Under the following conditions:

Attribution- You must attribute the work in the manner specified by theauthor or licensor (but not in any way that suggests that they endorseyou or your use of the work).

Noncommercial- You may not use this work for commercial purposes.

Share Alike- If you alter, transform, or build upon this work, you maydistribute the resulting work only under the same or similar license tothis one.

With the understanding that:

• Waiver- Any of the above conditions can be waived if you get permission from the copy-right holder.

• Public Domain- Where the work or any of its elements is in the public domain underapplicable law, that status is in no way affected by the license.

• Other Rights- In no way are any of the following rights affected by the license:

– Your fair dealing or fair use rights, or other applicable copyright exceptions andlimitations;

– The author’s moral rights;– Rights other persons may have either in the work itself or in how the work is used,

such as publicity or privacy rights.

• Notice- For any reuse or distribution, you must make clear to others the license terms ofthis work. The best way to do this is with the link below.

For more information, visit: http://creativecommons.org/licenses/by-nc-sa/3.0/

Page 7: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince
Page 8: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Contents

Introduction to this book 9Aims and scopes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Guidelines and structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

1 Basic read/write operations 111.1 Contents of this chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111.2 Brief review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

1.3.1 Basic input and output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121.3.2 Using functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

2 Alternative constructions 192.1 Contents of this chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192.2 Brief review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

3 Iterative constructions 353.1 Contents of this chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353.2 Brief review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353.3 On the selection of an iterative structure . . . . . . . . . . . . . . . . . . . . . . . . 373.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

3.4.1 Iterative processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383.4.2 Computing with sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . 453.4.3 On-screen matrix displaying . . . . . . . . . . . . . . . . . . . . . . . . . . 61

4 Data structures 654.1 Contents of this chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 654.2 Brief review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 654.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

4.3.1 Working with arrays and matrices . . . . . . . . . . . . . . . . . . . . . . . 674.3.2 Working with strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 824.3.3 On-screen matrix displaying . . . . . . . . . . . . . . . . . . . . . . . . . . 86

7

Page 9: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince
Page 10: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Introduction to this book

The first contacts with programming languages are never easy, specially for first-year students,which haven’t developed structured mathematical routines. Hence, they have frequent troublesto understand what is going on in a program and why do things happen. Although the bestway of dealing with such symptoms is personal work, the instructors usually find themselvesproviding the students with a large number of solved examples than might enhance the com-prehension of the students. This task is tedious and time-consuming. Moreover, the instructorfrequently has problems to find exercises and examples which are rich and diverse enough toshed light on all the aspects of the programming language. As a consequence of all the previousinstructors devote, year after year, a large amount of time to prepare sets of solved exercises.Since this is our experience, we have decided to create a book which can be used to complementan introductory course to programming. That is, a book the students can use a support fortesting their knowledge, but also for getting more used to read and develope code.

For a long time, students in our University have used Pascal in basic programming courses.The reasons are diverse, but ground mostly on the fact that the language has tight grammarand also that higher-level aspects, such as memory management, are simplified. Althoughits applicability to professional environments is much lower than that of other programminglanguages, we believe that Pascal is very suitable for learning good programming practices.Indeed, from our experience we can state that acquiring the fundamentals on programminglanguages is much easier with Pascal than with any other language. Hence, we consider worthusing this language the first and second semester of their higher education, despite it is neverused again in subsequent years.

Aims and scopes

This book aims at providing both the instructor and the studentsg a large collection of exercisesto fulfill the following goals:

• Alleviating the workload of the instructor by proving him with a large set of exampleexercises.

• Allowing the student to become familiar with Pascal by accessing a large number ofprograms.

• Illustrating the student with a large number of examples of well-written code, in whichgood programming and coding practices are considered.

9

Page 11: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Guidelines and structure

This book is divided into four units, according to the structure we have followed in the pastacademic years. Each one covers a specific aspect of the programming language, so that thestudent acquires the knowledge in an incremental way. The four units the book is broken downinto are:

• Basic read/write operations;

• Alternative structures;

• Iterative structures;

• Advanced data structures.

Each of the units is subsequently divided into more specific goals, as explained at the be-ginning of each of the chapters. Note that this book is not intended to be used for theoreticalteaching, but to support the theoretical contents instead. Hence, despite a brief theoretical intro-duction is included at the beginning of each unit, our intention is to help the student refreshingthe knowledge rather than creating it.

Each of the chapters in this book is composed of a brief explanation of the contents of theunit, followed by a list of solved exercises illustrating such contents. We recommend to readthe whole book, since the list of exercises is intented to have some sense of linearity. Otherwise,students might get lost in references to previous exercises or explanations. At the end of thebook, the student is expected to understanding structured programs, as well as of implementingmost of the algorithms required for mid-level courses.

Page 12: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Chapter 1

Basic read/write operations

1.1 Contents of this chapter

This chapter covers the instructions used to gather data from the user, as well as displayinon-screen the information generated by a program. Its contents are:

1.a Writing in the command line.

1.b Reading from the keyboard.

1.c Basic assignment operations.

1.d Usage of simple functions provided by the programming framework.

1.2 Brief review

This section cover the most basic read/write operations. There are two operations we can use towrite text in the command line:

� write(t) - Writes the text t in the command line (more on the composition of t later).

� writeln(t) - Does the same as write(t), but jumps the line right after writing the text.That is, places the prompt at the beginning of the line following.

The composition of the text to be displayed by write/writeln can be performed in differentways. These are the options:

• Simple static text between simple quotations. Some examples are write(’hello’) orwriteln(’computer’).

• Concatenation of static texts. To do so, we only have to include as many pieces oftext as necessary, all of them separated by the comma symbol. Some examples arewrite(’hel’,’lo’) or writeln(’this ’,’is ’,’my computer’). Note that, for ex-ample, write(’hel’,’lo’) produces the same message on-screen than write(’hello’).

• Concatenation of static text and non-static values. In this case we can combine the fixedtext with contents derived from the contents of the variables. To concatenate fixed textwith non-fixed content, we also use the comma symbol. Some examples are write(’2

11

Page 13: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

Function Usage Input Output

Absolute value abs(x) Int Same as input

Squared value sqr(x) Int./Real Same as input

Squared root sqrt(x) Int./Real Same as input

Trigonometric Sine sin(x) Int./Real Real

Trigonometric Cosine cos(x) Int./Real Real

Natural logarithm ln(x) Int./Real Real

e-power exp(x) Int./Real Real

Truncated value trunc(x) Real Int.

Rounded value round(x) Real Int.

Fractionary part frac(x) Real Real

Real part int(x) Real Real

Table 1.1: Some of the most important functions in Pascal, together with the type of inputs theydemand and the outputs they produce.

multiplied by 2 is ’,2*2) or write(’The value of a is ’,a), where a can be anykind of variable. Note that, regardless of the type of variable, the program will automati-cally convert it to text for its display in the write/writeln operation.

Regarding the reading-from-keyboard operations, here are two functions we can make useof:

� read(a) - Waits for the user to input information on the command line and stores it in thevariable a.

� readln(a) - Waits for the user to input information and press enter on the command line.Then, it stores all the information the user typed in the variable a.

After the execution of any of such functions, the value of the variable put into parenthesis isthe one the user input. In case the contents input by the user cannot be appropriately convertedto the type of the variable, an error is raised, and the execution of the program is aborted.

Apart from the read/write operations, Pascal offers a wide variety of functions for easing thecomputations. A selection of such functions can be found in Table 1.1, where the name of eachfunction is listed together with the type of arguments it admits and the type of the information itproduces. Note that this functions could be combined in any possible way, exactly as the usualmathematical operators.

1.3 Exercises

1.3.1 Basic input and output

Exercise 1.1. Write a program that reads an integer from the keyboard and shows it to the user.

�For doing this exercise we only need to declare one variable, which is read and displayed

using two different operations. Note that, by using readln, we save into int all the digits typedby the user before an enter, not only the first one.

12

Page 14: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Basic read/write operations

Program 1: Exercise 1.1

program c01e01;var

int:integer;begin

write(’Please type an integer number and press enter: ’);readln(int);writeln(’The number you typed is: ’,int)

end

Exercise 1.2. Write a program that reads two chars from the keyboard and displays them on-screen.

�This program is very similar to the previous, except for the fact that we now need two

variables instead of one.

Program 2: Exercise 1.2

program c01e02;var

firstChar,secondChar:char;begin

write(’Please type a char number and press enter: ’);readln(firstChar);writeln(’Now please type the second char and press enter: ’);readln(secondChar);writeln(’The chars you typed are: ’,firstChar,’ and ’,secondChar,’.’)

end

Exercise 1.3. Write a program that reads a real and an integer from the keyboard and showsthem to the user using one single line of code.

�Now the only difference with respect to the previous is the number of variables we need and

their type.

Program 3: Exercise 1.3

program c01e03;var

int:integer;r:real;

beginwrite(’Please type an integer number and press enter: ’);readln(int);writeln(’Now please type an real one and press enter: ’);readln(r);writeln(’The numbers you typed are: ’,int,’ and ’,r,’.’)

end

13

Page 15: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

Exercise 1.4. Write a program that reads two reals from the keyboard and shows their product.The program must display only 4 digits in the non-integer part.

The exercise consists of reading the names and displaying the product. Observe that there isno need to create a new variable to store the result, since we can perform the mathematical op-eration (product) inside the writeln operation. As a general rule, extra (unnecessary) variablesshould only be used when that increases significantly the readability of the program. Finally, inorder to adjust how the result is displayed, we force the program to display at most 5 digits onthe integer part and 4 in the non-integer one.

Program 4: Exercise 1.4

program c01e04;var

firstReal,secondReal:real;begin

write(’Please type the first real and press enter: ’);readln(firstReal);write(’Now type the second real and press enter: ’);readln(secondReal);writeln(’The product of both numbers is: ’,(firstReal*secondReal):5:4)

end

Exercise 1.5. Write a program that reads two integers in two variables. Then, after displayingthem on-screen, it swaps their values and displays them again.

Swapping the value of two variables is a frequent operation in real programs. It alwaysdemands the use of a third (auxiliar) variable to temporarily store the value of one of thevariables. Notice how the variable aux must be used at the beginning of the swapping operationto store the value of one of the integers (firstInt), then at the end to restore such value to theother one (secondInt).

Program 5: Exercise 1.5

program c01e05;var

firstInt,secondInt,aux:integer;begin

write(’Please input the first integer :’);readln(firstInt);write(’Now please input the second one :’);readln(firstInt);writeln(’The values are ’,firstInt,’ and ’,secondInt,’.’);aux:=firstInt;firstInt:=secondInt;secondInt:=aux;writeln(’The values are now ’,firstInt,’ and ’,secondInt,’.’)

end.

14

Page 16: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Basic read/write operations

1.3.2 Using functions

Exercise 1.6. Write a program that reads an integer from the keyboard and displays its absolutevalue.

�The easiest option to complete this exercise is using the abs function, that takes as single

argument a number (either integer or real) and returns its absolute value. As happened with theproduct in Exercise 1.5, the function can be used within writeln.

Program 6: Exercise 1.6 (Version A)

program c01e06;var

i:integer;begin

write(’Please type an integer number and press enter: ’);readln(i);writeln(’Its absolute value is: ’,abs(i),’.’)

end

In case we do not want to use such function, alternative options include the use of squareroots. In the following program we employ sqrt(x*x), which is equivalent to sqrt(sqr(x)).Note that the sole reason why this works is that the function sqrt(x) only returns the positiveroot of a real number.

Program 7: Exercise 1.6 (Version B)

program c01e06;var

r:integer;begin

write(’Please type the real number and press enter: ’);readln(r);writeln(’The absolute value of their product is: ’,sqrt(r*r),’.’)

end

Exercise 1.7. Write a program that reads an angle in randians (as a real) and displays its sineand cosine.

�The best way to obtain that information is using the functions provided by Pascal: sin(x)

and cos(x).

Program 8: Exercise 1.7

program c01e07;var

r:real;begin

write(’Please type the angle and press enter: ’);readln(r);writeln(’The sine and cosine of the angle are: ’,sin(r),’ and ’,cosine(r),’.’)

end

15

Page 17: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

Exercise 1.8. Write a program that reads a real and displays separately its integer and real parts.

�There are different ways to do so. The simplest one is employing the functions int(x) and

frac(x), where x is a real number.

Program 9: Exercise 1.8 (Version A)

program c01e08;var

r:real;begin

write(’Please type a real number and press enter: ’);readln(r);writeln(’The integer part of the number is: ’,int(r),’,’);writeln(’ while the fractionary one is ’,frac(r),’.’)

end

If we could not use such functions, there is always the possibility of using the functionstrunc(x), although this code will also work correctly when the real number input by the useris positive.

Program 10: Exercise 1.8 (Version B)

program c01e08;var

r:real;begin

write(’Please type a real number and press enter: ’);readln(r);writeln(’The integer part of the number is: ’,trunc(r),’,’);writeln(’ while the fractionary one is ’,r-trunc(r),’.’)

end

Exercise 1.9. Write a program that reads two real numbers and calculates their rounded sumand product.

�Rounding is a common operation that can be performed using round(x), which is a function

that takes as argument a real and produces an integer number.

Program 11: Exercise 1.9

program c01e09;var

firstReal,secondReal:real;begin

write(’Please type the first real number and press enter: ’);readln(firstReal);write(’Now type the second one and press enter: ’);readln(secondReal);writeln(’The rounded sum is: ’,round(firstReal+secondReal),’,’);writeln(’ while the rounded product is is ’,round(firstReal*secondReal),’.’)

end

16

Page 18: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Basic read/write operations

Exercise 1.10. Write a program that reads a char and displays its upper case version.

�For converting any character to upper case, we can use the function upcase(x), where x

must be a char. In case the char has no specific upper case version (e.g., it is a punctuation mark),the function returns the same char.

Program 12: Exercise 1.10

program c01e10;var

c:real;begin

write(’Please type a char and press enter: ’);readln(c);writeln(’The char is: ’,c,’, and its upper case version: ’,upcase(c),’.’)

end

17

Page 19: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

18

Page 20: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Chapter 2

Alternative constructions

2.1 Contents of this chapter

This chapter covers the following contents:

2.a Alternative structures based on if-then and if-then-else clauses.

2.b Alternative structures based on case-of clauses.

2.2 Brief review

Sequential programs are too simple to solve most of the problems in real world computing. Veryoften, we need a program to act in different ways depending upon the values it is working with.Since this book is addressed to beginners, we assume the only possible variation in a programcomes from a user inputting different data. Consequently, we focus this section on designingprograms that execute different sequences of instructions depending upon the values input bythe user. The structures that allow us to specify this kind of decisions are the alternative controlstructures.

An alternative control structures allows a program for modifying its behaviour dependingupon different conditions, which are checked in execution time. That is, before executing thereis no decision made on which is the sequence of instructions to be used. Hence, in some sense,they allow dynamic selection of the instructions to be performed during in the execution of theprogram.

There are two basic alternative structures considered in this chapter: if-then-else andcase-of structures. The former is the most commonly used, but the latter is of great help tosolve in an elegant way scenarios in which a large number of options are available.

The if-then-else structures enables the program to take a boolean decision on the executionof some instructions. That is, they capacitate the program to decide whether some code has tobe executed or not. In order to do so, the programmer must state some condition the programcan evaluate (as true or false) in execution time. Optionally, the programmer can introduce analternative block of code to be executed in case the program determined that the first block ofcode was not to be executed.

The semantics of the structure, together with the schematic representations are includedin Fig. 2.1. In. Fig. 2.1(a) we have the basic if-then, while in Fig. 2.1(b) we include theif-then-else. The if-then structure only capacitates the program to execute (or not) the

19

Page 21: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

...

[Precedent code]

if (Boolean condition) then

Instruction Block

[Following code]

...

[Precedent code]

?

Boolean condition

?

�Instruction block

?[Following code]

true false

(a) If-then clause...

[Precedent code]

if (Boolean condition) then

Instruction Block A

else

Instruction Block B

[Following code]

...

[Precedent code]

?

Boolean condition

? ?

Instruction block A Instruction block B

?[Following code]

true false

(b) If-then-else clause

Figure 2.1: Schematic representation of the if-then-else constructions.

Instruction Block, which can contain one single instruction or more than one instructions enclosedby begin-end clauses. This decision is taken based on the evaluation of some boolean expression(e.g. the comparison of two numbers), which must be included between the if and then

clauses. The if-then-else works exactly as the if-then one, exception made that it demandsan alternative instruction block to be executed in case the boolean condition was evaluated asfalse.

Eventually, a program has more than 2 alternatives to decide what code it must execute.The case-of structure is a commodity designed to simplify such situations. In order to do so,it evaluates a an expression than must produce an integer or char result. Then, this result iscontrasted against a set of values, each of them associated with an instruction block. The codeexecuted is the one associated with the value generated in the evaluation of the expression.

The semantics of the structure, together with the schematic representations are included inFig. 2.2. The difference between the case-of and case-of-else structures is that the latterhas the option to include certain instructions to be executed in case the value generated by theexpression does not match any of the listed values. Note that the case-of and case-of-elsestructures have the following components:

• Expression- Any expression producing an integer or a char.

• Values- Each of the values can be expressed as individual values (e.g. 5 or ’a’), a list ofvalues (e.g. 5,6,7 or ’a’,’b’,’v’) or a range of values (e.g. 5..10 or ’a’..’f’).

20

Page 22: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Alternative constructions

...

[Precedent code]

case ( int or char expression ) of

value1 :

Instruction Block 1

value2 :

Instruction Block 2...

valueN :

Instruction Block N

end

[Following code]

...

[Precedent code]

?

Computing expression

?

=value1

=value2

=valueN

-

-

-

Instruction Block 1

Instruction Block 2

Instruction Block N

q q q q q q�

[Following code]

(a) Case-of clause...

[Precedent code]

case ( int or char expression ) of

value1 :

Instruction Block 1

value2 :

Instruction Block 2...

valueN :

Instruction Block N

else

Instruction Block X

end

[Following code]

...

[Precedent code]

?

Computing expression

-

=value1

=value2

=valueN

-

-

-

Instruction Block 1

Instruction Block 2

Instruction Block N

Instruction Block X

q q q q q q

?

[Following code]

(b) Case-of clause with else statement

Figure 2.2: Schematic representation of the case-of-else constructions.

21

Page 23: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

• Instruction Block- Instruction or list of instructions to be executed in case the result generatedby the expression matches the values expressed in the corresponding value.

Note that, the execution of the instruction block associated with the else clause does notrequire any value to be matched. As happened with the else clause in the if-then, thisalternative is taken if the previous one (or ones) is (are) discarded.

2.3 Exercises

Exercise 2.1. Write a program that reads two integers from the keyboard. Then, if they are bothpositive or negative, it displays their product. Otherwise, it displays the difference between thepositive one and the negative one.

�The first option consists of manually checking whether both numbers are either positive or

negative (note that the 0 is considered as positive). In case one number is at each side of the 0,the program finds out which one is the positive and calculates the difference.

Program 13: Exercise 2.1 (Version A)

program c02e01;var

a,b:real;begin

write(’Input the first number: ’);readln(a);write(’Input the second number: ’);readln(b);(* Testing whether both numbers have the same sign*)if ( (a>=0) and (b>=0) ) or ( (a<0) and (b<0) ) thenwriteln(’The expected result is: ’,a*b:4:2)

elseif (a>b) then

writeln(’The expected result is: ’,a-b:4:2)else

writeln(’The expected result is: ’,b-a:4:2)end.

We can optimize the program by making use of two facts. The first one is that 2 numbers areboth positives or both negatives if and only if their product is positive. The second is that thedifference between the greatest and the smallest of two values is exactly the same as the absolutevalue of their difference, regardless of the order in which the subtraction is carried out. Hence,the program can be rewritten as:

Program 14: Exercise 2.1 (Version B)

program c02e01;var

a,b:real;begin

write(’Input the first number: ’);readln(a);write(’Input the second number: ’);readln(b);(* Testing whether both numbers have the same sign*)if (a*b)>0 thenwriteln(’The expected result is: ’,a*b:4:2)

22

Page 24: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Alternative constructions

elsewriteln(’The expected result is: ’,abs(a-b):4:2)

end.

However, the previous code has some failing situations: those in which one value is 0 (whichwe consider positive). In such situations, we cannot distinguish whether both numbers arepositive or not using the multiplication, since the product of 0 with any other number willcollapse to 0. Hence, we must change the comparison operator ≥ by > and add a clause to thefirst if.

Program 15: Exercise 2.1 (Version C)

program c02e01;var

a,b:real;begin

write(’Input the first number: ’);readln(a);write(’Input the second number: ’);readln(b);(* Testing whether both numbers have the same sign*)if ((a*b)>0) or ((a>=0) and (b>=0)) then

writeln(’The expected result is: ’,a*b:4:2)else

writeln(’The expected result is: ’,abs(a-b):4:2)end.

Exercise 2.2. Write a program that reads three integers from the keyboard. Then, it displays theone whose value is in the middle of the other two (i.e. the second greatest value).

�Our first strategy consists of first discarding one of the values by checking if it is smaller than

the other two. Then, we select the smallest of the remaining two variables.

Program 16: Exercise 2.2 (Version A)

program c02e02;var

a,b,c:integer;begin

write(’Input the first number: ’);readln(a);write(’Input the second number: ’);readln(b);write(’Input the third number: ’);readln(c);(* Now we compare the values one-by-one*)if (a<=b) and (a<=c) then

if (b<=c) thenwriteln(’The value is ’,b)

elsewriteln(’The value is ’,c)

elseif (b<=a) and (b<=c) then

if (a<=c) thenwriteln(’The value is ’,a)

elsewriteln(’The value is ’,c)

23

Page 25: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

elseif (b<=c) thenwriteln(’The value is ’,b)

elsewriteln(’The value is ’,c)

end.

The second alternative consists of sorting the three variables so that a ≤ b ≤ c. In suchcase, the value is always in the variable b. Note that the strategy for swapping the value of twovariables is as in Exercise 1.5.

Program 17: Exercise 2.2 (Version B)

program c02e02;var

a,b,c,aux:integer;begin

write(’Input the first number: ’);readln(a);write(’Input the second number: ’);readln(b);write(’Input the third number: ’);readln(c);if a<b then

beginaux:=a;a:=b;b:=aux

end;if b<c then

beginaux:=b;b:=c;c:=aux;

end;if a<b then

beginaux:=a;a:=b;b:=aux

end;writeln(’The value in the middle is : ’,b)

end.

Finally, by using the functions min and max, we can make the program look simpler andshorter. Note that we need to include the statement uses math; to be able to use such functions.

Program 18: Exercise 2.2 (Version C)

program c02e02;uses math;var

a,b,c,aux:integer;begin

write(’Input the first number: ’);readln(a);write(’Input the second number: ’);readln(b);write(’Input the third number: ’);readln(c);if (min(a,c)<=b) and (b<=max(a,c)) then

24

Page 26: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Alternative constructions

writeln(’The value in the middle is: ’,b)else if (min(b,c)<=a) and (a<=max(b,c)) thenwriteln(’The value in the middle is: ’,a)

elsewriteln(’The value in the middle is: ’,c)

end.

Exercise 2.3. Write a program that displays the absolute value of a real number not using theabs function.

�In this case we need to give a different treatment to the value depending on the fact that it is

negative or positive.

Program 19: Exercise 2.3

program c02e03;var

n:integer;begin

writeln(’Please type an integer: ’);readln(n);if (n<0) then

writeln(’The absolute value is ’,-n)else

writeln(’The absolute value is ’,n)end.

Exercise 2.4. Write a program that reads a char from the keyboard. In case it is upper case, theprogram displays its lower case version (and the other way round). If the character is not a letter,a warning message must be displayed.

�The difficulty in this exercise consists of knowing how to discriminate upper (or lower) case

letters from the other characters. In order to do that, we make use of comparison of chars,knowing that the alphabetical order is preserved. Considering that, any value greater than ’a’

and smaller than ’z’ must be a lower case letter. The comparison for upper case is identical.

Program 20: Exercise 2.4

program c02e04;var

c:char;begin

writeln(’Please type a char: ’);readln(c);if ((’a’<c) and (c<’z’)) thenwriteln(’The modified char is: ’,upcase(c))

else if ((’A’<c) and (c<’Z’)) thenwriteln(’The modified char is: ’,lowercase(c))

elsewriteln(’Warning: the char is not a letter.’)

end.

25

Page 27: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

Exercise 2.5. Write a program that reads two chars from the keyboard. Then, the program mustdisplay which one is the precedent in alphabetic order (regardless of the case). In case any ofthe char is not a letter, a warning message must be displayed.

�In this case we have to proceed in two consecutive steps: (1) checking the validity of the

values input by the user and (2) deciding which is the precedent in alphabetical order. In orderto do the first, we check that the upper and lower version of the variables are not the same. Thisproperty is only satisfied by the letters, since the remaining characters don’t have upper andlower version. Then, in order to compare the letters regardless of their case, we turn both toupper case and compare.

Program 21: Exercise 2.5

program c02e05;var

c1,c2:char;begin

(* Reading the data*)write(’Please type the first char: ’);readln(c1);write(’Please type the second one: ’);readln(c2);(* Comparing the chars*)if (upcase(c1)=lowercase(c1)) thenwriteln(’The first char is not a letter’)

else if (upcase(c2)=lowercase(c2)) thenwriteln(’The second char is not a letter’)

else if (upcase(c1)>upcase(c2)) thenwriteln(’The first letter is [’,c2,’] while the second is [’,c1,’].’)

elsewriteln(’The first letter is [’,c1,’] while the second is [’,c2,’].’)

end.

Exercise 2.6. Write a program that reads an integer from the keyboard and says whether it iseven or odd.

�This program is very simple once we understand that the modulus of a number in the division

by 2 is 0 if and only the number is even.

Program 22: Exercise 2.6

program c02e06;var

n:integer;begin

writeln(’Please type an integer: ’);readln(n);if (n mod 2 = 0) thenwriteln(’The number ’,n,’ is even’)

elsewriteln(’The number ’,n,’ is odd’)

end.

26

Page 28: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Alternative constructions

Exercise 2.7. Write a program that reads a real number from the keyboard. Then, if the numberis in the interval [−5, 5], it displays the message Within!. Otherwise, it displays the messageOutside.

�The first of the options consists of checking that the number is greater than −5 and smaller

than 5.

Program 23: Exercise 2.7 (Version A)

program c02e07;var

value:real;begin

write(’Input a number: ’);readln(value);(* Basic double comparison*)if (-5<=value) and (value<=5) thenwriteln(’Within.’)

elsewriteln(’Outside.’)

end.

We can also make the exercise a little simpler by realizing that the numbers in the giveninterval have an absolute value lower or equal to 5.

Program 24: Exercise 2.7 (Version B)

program c02e07;var

value:real;begin

write(’Input a number: ’);readln(value);if (abs(value)<=5) then

writeln(’Within.’)else

writeln(’Outside.’)end.

Exercise 2.8. Write a program that reads two intervals from the keyboard, and then display theinterval created from their intersection. Each of the intervals must be input as a pair increasingof real numbers in the same line (with a blank space in the middle). In case the intervals are notwell cast (i.e. the user does not input the numbers in increasing order), an error message mustbe displayed.

�In this exercise we first have to check that the intervals are well proposed, that is that the

upper bounds are actually greater (or equal) than the lower ones. Then, there are two possibilitiesto be handled: those with actual intersection and those in which the intervals are non-coincident.We first discard the second scenario, and then proceed to calculate the intersection.

In this case we first check whether n1 is the greatest value. If not, we take the greater of n2and n3 as the greatest value input by the user.

27

Page 29: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

Program 25: Exercise 2.8

program c02e08;uses math;var

aLow,bLow,aHigh,bHigh:integer;begin

(* Reading the values*)write(’Please type the first interval: ’);read(aLow);readln(aHigh);write(’Please type the second interval: ’);read(bLow);readln(bHigh);(* Checking them up*)if ((aLow>=aHigh)or(bLow>=bHigh)) thenwriteln(’The intervals are inconsistent.’)

else if ((bLow>aHigh) or (aLow>bHigh)) thenwriteln(’The intersection is null’)

elsewriteln(’The intersection is [’,max(aLow,bLow),’,’,min(aHigh,bHigh),’]’)

end.

Exercise 2.9. Write a program that reads 3 integers and displays the product of the greatest oneby the sum of the other two.

�In this program we first aim at sorting the values so that n1 ≥ n2 ≥ n2. In order to do so,

we sort the values 2-by-2, finally ensuring the order. Later on, we proceed for the mathematicaloperations on the data.

Program 26: Exercise 2.9

program c02e09;var

n1,n2,n3:integer;begin

(* Reading*)write(’Please type three integer splitted by spaces: ’);read(n1);read(n2);readln(n3);(* Comparing the values one-by-one*)if ((n1>=n2) and (n1>=n3)) then

writeln(’The result is ’,n1*(n2+n3),’.’)else if (n2>=n3) then

writeln(’The result is ’,n2*(n1+n3),’.’)else

writeln(’The result is ’,n3*(n1+n2),’.’)end.

Exercise 2.10. Write a program that reads 3 reals and displays them sorted in decreasing order.

�This exercise is very similar to the previous. Note how, after the first two if-then structures

we already know that the smallest value of the three is in n3.

28

Page 30: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Alternative constructions

Program 27: Exercise 2.10

program c02e09;var

n1,n2,n3,aux:real;begin

(* Reading*)write(’Please type three integers splitted by spaces: ’);read(n1);read(n2);readln(n3);(* Initially, we have no idea about how the numbers are sorted*)if (n1<n2) thenbegin

aux:=n1;n1:=n2;n2:=aux

end;(* Now, n1>n2*)if (n2<n3) then

beginaux:=n3;n3:=n2;n2:=aux

end;(* Now n3 has the smallest value*)if (n1<n2) thenbegin

aux:=n1;n1:=n2;n2:=aux

end;

writeln(’The sorted values are ’,n1:4:4,’, ’,n2:4:4,’, ’,n3:4:4,’.’)

end.

Exercise 2.11. Write a program that reads a numeric mark (an integer in the interval [0, 10]) andthen displays the qualitative grade the mark corresponds to. The program must be prepared todisplay an error message in case the value input by the user is not in the expected interval. Thetable of correspondences is as follows:

Mark Qualitative grade[0, 5) Fail[5, 7) Pass[8, 9) Honors[9, 10] High honors

�This exercise is an example of the use of a case-of for simplifying the organization of a large

number of potential behaviours of the program. When more than two consecutive values canbe listed in the same alternative, we define them as a range (using double dot, as in 0..4). Ifthere are only two of such values, the comma is preferred, although writing 5..6 will producethe same result as 5,6.

29

Page 31: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

Program 28: Exercise 2.11

program c02e11;var

m:integer;begin

(* Reading the values*)write(’Please type the mark: ’);readln(m);(* Now we have ranges defining the qualitative result*)case m of0..4: writeln(’The grade is: Fail’);5,6: writeln(’The grade is: Pass’);7,8: writeln(’The grade is: Honours’);9,10: writeln(’The grade is: High Honours’)else

writeln(’The mark is not valid.’)end

end.

The surrogate version, not making use of the case-of construction, is not as clear as theprevious. Hence, if a multi-branch alternative is to be taken based upon the value of an integeror char, case-of is preferred.

Program 29: Exercise 2.11

program c02e11;var

m:integer;begin

(* Reading the values*)write(’Please type the mark: ’);readln(m);(* We now use 2-fold alternatives*)if (m<0) then

writeln(’The mark is not valid.’)else if (m<=4) then

writeln(’The grade is: Fail’)else if (m<=6) thenwriteln(’The grade is: Pass’)

else if (m<=8) thenwriteln(’The grade is: Honours’)

else if (m<=10) thenwriteln(’The grade is: High Honours’)

elsewriteln(’The mark is not valid.’)

end.

Exercise 2.12. Write a program that reads 2 angles in radians (as reals) and shows their sum indegrees and radians. Note that all of the values must be in the interval [0, 360[ (in the degreescale) and [0, 2π[ (in the radian scale).

�In this program the difficulty comes at restraining the value to be displayed. The main

complexity comes from the fact that the sum of two angles might go outside of the predefinedinterval. In such case, we only need to substract 2*PI to the result to generate the appropriatevalue.

30

Page 32: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Alternative constructions

Program 30: Exercise 2.12

program c02e12;const

PI=3.14159;var

a1,a2,aTotal:real;begin

(* Reading the values*)write(’Please type the first angle (in radians): ’);readln(a1);write(’Now type the second one: ’);readln(a2);(* Adding them up*)aTotal:=a1+a2;if (aTotal>2*PI) thenaTotal:=aTotal-2*PI;

(* Displaying the result*)writeln(’The total angle is ’,aTotal:2:2,’ radians ’);writeln(’ (= ’,aTotal*180/PI:3:2,’ degrees).’)

end.

Exercise 2.13. Write a program that reads 3 angles in radians (as reals) and displays the mag-nitude of the greatest vector (cross) product than can be produced with two of them, assumingthey represent vectors of magnitude 1.

�The magnitude cross product is given by the product of the magnitude of the vectors mul-

tiplied by the sine of the angle they generate. Since the magnitudes are assumed to be 1, werestrict the analysis to the comparison of the sine of the difference between any two angles. Notetwo different facts. First, since we are only interested in the magnitude of the vector, we canapply the difference of angles in any order, then calculate the absolute value. Second, we needto apply the max operator twice to be able to handle 3 elements.

Program 31: Exercise 2.13

program c02e13;uses math;const

PI=3.14159;var

a1,a2,a3:real;begin

(* Reading the values*)write(’Please type the three angles (in radians): ’);read(a1);read(a2);readln(a3);(* Calculating the maximum vectorial product.*)write(’The max vectorial product is: ’);writeln(abs(max(sin(a1-a3),max(sin(a1-a2),sin(a2-a3)))):1:3,’.’)

end.

31

Page 33: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

Exercise 2.14. Write a program that reads the coefficients of a 2nd order equation ax2 + bx + c = 0and obtains all the real solutions it has.

�There are different considerations to be taken in the resolution of this program, that lead to

different ways of proceeding. First, if a = b = 0, then the equation is not well posed. Then, incase a = 0 but b , 0, the solution is unique and straight (that would be, in fact, a first orderequation). Finally, the remaining case depends upon the number of solutions of the square rootin the formula

x =−b ±

b2 − 4ac2a

.

In case√

b2 − 4ac has no real solution, then there are no real solutions for the equation either.If√

b2 − 4ac has a single real solution (because b2− 4ac = 0), the solution for the equation is

unique. Otherwise, we must consider the two options in the ± operator.

Program 32: Exercise 2.14

program c02e14;uses math;const

PI=3.14159;var

a,b,c,sqrtVal:real;begin

(* Reading the values*)write(’Please type the three coefficients: ’);read(a);read(b);readln(c);(* Now discerning the different options*)if (a=0) then

if (b=0) thenwriteln(’The equation is wrongly posed’)

elsewriteln(’The single solution is ’,-c/b:3:4,’.’)

elseif ((b*b-4*a*c) <0) then

writeln(’The equation has no real solution.’)else if ((b*b-4*a*c) =0) then

writeln(’The single solution is ’,-b/(2*a):3:4,’.’)elsebegin

sqrtVal=sqrt(b*b-4*a*c);writeln(’The solutions are ’,(-b+sqrtVal)/(2*a):3:4,’,’);writeln(’ and ’,(-b-sqrtVal)/(2*a):3:4,’.’)

end;end.

Exercise 2.15. Write a program that acts as a calculator. First, the program must ask for 2real numbers a and b. Then, the user must input for a command letter ’s’,’d’, ’p’ or ’v’,representing the sum, the difference, the product or the division. The result of the operationwith a and b has to be displayed with only 2 digits in the fractionary part.

32

Page 34: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Alternative constructions

This program is yet another example of the use of case-of for the organization of severaloptions in the program.

Program 33: Exercise 2.15

program c02e15;var

val1,val2:real;comm:char;

begin(* Reading the data*)write(’Please type the first value: ’);readln(val1);write(’Please type the second one: ’);readln(val2);writeln(’Now choose the command’);writeln(’ s - sum’);writeln(’ d - difference’);writeln(’ p - product’);writeln(’ v - division’);write(’Selection: ’);readln(comm);(* checking the value stored in comm *)case comm of’s’: writeln(’The operation is ’,val1:3:2,’+’,val2:3:2,’=’,(val1+val2):3:2);’d’: writeln(’The operation is ’,val1:3:2,’-’,val2:3:2,’=’,(val1-val2):3:2);’p’: writeln(’The operation is ’,val1:3:2,’*’,val2:3:2,’=’,(val1*val2):3:2);’v’: writeln(’The operation is ’,val1:3:2,’/’,val2:3:2,’=’,(val1/val2):3:2);else

writeln(’Invalid command’)end

end.

33

Page 35: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

34

Page 36: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Chapter 3

Iterative constructions

3.1 Contents of this chapter

This chapter covers the following contents:

1.a Iterative structure for using to and downto clauses.

1.b Iterative structure while.

1.c Iterative structure repeat.

3.2 Brief review

Computer programs are usually based on the repetition of a sequence of instructions. It wouldbe very inconvenient for a programmer to rewrite the instructions casting such sequences severaltimes. Moreover, the programmer might not know in advance how many times the sequencesmust be repeated. Hence, most of the modern programming languages allow for the use of theso-called iterative constructions, that is, constructions that force the program to repeat (iterate)the same sequences several times. Moreover, the number of times the code is to be repeated canbe dependent upon the data input by the user so that there is no need for the programmer tohave that knowledge in advance.

There are three iterative constructions considered in this chapter: for, while and repeat

structures. Very often, two or even three of them can be applied to solve a given solution.However, their semantic is different, and hence very often one of the solutions is slightly moreappropriate than the others. The syntax of these structures is included in Figures 3.1-3.3.

The first of the iterative structures covered in this book is the for structure. This structureallow for the repetition of some code as many time as indicated by a pair of integer values. Thekey concept in this structure is that of the counting variable (var, in Fig. 3.1). This variable takesan initial value (initVal), and is then modified by one unit each time the code in the instructionblock is repeated. Eventually, when the counter goes over (or under) a predefined limit, theiteration stops.

In a for structure, we can use either a to or a downto clause. The only difference betweenthem is whether the counter variable (var) is increased or decreased at each iteration. When theto clause is used, the iteration is kept until the counter is greater than finalVal. Alternatively,if downto is used instead, the iteration is hold until the counter is lower than finalVal. Notethat, if using the to clause, we should use a finalVal greater than initVal. Otherwise, as seen

35

Page 37: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

...

[Precedent code]

for var:=initVal to finalVal do

Instruction Block

[Following code]

...

[Precedent code]?

var:=initVal

?

var ≤ finalVal

?

Instruction block

-

true false

var:

=va

r+1

?[Following code]

(a) for structure with to clause

...

[Precedent code]

for var:=initVal downto finalVal do

Instruction Block

[Following code]

...

[Precedent code]?

var:=initVal

?

var ≥ finalVal

?

Instruction block

-

true false

var:

=va

r-1

?[Following code]

(b) for structure with downto clause

Figure 3.1: Schematic representation of the if-then-else constructions

36

Page 38: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Iterative constructions

...

[Precedent code]

while booleanExpression do

Instruction Block

[Following code]

...

[Precedent code]?

booleanExpression

?

Instruction block

-

true false

?[Following code]

(a) while structure.

Figure 3.2: Schematic representation of the while construction.

in the diagram in Fig. 3.1(a), the iteration block would never be executed. In the same way, ifusing downto, it should hold that initVal is greater than finalVal.

The for structure can be used when the number of iterations can be defined in numericterms. However, sometimes we might expect a program to do something until some conditionholds. For example, we might be interested in the program to ask the user for some piece ofdata until he or she inputs one satifying some criterion of validity. Hence, we would expect theprogram to repeat the inquiry until the value input by the user is satisfactory. It is impossibleto characterize how many iterations the program has to perform in numerical terms, but it ishowever rather easy to explain it as a boolean condition. Consequently, the while structure wascreated as a commodity to ease the work of the programmer in such situations.

The while structure, included in Fig. 3.2, iterates over an instruction block until some condi-tion is evaluated as false. The booleanExpression can include any kind of functions, operationsor variables, as long as it can be evaluable in a boolean way. Note that the boolean expression isevaluated before reaching the instruction block. Hence, in case the boolean expression is falsewhen the while structure is reached, the instruction block will never be executed, not even once.

A very important difference between for and while is that in the latter we are in charge ofmaking the changes to exit the iteration. That is, there are no embedded modification of a variable(as in the for), which will eventually lead to the exiting of the iteration. When using while, wehave to be cautious with the selection of the iteration, or we might make the program stay in theiteration forever. Hence, the selection of an appropriate booleanExpression is of paramountimportance.

The last of the iterative structures is the repeat, as recap in Fig. 3.3. This structure is verysimilar to the while, since it also relies on a boolean condition to decide whether to stay or leavethe iteration. However, there are two clear differences: (a) the condition is checked at the end ofthe instruction block and (b) the iteration is hold until the boolean expression is true. Note that (a)forces the instruction block to be executed at least once, differently from what happened in thewhile structure.

3.3 On the selection of an iterative structure

As happened with the iterative structure, there exist several situation for which more than oneiterative structure is appropriate. Indeed, they capabilities of each of them are very similar,although they are presented in a rather different way. In order to preserve the readability of the

37

Page 39: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

...

[Precedent code]

repeat

Instruction Block

until booleanExpression

[Following code]

...

[Precedent code]?

booleanExpression?

Instruction block-

true

fals

e

?[Following code]

(a) repeat structure.

Figure 3.3: Schematic representation of the repeat construction.

code, as well as the best-possible programming manners, we should always use the structurethat better suits the semantics of the problem. As a general rule, we have to identify whetherthe number of iterations is determined by numerical values or by some logical conditions. If thefist is hold, and we can establish the number of iterations to be performed before entering theiterative structure, we should use for. Alternatively, if we cannot know before entering howmany times we have to iterate over the instruction block, then either while or repeat shouldbe used. In order to pick up one of these, a rule of thumb is considering that, if the instructionblock has to be executed at least once, then a repeat is more suitable.

Still, may we note that the diversity of the problems tackled with real world make it impossibleto define strict rules. The best tool the programmer has to successfully identify the mostappropriate construction for each situation is a deep comprehension of the specificities of each ofthem. Then, he or she will be able to judiciously evaluate each situation he or she comes across.

3.4 Exercises

This chapter contains three different blocks of exercises. In Section 3.4.1 we present simplisticexercises to get in touch with the iterative structures. Section 3.4.2 tackles the inline processingof sequences of unknown length. To conclude, Section 3.4.3 includes exercises on which theiterative structures are used to generate uncommon on-screen displays.

3.4.1 Iterative processing

Exercise 3.1. Write a program that asks a user to introduce an integer as many times as necessaryuntil it is positive.

�In this case we enclose the typical write/read instruction pair into a repeat structure. The

selection of repeat over the other options is due to two facts: (a) we don’t know in advance howmany attempts it will take the user to input a valid number and (b) we have to read the valueinput by the user at least once, so the semantic fits better into a repeat than into a while.

38

Page 40: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Iterative constructions

Program 34: Exercise 3.1 (Version A)

program c03e01;var

a:integer;begin

repeatwrite(’Please input a positive integer: ’);readln(a)

until (a>=0);writeln(’The number is ’,a,’.’)

end.

In case we prefer to use while instead of a repeat, we need to include twice the write/read,so that the variable already has a value by the time we perform the first comparison.

Program 35: Exercise 3.1 (Version B)

program c03e01;var

a:integer;begin

write(’Please input a positive integer: ’);readln(a);while (a<0) do (* Exit when positive *)begin

write(’Please input a positive integer: ’);readln(a)

end;writeln(’The number is ’,a,’.’)

end.

Exercise 3.2. Write a program that reads an integer number from the keyboard. Then, it demandsthe user for another one. Repeat the second part until the absolute value of the second integeris at least 5 times greater than the absolute value of the first one.

�This exercise is quite similar to the previous one. In this case we only need to repeat the

questioning on the second variable. This is why we leave the reading of a outside the iterativestructure. Note that, again, for is not applicable, since we cannot estimate, before entering theiterative structure, how many times the instruction block is to be repeated.

Program 36: Exercise 3.2

program c03e02;var

a,b:integer;begin

write(’Please input the first integer: ’);readln(a);repeat

write(’Please input the second integer: ’);readln(b)

until (abs(b)>=(5*abs(a)));writeln(’The numbers are a=’,a,’ and b=’,b,’.’)

end.

39

Page 41: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

Exercise 3.3. Write a program that asks the user for 2 integer numbers, the second being greaterthan the first one. Then, displays all the odd numbers existing between the first and the secondone (both included).

�In this exercise we will check all the numbers in the interval specified by the user. Con-

sequently, the program needs to check all the values between the first integer (say a) and thesecond one (b). Note that now, opposedly to what happened in previous exercises, we knowhow many iterations we have to perform: the amount of integer numbers within that interval.Hence, we use a for construction in which the counting variable takes the initial value a, andincreases until it surpasses b. At each iteration that same variable, namely i, represents thecandidate number.

Program 37: Exercise 3.3 (Version A)

program c03e03;var

a,b,i:integer;begin

write(’Please input the first integer: ’);readln(a);write(’Please input the second integer: ’);readln(b);for i:=a to b do

if (i mod 2 =1) thenwrite(i,’ ’);

writelnend.

Although the for structure is the most convenient option when the range of the iteration isfixed (i.e. when we know in advance when is the iteration starting and finishing), we could alsouse a while. Note that in this case we have to explicitly increase the counter of positions with thestatement i:=i+1; Otherwise, i would never be increased, and the program would stay foreverin the iteration.

Program 38: Exercise 3.3 (Version B)

program c03e03;var

a,b,i:integer;begin

write(’Please input the first integer: ’);readln(a);write(’Please input the second integer: ’);readln(b);i:=a;while (i<=b) do

beginif (i mod 2 =1) thenwrite(i,’ ’);

i:=i+1end;

writelnend.

40

Page 42: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Iterative constructions

Exercise 3.4. Write a program that demands the user to input two positive integer numbers.Then, increases them unit by unit as many times as necessary until their product becomes greaterthan 1000.

�Doing this in an iterative way simply consists of repeatedly increasing in one unit the value

of both variables, until their product reaches the expected value. We prefer for this the while

structure because, if the product of the numbers input by the user is over 1000, there is no needfor increasing the numbers.

Program 39: Exercise 3.4 (Version A)

program c03e04;var

a,b:integer;begin

write(’Input a integer number: ’);readln(a);write(’Input another integer number: ’);readln(b);while (a*b<1000) do

beginb:=b+1;a:=a+1

end;writeln(’Now a=’,a,’, and b=’,b,’.’)

end.

Note that there is no need for iterative constructions to solve the problem. The reason isthat we can preview the number of iterations that we are going to need. Considering we expect(a + k) ∗ (b + k) > 1000, we can compute k and avoid using iterative structures of any kind.

Program 40: Exercise 3.4 (Version B)

program c03e04;uses math;var

a,b:integer;k:real;

beginwrite(’Input a integer number: ’);readln(a);write(’Input another integer number: ’);readln(b);

if (a*b<1000) thenbegin

k:=(1000-a-b)/2;a:=a+ceil(k);b:=b+ceil(k)

end;

writeln(’Now a=’,a,’, and b=’,b,’.’)end.

41

Page 43: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

Exercise 3.5. Write a program that asks a user for two integers and calculates their product notusing the neither product (*) nor division (div, /) operators.

�To solve this exercise we only need to sum the first integer (a) as many times as the value of

the second integer (b). That is, we have to iterate the sum of a a fixed number of times, which isgiven by b, what intuitively leads to the use of a for construction. Note that the result is storedin a variable result that must be initialized to 0. An alternative to this initialization would havebeen setting result:=a, but in this case we would have needed one iteration less, so that theinitial value of i in the for structure would have been 2 instead of 1.

Program 41: Exercise 3.5 (Version A)

program c03e05;var

a,b,result:integer;i:integer;

beginwrite(’Please type the first integer: ’);readln(a);write(’Please type the second integer: ’);readln(b);

result:=0;for i:=1 to a do

result:=result+b;

writeln(’The result is ’,result)end.

Note that if a is much greater than b, the program will be performing an unnecessarilyhigh number of iterations. The program can be optimized by summing the greatest number asmany times as the value of the smallest. By doing this, we keep the number of iterations to theminimum, but we still produce the right result. However, we have the drawback of checking,at each iteration, which is the minimum and the maximum of the two values introduced by theuser. Moreover, the program is not very easy to read, compared to the previous one.

Program 42: Exercise 3.5 (Version B)

program c03e05;uses math;var

a,b,result:integer;i:integer;

begin(* Reading the values *)write(’Please type the first integer: ’);readln(a);write(’Please type the second integer: ’);readln(b);(* Computing the product *)result:=0;for i:=1 to min(a,b) doresult:=result+max(a,b);

writeln(’The result is ’,result)end.

42

Page 44: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Iterative constructions

Instead of using max/min functions, we could also force a to contain the lowest of both values.That is, the program can always be sure that a will have the smallest of the values, while b willhave the greatest one. In the following program we use a simple comparison to always leave ina the lowest value. Hence, by the time we reach the iteration, we know that a ≤ b.

Program 43: Exercise 3.5 (Version C)

program c03e05;var

a,b,result,aux:integer;i:integer;

beginwrite(’Please type the first integer: ’);readln(a);write(’Please type the second integer: ’);readln(b);(* First we make sure that a holds the smallest value *)if (b<a) then

beginaux:=a;a:=b;b:=aux

end;(* Now we compute the sum *)result:=0;for i:=1 to a doresult:=result+b;

writeln(’The result is ’,result)end.

Exercise 3.6. Write a program that asks a user for an integer number n. Then, displays the n firstnumbers of the Fibonacci sequence.

�The Fibonacci sequence is an infinite sequence of integer that starts with two ones (1’s), and

from there one any number is composed by the sum of the previous twe.To calculate an upcoming number in the Fibonacci number we only need the two previous

values. Hence, we will produce an iteration to evolve through the sequence only rememberingthe two previous numbers. In order to keep those numbers we declare two variables underthe names a and b. Once this is done, we perform an iteration starting at the position 3 of thesequence (note that the two first values are already computed in a and b). At each position ofthe sequence we use the variable aux to produce the new number.

Program 44: Exercise 3.6

program c03e06;var

a,b:integer;aux,i:integer;num:integer;

begin

write(’Please type the number: ’);readln(num);(* The first values in the Fibonacci sequence are 1 *)a:=1;

43

Page 45: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

write(a,’, ’);b:=1;write(b,’, ’);

(* Now comes the sequence from second position on *)for i:=3 to num dobegin

aux:=a+b;a:=b;b:=aux;write(b,’, ’)

endend.

Exercise 3.7. Write a program that asks the user for 2 integer numbers, the second being greaterthan the first one. Then, displays all the numbers existing between the first and the second one(both included), in decreasing order.

�In this exercise we have to use a for statement to go though the numbers. The clause used

to modify the counting variable is downto, since the sequence has to be decreasing.

Program 45: Exercise 3.7

program c03e07;var

a,b,i:integer;begin

write(’Please input the first integer: ’);readln(a);write(’Please input the second integer: ’);readln(b);

for i:=b downto a dowrite(i,’ ’);(* The space separates the numbers *)

writeln(* Jumping the line *)end.

Exercise 3.8. Write a program that asks the user for 2 integer numbers, the second being greaterthan the first one. Then, displays all the numbers existing between the first and the second one(both included). First, all the odd numbers (including the numbers input by the user) mustappear in decreasing order in the same line. Then, all the even numbers (including the numbersinput by the user) must appear in another line in increasing order.

�In this exercise we have to go twice through the numbers in the sequence of numbers

contained between the values input by the user. The first time, we must traverse the sequence indecreasing order, displaying all the odd numbers. Then, we make the way in increasing order,displaying the even ones. Both of the tasks fits a for statement, the difference being the fact thatthe first one uses a downto clause, while the second uses a to. To complete the exercise we needto consider the use of mod 2 for discriminating even and odd numbers.

44

Page 46: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Iterative constructions

Program 46: Exercise 3.8

program c03e08;var

a,b,i:integer;begin

write(’Please input the first integer: ’);readln(a);write(’Please input the second integer: ’);readln(b);for i:=b downto a doif (i mod 2 =1) then

write(i,’ ’);writeln;(* Jumping the line *)for i:=a to b doif (i mod 2 =0) thenwrite(i,’ ’);

writelnend.

3.4.2 Computing with sequences

The exercises on sequences are based on the analysis of a series of numbers or characters. Wenever know in advance how many elements the sequence will have, so while and repeat arethe mainstream options to handle the iteration. Moreover, the program is required to capturesome information about the elements of the sequence, so that we need to mantain some kindof data about what we have seen so far, but at the same time having the ability to modify thatinformation depending upon the elements in the sequence.

Exercise 3.9. Write a program that demands the user for as many characters as necessary untilthe user inputs the same character 2 times in a row.

�Now we don’t have any idea of how many attempts it will take the user to satisfy the

condition. Hence, we use a while structure. In this exercise we use the variable b to save thelast value, while the one before the last one is stored in a. In this way, each time the user inputs anew number, a is updated (taking the value in b), while b stores the new one.

Program 47: Exercise 3.9

program c03e09;var

a,b:char;begin

write(’Please input a char and press enter: ’);readln(a);write(’Please input the second char and press enter: ’);readln(b);while (a<>b) dobegin

a:=b;write(’Please another char and press enter: ’);readln(b)

endend.

45

Page 47: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

Exercise 3.10. Write a program that demands the user as many integer numbers as necessaryuntil the user inputs one that is 3 times greater than the one he or she input 2 positions before.

�In order to solve the problem we need to keep track of as many as 3 numbers in the sequence,

until the last one is 3 times greater than the one 2 positions before. Hence, we need threevariables, namely a1, a2 and a3, These variables are are going to store, at each position of thesequence, the last three values. Hence, each iteration they have to be updated as if they castsome sort of chaing Every time we read an integer, it will be stored in a3). At the same time, a1and a2 need to be updated using the values obtained from the previous iteration The iterativeprocess stops when the comparison of a1 and a3 satisfies the exiting condition.

Program 48: Exercise 3.10

program c03e10;var

a1,a2,a3:integer;begin

(* Reading the values *)write(’Please input the first integer and press enter: ’);readln(a1);write(’Please input the second integer and press enter: ’);readln(a2);write(’Please input the third integer and press enter: ’);readln(a3);(* Iterating *)while (a3<a1*3) dobegin

(* The previous a2 is now the new a1 *)a1:=a2;(* Same for a2 and a3 *)a2:=a3;write(’Please input another integer and press enter: ’);readln(a3)

endend.

Exercise 3.11. Write a program that demands from the user as many integer numbers as necessaryuntil the sum of those input in even positions is 2 times greater than the greatest integer inputin an odd position.

�Again, the complexity of this problem relies on the information we need to keep while the

sequence passes through. Our program must maintain two pieces of information: the sum ofthe integers at even positions (evenSum) and the value of the greatest integer at an odd one(evenSum). Then, in order to know whether we are at an even or odd position, we use a booleanvariable (evenPos) that inverts its value at each iteration. We could also have done the even/odddiscrimination using a counter of the numbers that were already input, but using a booleanvariable we make the program simpler. As long as it does not hinders the understandability ofthe program, simplicity is one of the key goals of a programmer.

46

Page 48: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Iterative constructions

Program 49: Exercise 3.11

program c03e11;var

a:integer;greatestOdd,evenSum:integer;evenPos:boolean;

beginwrite(’Please input the first integer and press enter: ’);readln(a);greatestOdd:=a;write(’Please input the second integer and press enter: ’);readln(a);evenSum:=a;evenPos:=false;(* Start reading more numbers as long as the condition is satisfied *)while (2*greatestOdd>evenSum) do

begin(* 1- Reading the number *)write(’Please input another integer and press enter: ’);readln(a);(* 2- Processing the number *)if (evenPos) then

evenSum:=evenSum+aelse

if (a>greatestOdd) thengreatestOdd:=a;

(* 3- Changing the even/odd flag *)evenPos:=not(evenPos)

endend.

Exercise 3.12. Write a program that reads from the user a sequence of chars ended by ’.’, andcounts the number of letters (either upper or lower case) typed by the user.

�To solve this problem we need to count the number of letters using one integers. To do so

we only need to distinguish between letter and non-letter chars. In this case we do it with an if

statement in which we check whether the char is enclosed in the lower or upper case range.

Program 50: Exercise 3.12 (Version A)

program c03e12;var

c:char;counter:integer;

beginwriteln(’Please input the sequence of characters ended by dot (.): ’);counter:=0;repeat

(* 1- Reading the upcoming value *)read(c);(* 2- Updating the other variables *)if ( ((’a’<=c) and (c<=’z’)) or ((’A’<=c) and (c<=’Z’))) thencounter:=counter+1;

until(c=’.’);writeln(’There were ’,counter,’ letters in the sequence’)

end.

47

Page 49: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

In order to make the comparison simpler we might use the function lowercase, whichconverts any char (if possible) to its lower case representation. If using this function, we onlyneed to know if the letter is included in the lower-case range of letters.

Program 51: Exercise 3.12 (Version B)

program c03e12;var

c:char;counter:integer;

beginwriteln(’Please input the sequence of characters ended by dot (.): ’);counter:=0;repeat

(* 1- Reading the upcoming value *)read(c);(* 2- Updating the other variables *)if ((’a’<=lowercase(c)) and (lowercase(c)<=’z’)) then

counter:=counter+1;until(c=’.’);writeln(’There were ’,counter,’ letters in the sequence’)

end.

Exercise 3.13. Write a program that reads from the user a sequence of integers ended by anynegative number. Then, counts how many times the sequence 1 2 3 occurs in consecutivepositions.

�Once again in this case we need to keep track of the last 3 values input by the user, plus

the number of times the situation has been repeated. So, the program consists of an iteration inwhich we make the comparison of the values and the subsequent updating.

Program 52: Exercise 3.13

program c03e13;var

a1,a2,a3:integer;counter:integer;

beginwriteln(’Please input the sequence of integers ended by a negative: ’);counter:=0;a3:=0;a2:=0;repeat

(* 1- Reading the upcoming value *)read(a1);if ( (a1=3) and (a2=2) and (a3=1)) then

counter:=counter+1;(* 2- Updating the other variables *)a3:=a2;a2:=a1;

until(a1<0);writeln(’There were ’,counter,’ subsequences 1-2-3 in the sequence’)

end.

48

Page 50: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Iterative constructions

Exercise 3.14. Write a program that reads from the user a sequence of integers ended by anynegative number. Then, counts how many times the sequence 1 2 3 occurs in non-consecutivepositions. That is, after a 1 all the values are ignored until a 2 occurs, and so on.

�This program is conceptually more difficult than the previous, since we cannot store all the

previous value at each position of the sequence. So, instead of maintaing that, we will keep trackof the next expected value in the 1-2-3 subsequence. We do so by using the variable nowWaiting,which stores the next value we are waiting for in such subsequence. This variable is initialized to1, since that is the first value we are awaiting. Then, every time we were expecting (and found)a 3, we increase the counter and reset nowWaiting to 1.

Program 53: Exercise 3.14

program c03e14;var

a:integer;nowWaiting:integer;counter:integer;

beginwriteln(’Please input the sequence of integers ended by a negative: ’);counter:=0;nowWaiting:=1;repeat

(* 1- Reading a new value *)read(a);(* 2- Updating the other variables *)if (nowWaiting=a) then

beginnowWaiting:=nowWaiting+1;if (nowWaiting=4) thenbeginnowWaiting:=1;counter:=counter+1

endend

until(a<0);writeln(’There were ’,counter,’ subsequences 1-2-3 in the sequence’)

end.

Exercise 3.15. Write a program that reads a sequence of characters ending with’.’ and computesthe length of the longest subsequence including only vowels.

�This program is based on the use of a counter for the number of vowels found in the current

subsequence (currentLength). When we are in the middle of a vowel subsequence, the variablestores the number of vowels we already went through. Otherwise, it is set to 0. Then, at eachiteration, we check whether the current length is maximal, and if so we store the valuemaxLength.

Note that we don’t need to remember what the previous character was, since that informationis provided by the own counter. The previous char was not a vowel if and only if currentLengthis greater than 0. Note also that every time the program finds a non-vowel characters, the counteris set to 0. Eventually, if many such characters are consecutive, the counter will be (unnecessarily)reset to 0. However, this is a toll payed to minimize the complexity of the problem.

49

Page 51: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

Program 54: Exercise 3.15

program c03e15;var

c:char;currentLength,maxLength:integer;

beginwriteln(’Please input the sequence of characters ended by dot (.): ’);currentLength:=0;maxLength:=0;repeat

(* 1- Reading a new value *)read(c);(* 2- Updating the other variables *)case c of

’a’,’e’,’i’,’o’,’u’:currentLength:=currentLength+1

elsecurrentLength:=0

end;if (currentLength>maxLength) then

maxLength:=currentLengthuntil(c=’.’);writeln(’The subsequence of vowels with max length has ’,maxLength,’ letters.’)

end.

Exercise 3.16. Write a program that reads a sequence of characters ending with ’.’ and countshow many times an upper case letter is placed right after a lower case one.

�The most evident alternative to solve this exercise is maintaining the last two chars in the

sequence. However, instead of remembering the last 2 chars introduced by the user, we will onlyremember whether it was a lower case letter or not using a boolean variable (prevWasLowerCase).That information, combined with the current char, is enough to decide whether the upper-lowercase combination has taken place.

Program 55: Exercise 3.16

program c03e16;var

c:char;prevWasLowerCase:boolean;counter:integer;

beginwriteln(’Please input the sequence of characters ended by dot (.): ’);counter:=0;prevWasLowerCase:=false;repeat

(* 1- Reading the next value *)read(c);(* 2- Updating the other variables *)if (prevWasLowerCase and (’A’<=c) and (c<=’Z’)) then

counter:=counter+1;prevWasLowerCase:=(’a’<=c) and (c<=’z’);

until(c=’.’);writeln(’The situation happened as many as ’,counter,’ times.’)

end.

50

Page 52: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Iterative constructions

Exercise 3.17. Write a program that reads a sequence of characters ending with ’.’ and countshow many times an upper case letter is placed right between 2 lower case ones.

�In this case we shall now keep memory of the last three values input by the user, which we

refer to as c (for the current), prevC and prevPrevC (for the past ones). Then, we only need tocompare at each iteration whether the requirements are fulfilled to increase the counter.

There is a reason why we cannot repeat the schema in the previous exercise, using a booleanvariable to remember whether it was a lower case letter. Now the treatment of each char in thesequence is different when they are the current, previous or previous to the previous element in thesequence. When the character is the current one, we are interested on whether it is a lower casechar. However, when a new char in input, that current becomes the previous char, so that we arenow interested on whether it is an upper case letter. Since we cannot represent those three facts(upper case, lower case or none of them) with a boolean, we shall not use booleans instead ofchars.

Program 56: Exercise 3.17

program c03e17;var

c:char;prevC, prevPrevC:char;counter:integer;

beginwriteln(’Please input the sequence of characters ended by dot (.): ’);(* Initializing the variables *)prevC:=’.’;prevPrevC:=’.’;counter:=0;repeat

(* 1- Reading the next value *)read(c);(* 2- Updating the other variables *)if ( (’a’<=c) and (c<=’z’) and (’A’<=prevC) and (prevC<=’Z’) and (’a’<=

prevPrevC) and (prevPrevC<=’z’) ) thencounter:=counter+1;

prevPrevC:=prevC;prevC:=c

until(c=’.’);(* Displaying the result *)writeln(’The situation happened as many as ’,counter,’ times.’)

end.

Exercise 3.18. Write a program that reads a sequence of characters ending with’.’ and computesthe largest distance between two consecutive lower case a’s.

�The resolution of this problem is similar to that of Exercise 3.15. The main difference is that

we now update maxDistance only when we find a new ’a’. However, we shall not include thecharacters on the left of the first ’a’ or those on the right of the last ’a’, since those sequences arenot enclosed by ’a’ symbols. To represent this fact, we only update the maxDistance counterwhen an ’a’ (the one that closes the subsequence on the right) is found.

51

Page 53: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

Program 57: Exercise 3.18

program c03e18;var

c:char;maxDistance,currentDistance:integer;

beginwriteln(’Please input the sequence of characters ended by dot (.): ’);currentDistance:=-1;maxDistance:=-1;repeat

(* 1- Reading the next value *)read(c);(* 2- Updating the other variables *)if (c=’a’) then

beginif (currentDistance>maxDistance) then

maxDistance:=currentDistance;currentDistance:=0

endelse

if (currentDistance>-1) then(* This means that we already found an ’a’ *)currentDistance:=currentDistance+1;

until(c=’.’);writeln(’The maximal distance is ’,maxDistance,’ positions.’)

end.

Exercise 3.19. Write a program that reads a sequence of characters ending with’.’ and computesthe length of the longest subsequence composed of the same character (either upper or lowercase).

�To solve this exercise we need to keep track of (a) the length of the current same-char sequence

and (b) the char that it is composed of. For the first aspect we use the variable currentLength,while the second is tackled by the variable currentChar. In case we find a new char that is equalto currentChar, we increase currentLength. In case we find a different char, we check whetherthe just finished subsequence was the longest so far and update our variables. Note that thechars are always stored in lower case, so we do not have to worry about the case anymore.

Program 58: Exercise 3.19

program c03e19;var

c:char;currentChar:char;maxLength,currentLength:integer;

beginwriteln(’Please input the sequence of characters ended by dot (.): ’);read(c);currentChar:=lowercase(c);currentLength:=1;maxLength:=1;while (c<>’.’) dobegin

(* 1- Reading the next value *)read(c);(* 2- Updating the other variables *)

52

Page 54: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Iterative constructions

if (lowercase(c)=currentChar) thencurrentLength:=currentLength+1

elsebeginif (currentLength>maxLength) thenmaxLength:=currentLength;

currentLength:=1;currentChar:=lowercase(c)

endend;

writeln(’The maximal length is ’,maxLength,’.’)end.

Exercise 3.20. Write a program that reads a sequence of characters ending with’.’ and discoverswhich is the vowel that appears later for the first time. In case all of the vowels are not includedin the sequence, a warning message must be displayed.

�In order to complete this exercise we need five boolean variables to know whether each of

the vowels already appeared in the sequence, plus a variable to save the letter that was the last toappear. Note that we only overwrite the value of lastVowel when no value was written before(it still has ’.’) and all the vowels have appeared. This situation will only happen once: thefirst time all the hasX variables are set to true, i.e. right after the last vowel appears for the firsttime.

Program 59: Exercise 3.20

program c03e20;var

c,lastVowel:char;hasA,hasE,hasI,hasO,hasU:boolean;

beginwriteln(’Please input the sequence of characters ended by dot (.): ’);hasA:=false;hasE:=false;hasI:=false;hasO:=false;hasU:=false;lastVowel:=’.’;repeat

(* 1- Reading the next value *)read(c);(* 2- Updating the other variables *)if (lowercase(c)=’a’) then hasA:=trueelse if (lowercase(c)=’e’) then hasE:=true

else if (lowercase(c)=’i’) then hasI:=trueelse if (lowercase(c)=’o’) then hasO:=true

else if (lowercase(c)=’u’) then hasU:=true;if ((lastVowel=’.’) and hasA and hasE and hasI and hasO and hasU) thenlastVowel:=c;

until (c=’.’);if (lastVowel=’.’) thenwriteln(’Some vowels did not appear in the sequence’)

elsewriteln(’The last vowel was: ’,lastVowel)

end.

53

Page 55: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

Exercise 3.21. Write a program that reads a sequence of integers ended by a zero (0) and countsthe weight of the heaviest subsequence of length 3.

�This program is a classical example of how to keep track of a finite number of past values.

An interesting point is the initialization of the values of the previous values when starting thesequence. We have chosen to use the minimum value an integer can take, and hence we setsuch variables to -32500. The reason is that this value will automatically prevent the 2 firstelements of the sequence from being considered as belonging to the heaviest sequences. Ofcourse, alternatives could be taken. An example would be reading the first two numbers outsidethe iteration in order to provide maxWeight with a meaningful initial value

Program 60: Exercise 3.21

program c03e21;const

MIN_INTEGER=-32500;var

n:integer;prevN,prevPrevN:integer;maxWeight:integer;

beginwriteln(’Please input the sequence of integers ended by zero (0): ’);(* 0- Initializing the values *)maxWeight:=MIN_INTEGER;prevN:=MIN_INTEGER;prevPrevN:=MIN_INTEGER;repeat

(* 1- Reading the next value *)read(n);(* 2- Updating the other variables *)if (n+prevN+prevPrevN>maxWeight) then

maxWeight:=n+prevN+prevPrevN;prevPrevN:=prevN;prevN:=n

until(n=0);(* Displaying the result *)writeln(’The maximal weight is ’,maxWeight,’.’)

end.

Exercise 3.22. Write a program that reads a sequence of characters ending with ’.’ and countsthe weight of the heaviest subsequence of length 3, provided that the weight of each letter isequal to its position in the alphabetical order (i.e., a and A count as 1, b and B count as 2,...). Anysymbol other than the letters has weight 0.

�This program is very similar to the previous, provided two differences. First, we have

the need to convert each letter to its numerical value; Second, the initialization of maxWeight,prevWeight and prevPrevWeight is easier, since we can set them to 0. This is possible because0 is the lowest value the sequence (and the individual values) can take, and consequently weknow that any sequence will be at least as heavy as 0. Appart from these two differences, theschema of the program is the same as in the past exercise.

54

Page 56: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Iterative constructions

Program 61: Exercise 3.22

program c03e22;var

c:char;currentWeight,maxWeight,prevWeight,prevPrevWeight:integer;

beginwriteln(’Please input the sequence of characters ended by dot (.): ’);prevWeight:=0;prevPrevWeight:=0;maxWeight:=0;repeat

(* 1- Reading the next value *)read(c);(* 2- Updating the other variables *)if (’a’<lowercase(c)) and (lowercase(c)<’z’) then

currentWeight:=ord(lowercase(c))-ord(’a’)else

currentWeight:=0;if (currentWeight+prevWeight+prevPrevWeight>maxWeight) thenmaxWeight:=currentWeight+prevWeight+prevPrevWeight;

prevPrevWeight:=prevWeight;prevWeight:=currentWeight

until(c=’.’);writeln(’The maximal weight is ’,maxWeight,’.’)

end.

Exercise 3.23. Write a program that reads a sequence of characters ending with ’.’ and checkswhether the parenthesis are well balanced. Note that we consider the parentheses to be wellbalanced when each of the left (opening) parenthesis can be matched to an exclusive right(closing) one.

�We solve this problem keeping a counter (parCount) of the number of left (opening) paren-

theses we have found. That is, the amount of parentheses that have been opened but not closed.There are two situations that might let us know that the parenthesis are wrongly balanced. First,in case parCount is positive (over 0) at the end of the sequence, we have that some parentheseshave been left open. Second, if parCount becomes negative at some position of the sequence,then the parenthesis must be wrongly balanced. Since we have to read the whole sequence, weneed both parCount to count the parentheses and result to indicate whether some inconsistencytook place at some point.

Program 62: Exercise 3.23

program c03e23;var

c:char;parCount:integer;result:boolean;

beginwriteln(’Please input the sequence of characters ended by dot (.): ’);parCount:=0;(* number of opened parenthesis *)result:=true;repeat

(* 1- Reading the next value *)read(c);(* 2- Updating the other variables *)

55

Page 57: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

if (c=’(’) thenparCount:=parCount+1

else if(c=’)’) thenbeginparCount:=parCount-1;if (parCount<0) thenresult:=false

enduntil(c=’.’);if (parCount=0) and result thenwriteln(’The parentheses are well balanced.’)

elsewriteln(’The parentheses are imbalanced.’)

end.

Exercise 3.24. Write a program that reads a sequence of characters ending with ’.’ and checkswhether at both sides of an ’a’ there exist at least one ’b’.

�This program consists of knowing whether we can find a ’b’ at each side of an ’a’. To solve

it we employ a boolean variable expectingB which let us know whether we are looking for a’b’ (if true) or an ’a’ (if false).

For starters, we are looking for a ’b’ before the first ’a’ is met. Otherwise, the sequencewould be wrongly typed. Then, each time we find an ’b’, we start looking for an ’a’, andvice versa. Note that finding a ’b’ when looking for an ’a’ is perfectly fine, but the opposite(two consecutive ’a’ with no ’b’) would make the sequence illegal. At the end, we need to belooking for an ’a’, since the opposite would mean that there is no ’b’ on the right of the last’a’. Note that the result variable (someAappear) we use to detect illegal situations must be setto true at the beginning since a sequence with no ’a’ would be perfectly legal.

Program 63: Exercise 3.24 (Version A)

program c03e24;var

c:char;expectingB,result:boolean;

beginwriteln(’Please input the sequence of characters ended by dot (.): ’);expectingB:=true;(* else is expecting an A *)result:=true;repeat

(* 1- Reading the next value *)read(c);(* 2- Updating the other variables *)if (c=’a’) thenif (expectingB) then

result:=false(* I needed a ’b’ but an ’a’ was found *)elseexpectingB:=true(* I found an ’a’, now I need a ’b’ coming *)

else if (c=’b’) thenexpectingB:=false (* Error condition fulfilled *)

until(c=’.’);if ((expectingB) or not(result)) thenwriteln(’The condition is not satisfied’)

elsewriteln(’The condition is satisfied’)

end.

56

Page 58: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Iterative constructions

Although the exercise appears to be complete, it has a failing scenario when no ’a’ or ’b’ isincluded in the sequence. In such a case, we have that expectingB is set to true, and hence thesequence is classified as illegal. To solve it, we use a boolean variable to know whether an ’a’

was found in the sequence. Note that, otherwise, any of such sequences is going to be valid.

Program 64: Exercise 3.24 (Version B)

program c03e24;var

c:char;someAappear:boolean;expectingB:boolean;result:boolean;

beginwriteln(’Please input the sequence of characters ended by dot (.): ’);expectingB:=true;(* otherwise it is expecting an A *)result:=true;someAappear:=false;repeat

(* 1- Reading the next value *)read(c);(* 2- Updating the other variables *)c:=lowercase(c);if (c=’a’) thenbegin

someAappear:=true;if (expectingB) then

result:=false(* I needed a B but an a was found *)elseexpectingB:=true(* I found an ’a’, now I need a ’b’ coming *)

endelse if (c=’b’) thenexpectingB:=false; (* Error condition fulfilled *)

until(c=’.’);if (((expectingB) or not(result)) and someAappear) then

writeln(’The condition is not satisfied’)else

writeln(’The condition is satisfied’)end.

Exercise 3.25. Write a program that reads a sequence of integers ended by a zero (0) and displaysthe number of pairs of consecutive even numbers.

�In this problem we need to remember whether the previous number was even or not. We use

a boolean variable (prevIsEven) to perform such task. Note that we initialize it with the falsevalue, so that the first integer in the sequence will never be accounted for. Otherwise, having aeven number as first element of the sequence, we would count it as a pair.

Program 65: Exercise 3.25

program c03e25;var

n:integer;prevIntIsEven:boolean;counter:integer;

beginwriteln(’Please input the sequence of integers ended by zero (0): ’);

57

Page 59: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

counter:=0;prevIntIsEven:=false;repeat

(* 1- Reading the next value *)read(n);(* 2- Updating the other variables *)if (prevIntIsEven and (n mod 2=1)) then

counter:=counter+1;prevIntIsEven:=(n mod 2=1)

until(n=0);writeln(’The situation happens ’,counter,’ times.’)

end.

Exercise 3.26. Write a program that reads a integers until a zero (0) is found and checks whetherthere exist some subsequence of 3 positions so that the sum of their elements is equal to 0.

�The only complexity in this problem comes from remembering, at each step of the sequence,

the value of the previous three values. Apart from that, we only need to sum the up each timeto see if the result is equal to 0.

Program 66: Exercise 3.26

program c03e26;const

MIN_INTEGER=-32500;var

n:integer;prevInt,prevPrevInt:integer;result:boolean;

beginwriteln(’Please input the sequence of integers ended by zero (0): ’);prevInt:=MIN_INTEGER;prevPrevInt:=MIN_INTEGER;result:=false;repeat

(* 1- Reading the next value *)read(n);(* 2- Updating the other variables *)if (prevInt+prevPrevInt+n=0) then

result:=true;prevPrevInt:=prevInt;prevInt:=n

until(n=0);if (result) then

writeln(’The situation happens at least once.’)else

writeln(’The situation does not happen in the sequence.’)end.

Exercise 3.27. Write a program that reads a sequence of integers and computes the number ofsubsequences of 3 positions so that their values are sorted in increasing order.

�This problem is very similar to the one in the Exercise 3.26, exception made that we are now

checking the ordering of the values, instead of their sum.

58

Page 60: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Iterative constructions

Program 67: Exercise 3.27

program c03e27;const

MAX_INTEGER=32500;var

n:integer;prevInt,prevPrevInt:integer;counter:integer;

beginwriteln(’Please input the sequence of integers ended by zero (0): ’);prevInt:=MAX_INTEGER;prevPrevInt:=MAX_INTEGER;counter:=0;repeat

(* 1- Reading the next value *)read(n);(* 2- Updating the other variables *)if ((prevPrevInt<=prevInt) and (prevInt<=n) ) then

counter:=counter+1;prevPrevInt:=prevInt;prevInt:=n

until(n=0);writeln(’The situation happens ’,counter,’ times.’)

end.

Exercise 3.28. Write a program that reads a sequence of integers and computes the number ofsubsequences of 3 positions so that their third value is equal to the product of the first two ones.

�Very similarly to what happened in the previous exercises, we now need to keep track of the

last three integers appearing in the sequence.

Program 68: Exercise 3.28

program c03e28;var

n:integer;prevInt,prevPrevInt:integer;counter:integer;

beginwriteln(’Please input the sequence of integers ended by zero (0): ’);prevInt:=0;prevPrevInt:=0;counter:=0;repeat

(* 1- Reading the next value *)read(n);(* 2- Updating the other variables *)if ((prevPrevInt*prevInt=n) ) then

counter:=counter+1;prevPrevInt:=prevInt;prevInt:=n

until(n=0);writeln(’The situation happens ’,counter,’ times.’)

end.

59

Page 61: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

Exercise 3.29. Write a program that reads a sequence of integers and computes the number ofsubsequences of 3 positions so that their product would be a negative (stricly under zero) value.

�This problem is very similar to the one in the Exercise 3.26.

Program 69: Exercise 3.29

program c03e29;var

n,prevInt,prevPrevInt:integer;counter:integer;

beginwriteln(’Please input the sequence of integers ended by zero (0): ’);prevInt:=0;prevPrevInt:=0;counter:=0;repeat

(* 1- Reading the next value *)read(n);(* 2- Updating the other variables *)if (prevPrevInt*n*prevInt<0) then

counter:=counter+1;prevPrevInt:=prevInt;prevInt:=n

until(n=0);writeln(’The situation happens ’,counter,’ times.’)

end.

Exercise 3.30. Write a program that reads a sequence of reals ended by a negative number andcomputes the number of elements at least 3 times greater than the product of the precedent andfollowing values.

�Again, this problem is very similar to the one in the Exercise 3.26.

Program 70: Exercise 3.30

program c03e30;var

r,prevReal,prevPrevReal:real;counter:integer;

beginwriteln(’Please input the sequence of integers ended by zero (0): ’);prevReal:=0;prevPrevReal:=0;counter:=0;repeat

(* 1- Reading the next value *)read(r);(* 2- Updating the other variables *)if (prevReal>=3*prevPrevReal*r) then

counter:=counter+1;prevPrevReal:=prevReal;prevReal:=r

until(r<0);writeln(’The situation happens ’,counter,’ times.’)

end.

60

Page 62: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Iterative constructions

3.4.3 On-screen matrix displaying

This problems consists of creating in the command line some sort of mosaic dependent uponsome value introduced by the user. Mostly, their resolution lies on finding out an expression ableto represent the information to be displayed at every position of the matrix. If such expression isfound, we only have the need of using a double for statement to go through rows and columns.

Exercise 3.31. Create a program that reads an integer N from the keyboard and writes a matrixof N ×N elements so that at each position (i, j) the value i · j is displayed. That is, a matrix suchas

1 2 3 . . . N2 4 6 . . . 2 ·N3 6 9 . . . 3 ·N. . . . . . . . . . . . . . .N 2 ·N 3 ·N . . . N2

�In this case the expression to be applied at each position is simply i · j, where i represents

the number of row and j the number of column. Note that we must write each cell with thecommand write, so that we stay in the same line until we finish each row.

Program 71: Exercise 3.31

program c03e31;var

n:integer;i,j:integer;

beginwrite(’Please input the value of n: ’);readln(n);for i:=1 to n dobegin

for j:=1 to n dowrite(’ ’,i*j:4,’ ’);

writelnend

end.

Exercise 3.32. Create a program that reads an integer N from the keyboard and writes a matrixof N × N elements so that at each position (i, j) the Manhattan distance to the main diagonal.That is, a matrix such as

0 1 2 . . . N1 0 1 . . . N − 12 1 0 . . . N − 2. . . . . . . . . . . . . . .N N − 1 N − 2 . . . 0

.

�The distance to the main diagonal is always the either the distance in horizontal or the distance

in vertical (it is always the same). Hence, at each position (i, j) we must display either |i − j| or| j − i|.

61

Page 63: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

Program 72: Exercise 3.32

program c03e32;uses math;var

n:integer;i,j:integer;

beginwrite(’Please input the value of n: ’);readln(n);for i:=1 to n do

beginfor j:=1 to n dowrite(’ ’,abs(i-j):4,’ ’);

writelnend

end.

Exercise 3.33. Create a program that reads an integer n from the keyboard and writes a matrixof n × n elements so that at each position (i, j) the value i · j is displayed if and only the positionbelongs to one of the matrix diagonals. That is, a matrix such as

1 . . . n4 . . .

9 . . .. . . . . . . . . . . . . . .n . . . n2

.

�An position (i, j) a matrix belongs to a diagonal (a) if i = j or (b) if i = j − n + 1. Hence, we

just need to use an if statement to discriminate those situations from the others. Note that, inorder for the matrix to be well aligned, we have to write some blank spaces even when there isno number to be displayed.

Program 73: Exercise 3.33

program c03e33;var

n:integer;i,j:integer;

beginwrite(’Please input the value of n: ’);readln(n);for i:=1 to n do

beginfor j:=1 to n doif ((i=j) or (i=n-j+1)) thenwrite(’ ’,i*j:4,’ ’)

elsewrite(’ ’);

writelnend

end.

62

Page 64: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Iterative constructions

Exercise 3.34. Create a program that reads an integer n from the keyboard and writes a matrixof n × n elements so that at each position (i, j) the value (i · n) + j is displayed if and only if it isan even number. Otherwise, the displayed value is 0. For example, if n = 5, the matrix is:

6 0 8 0 100 12 0 14 0

16 0 18 0 200 22 0 24 0

26 0 28 0 30

�In this exercise we also have to perform a discrimination based upon the values of i and j.

Program 74: Exercise 3.34

program c03e34;var

n:integer;i,j:integer;

beginwrite(’Please input the value of n: ’);readln(n);for i:=1 to n dobegin

for j:=1 to n doif (((i* N) +j) mod 2=0) then

write(’ ’,(i* N) +j:4,’ ’)elsewrite(’ ’);

writelnend

end.

Exercise 3.35. Create a program that reads an integer n from the keyboard and writes a matrixof n × n elements such as

1 2 3 . . . N − 1 N2 . . . N − 13 . . . N − 2. . . . . . . . . . . . . . . . . .

N − 1 . . . 2N N − 1 N − 2 . . . 2 1

�There exist now four configurations of i and j for which we need to display a value. Hence,

we nested if-else-if structure within the iteration.

Program 75: Exercise 3.35

program c03e35;var

n:integer;i,j:integer;

beginwrite(’Please input the value of n: ’);readln(n);

63

Page 65: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

for i:=1 to n dobegin

for j:=1 to n doif (i=1) then(* first row *)write(’ ’,j:3,’ ’)

else if (i=n) then(* last row *)write(’ ’,n-j+1:3,’ ’)

else if (j=1) then(* first column *)write(’ ’,i:3,’ ’)

else if (j=n) then(* last column *)write(’ ’,n-i+1:3,’ ’)

elsewrite(’ ’);

writelnend

end.

64

Page 66: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Chapter 4

Data structures

4.1 Contents of this chapter

This chapter covers the following contents:

4.a Use of vectors (one dimensional arrays).

4.b Use of matrices (two dimensional arrays).

4.c Use of strings.

4.2 Brief review

So far we have only used scalar variables, that is variables that contain one single elementof a given type. This is convenient for learning pourposes, but is far from what happens inreal applications. In fact, a large portion of the potential of computers lies on their ability tohandle huge amounts of data. If restricting to the contents of the previous chapters, in order tohandle a large number of variables we should declare them individually, each of them labeledwith a different name. This is extremely tedious and time consuming. Consequently, modernprogramming languages allow the programmer for declaring a large number of variables in a aso-called array structure. An array is a multidimensional grid of variables identified by a singlename, so that each of the individual variables it contains can be addressed by referring to itsposition in the grid. In a sense, the concept of array in programming languages is that of matrixin mathematical terms.

An array is defined by a name, exactly as a normal variable. In addition, it must also beassociated with a given type. The novelty in the definition of an array is the fact that we need todefine the range, that is the number of dimensions it has, as well as the number of elements ineach of the dimensions. Once the definition is done, the logical configuration of an array is as inFig. 4.1. As seen in that figure, in order to access (for reading or writing) each of the positions ofthe array, we must indicate the position it occupies at each of the dimensions. The configurationof an array is the same, independently of the type of its components.

The previous schema is the only possibility when dealing with arrays of integers, reals orbooleans, but managing sequence of characters can be tackled in two different ways. Processingtext is so common in modern programs that Pascal offers extra commodities in order to simplifythe task. More specifically, it offers the type string, which is a wrapper of an array of chars. A

65

Page 67: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

a[1] a[2] a[3] r r r a[N-1] a[N]

(a) Unidimensional array (vector) declared as a:array[1..N] of integer.

r r r r r ra[1][1] a[1][2] a[1][3] r r r a[1][N-1] a[1][N]

a[2][1] a[2][2] a[2][3]r r r

a[2][N-1] a[2][N]

a[M][1] a[M][2] a[M][3]r r r

a[M][N-1] a[M][N]

(b) Bidimensional array declared as a:array[1..M,1..N] of integer.

Figure 4.1: Schematic representation of arrays and matrices.

variable of type string can be used exactly as a variable of type array of char, and in additionoffers extra functionalities. The most interesting of such functionalities are the following:

� length(w)- The maximum length of a string has to be defined in the declarison of thevariable. However, it might be storing a sentence that does not fill the whole space. Byusing length(w) we obtain the number of positions (characters) the string is actuallyholding.

� readln(w)- The programmer can read a sentence at once by using readln(w), so thateverything the user input before pressing enter will be stored in the variable w. If thelength of w does not allow for all the text to fit in the variable, only the first chars are stored.After using this functionality, the length(w) returns the number of chars stored in thevariable.

In addition to the previous, there are special functions available for functions:

� [+] - The + symbol can act as concatenator of different strings. For example, the commandwrite(w1+w1) will display the same as write(w1,w1).

� concat(w1,w2,...,wn) - Concatenates a sequence of strings, exactly as the + operatordoes.

� [=] - The symbol = performs the char-by-char comparison of two strings, so that it producesa boolean true if and only if both strings have the same length and the same chars at eachof their positions.

� delete(w,pos,num) - Removes from the string as many as num positions starting from thepos-th one. The length of the string is consequently reduced.

� insert(w1,w2,pos) - Introduces at the position pos of the string w1 the substring w2. Thelength of the string is consequently increased.

66

Page 68: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Data structures

� str(num,w) - Stores in the variable w the text representation of num, where num is anynumeric (real or integer) variable.

� val(w,num,cod) - Stores in the numeric variable num the value represented by the stringw. In case the string w represents a number, the variable cod takes value 0, but if some erroroccurred cod takes a value other than 0.

� pos(w1,w2) - Find the first position at which w1 contains w2, if any. In case w2 does notappear in w1, the function returns the value 0.

� copy(w,pos,len) - Creates a new string that contains len chars of the string w starting atposition pos.

Considering all the functionalities they offer, very often it is more practical to use strings

instead of arrays of chars when handling sentences or words. However, note that string canonly hold lines of text, and cannot be used to substitute arrays of chars with more than onedimension (e.g. 2D matrices).

4.3 Exercises

4.3.1 Working with arrays and matrices

Exercise 4.1. Create a program that reads a vector of N positions (being N a constant) and displayits contents.

�When the length of an array is known (and that is the case for the exercises in this book),

the best way to go through its positions is using a for statement. Note that we define the rangeof the iteration using as limit value the constant previously declared, so that any change in thevalue of the constant does not invalidate the existing code.

Program 76: Exercise 4.1

program c04e01;const

N=10;type

realVector=ARRAY[1..N] OF real;var

i:integer;myVector:realVector;

begin(* 1- Reading the vector *)writeln(’About to start’);for i:=1 to N dobegin

write(’Enter value ’,i,’: ’);readln(myVector[i]);

end;(* 2- Displaying the values *)writeln(’The contents of the vector are:’);for i:=1 to N dowriteln(’At pos ’,i,’: ’,myVector[i]:4:3)

end.

67

Page 69: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

Exercise 4.2. Create a program that reads two vectors of N elements (being N a constant) andcalculates their scalar product. Each vector must be read at one single line, in which the user hasto input N numbers split by blank spaces.

�This exercise brings forward two different tasks: reading several values in the same line

and computing the scalar product of two vectors. For the former one, we have to use theread command, which reads all the consecutive digits until the user inputs a blank space, thencombines them to create a number. Since the read is enclosed in for construction, the process isrepeated as many as N times. In this way, the use does not need to be asked for several numbersone after another, alleviating the work of inputing a long sequence of numbers. Regarding theformer, we only need an accumulating variable that increasingly sums the product of the elementsin the vectors.

Program 77: Exercise 4.2

program c04e03;const

N=5;type

realVector=ARRAY[1..N] OF real;var

i:integer;vecA,vecB:realVector;result:real;

begin(* Reading the first vector *)writeln(’Introduce the first vector of ’,N,’ elements, splitted by blank spaces.’

);for i:=1 to N doread(vecA[i]);

(* Reading the second one *)writeln(’Introduce the second vector of ’,N,’ elements, splitted by blank spaces.

’);for i:=1 to N doread(vecB[i]);

(* Initializing the variable and computing the result *)result:=0;for i:=1 to N doresult:=result+vecA[i]*vecB[i];

(* Displaying the result *)writeln(’The result is ’,result:3:3,’.’)

end.

Exercise 4.3. Create a program that reads a matrix of N × N integers (being N a constant) anddisplays its elements.

�Working with matrices or, in a general way, with d-dimensional arrays is not problematic. In

this case, we use a double combination of indices for accessing the values, so that the first onerepresents the row, and the second one points out the column. Note that declaring a type for thematrix is not strictly necessary, but enhances slightly the readability of the program

68

Page 70: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Data structures

Program 78: Exercise 4.3

program c04e03;const

N=10;type

intMatrix=ARRAY[1..N,1..N] OF integer;var

i,j:integer;matA:intMatrix;

begin(* 1- Reading the vector *)writeln(’Introduce the matrix.’);for i:=1 to N dofor j:=1 to N dobegin

write(’Introduce the value at row ’,i,’ and col ’,j,’: ’);read(matA[i][j])

end;(* 2- Displaying the values *)for i:=1 to N dobegin

for j:=1 to N dowrite(matA[i][j],’ ’);

writelnend

end.

Exercise 4.4. Create a program that reads a vector of N reals (being N a constant), then finds outits min value, its max value and its mean.

�This exercise is solved by following a 2-step scheme. First, we need to read the whole array,

for later going trough all the values. Note that the variables minVal and maxVal must be setto some value before analyzing the first position of the array. In this case we set them to themaximum and minimum value an integer can have, respectively, so that they are never taken asfinal values of the variables. Note that the when the first element of the array is checked, bothminVal and maxVal are set to its value.

Program 79: Exercise 4.4 (version A)

program c04e04;const

N=10;type

intVector=ARRAY[1..N] OF integer;var

i:integer;myVector:intVector;minVal,maxVal,sum:integer;mean:real;

begin(* 1- Reading the vector *)writeln(’Introduce the vector of ’,N,’ elements, splitted by blank spaces.’);for i:=1 to N do

read(myVector[i]);(* 2- Obtaining the information *)minVal:=32000;maxVal:=-32000;

69

Page 71: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

sum:=0;for i:=1 to N do

beginif (myVector[i]<minVal) thenminVal:=myVector[i];

if (myVector[i]>maxVal) thenmaxVal:=myVector[i];

sum:=sum+myVector[i]

end;mean:=sum/N;writeln(’The max is ’,maxVal,’, the min is ’,minVal,’, and the mean is ’,mean

:3:3,’.’)end.

A more elegant way to overcome the problem of setting the initial values of minVal andmaxVal is using the value at the first position of the array. If doing this, we need to start thesecond for at the second position (i:=2), in order not to count the value of the first positiontwice in the computation of the mean.

Program 80: Exercise 4.5 (version B)

program c04e04;const

N=10;type

intVector=ARRAY[1..N] OF integer;var

i:integer;myVector:intVector;min,max,sum:integer;mean:real;

begin(* 1- Reading the vector *)writeln(’Introduce the vector of ’,N,’ elements, splitted by blank spaces.’);for i:=1 to N do

read(myVector[i]);(* 2- Obtaining the information *)min:=myVector[1];max:=myVector[1];sum:=myVector[1];for i:=2 to N dobegin

if (myVector[i]<min) thenmin:=myVector[i];

if (myVector[i]>max) thenmax:=myVector[i];

sum:=sum+myVector[i]

end;mean:=sum/N;writeln(’The max is ’,max,’, the min is ’,min,’, and the mean is ’,mean:3:3,’.’)

end.

The whole exercise could be done in a more efficient way by checking the values when theyare read, instead of first reading the whole array. However, although the program followingis more efficient, we will stick to the previous structure in the upcoming exercises, with thepourpose of making the programs as readable as possible.

70

Page 72: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Data structures

Program 81: Exercise 4.4 (version C)

program c04e04;const

N=10;type

intVector=ARRAY[1..N] OF integer;var

i:integer;myVector:intVector;min,max,sum:integer;mean:real;

beginwriteln(’Introduce the vector of ’,N,’ elements, splitted by blank spaces.’);(* Reading the first value *)read(myVector[1]);(* Setting the initial values *)min:=myVector[1];max:=myVector[1];sum:=myVector[1];(* Reading and processing the remaining values *)for i:=2 to N dobegin

read(myVector[i]);if (myVector[i]<min) then

min:=myVector[i];

if (myVector[i]>max) thenmax:=myVector[i];

sum:=sum+myVector[i]end;

mean:=sum/N;writeln(’The max is ’,max,’, the min is ’,min,’, and the mean is ’,mean:3:3,’.’)

end.

Exercise 4.5. Create a program that reads a vector of N integers (being N a constant), then findsout its standard deviation.

�The difference between this exercise and the previous is the fact that we need at least two

iterations over the values of the array to compute the expected result. The reason is that, inorder to compute the standard deviation, we need to know the mean of the values. Hence, afirst pass through the vector has to be accomplish to compute the mean, followed by a secondone to compute the standard deviation.

Program 82: Exercise 4.5

program c04e05;const

N=5;type

intVector=ARRAY[1..N] OF integer;var

i:integer;myVector:intVector;mean,std:real;

begin(* Reading *)

71

Page 73: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

writeln(’Introduce the vector of ’,N,’ elements, splitted by blank spaces.’);(* First pass computing the mean *)mean:=0;for i:=1 to N dobegin

read(myVector[i]);mean:=mean+(myVector[i]/N)

end;(* Second pass computing the standard deviation *)std:=0;for i:=1 to N dostd:=std+( (sqr(myVector[i]-mean))/N);

std:=sqrt(std);writeln(’The mean is ’,mean:3:3,’ and the standard deviation is ’,std:3:3,’.’)

end.

Exercise 4.6. Create a program that reads a vector A of N reals (being N a constant), and creates anew vector so that at every position i it contains the sum of all the values of A up to that position.

�Initially, this problem is solved by using a double loop. First, we have to read the vector A.

Then, for each position i, we perform an iteration up to that position accumulating the valuesstored in the vector A. Note that it is necessary a good practice to initialize the values in thevector B to 0.

Program 83: Exercise 4.6 (Version A)

program c04e06;const

N=5;type

intVector=ARRAY[1..N] OF integer;var

i,j:integer;A,B:intVector;

begin(* Reading *)writeln(’Introduce the vector of ’,N,’ elements, splitted by blank spaces.’);for i:=1 to N dobegin

read(A[i]);end;

(* Accumulating *)for i:=1 to N do

beginB[i]:=0;for j:=1 to i doB[i]:=B[i]+A[j]

end;(* Accumulating *)write(’The values in the vector are: ’);for i:=1 to N dowrite(B[i],’ ’);

end.

The exercise in the past form is not very efficient. Every time we increase the value of i, werecalculate the sum of all the values up to i-1. However, that sum is already stored in B[i].Hence, the solution can be simplified (and enhanced) by making use of such values

72

Page 74: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Data structures

Program 84: Exercise 4.6 (Version B)

program c04e06;const

N=5;type

intVector=ARRAY[1..N] OF integer;var

i:integer;A,B:intVector;

begin(* Reading *)writeln(’Introduce the vector of ’,N,’ elements, splitted by blank spaces.’);for i:=1 to N dobegin

read(A[i]);end;

(* Accumulating *)B[1]:=A[1];for i:=2 to N doB[i]:=B[i-1]+A[i];

(* Accumulating *)write(’The values in the vector are: ’);for i:=1 to N dowrite(B[i],’ ’);

end.

Exercise 4.7. Create a program that reads a vector A of N reals (being N a constant), and createsa new vector so that at every position i it contains the sum of the values of A in the positionsi − 2, i − 1 and i.

�This problem is similar to the previous, but the solution cannot be as elegant as that in

Program 84. The reason is that different positions of B, more specifically the first 3, cannot befilled in using the general schema, because for such positions there are not enough values on theleft. Still, the general solution for the problem resembles that in the previous exercise, exceptionmade that we need to remove one of the values from the count in B[i-1], since the value in theposition i-3 should not be taken into account in the sum for a given B[i].

Program 85: Exercise 4.7

program c04e07;const

N=10;type

intVector=ARRAY[1..N] OF integer;var

i:integer;A,B:intVector;

begin(* Reading *)writeln(’Introduce the vector of ’,N,’ elements, splitted by blank spaces.’);for i:=1 to N do

read(A[i]);(* Accumulating *)B[1]:=A[1];(* Initial values *)for i:=2 to 3 do

73

Page 75: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

B[i]:=B[i-1]+A[i];(* General schema and, then, accumulation *)for i:=4 to N doB[i]:=B[i-1]-A[i-3]+A[i];

write(’The values in the vector are: ’);for i:=1 to N dowrite(B[i],’ ’);

end.

Exercise 4.8. Create a program that reads a vector of N integers (being N a constant), then findsthe last negative number.

�The previous exercises had something in common: we needed an exhaustive examination of

the array in order to obtain the results. That is, all the elements of the array had to be checkedto be sure about the exactitude of the exercise. In such cases, the for iterative structure is themost convenient option, since we can use the own counting variable as index for accessing allthe positions of the array. However, in this exercise we don’t have to examine all the elementsin the array, but to stop when we find the last (first starting by the end) negative instead. Thewhile iterative structure seems now more appropriate. Note that we need to update the valueof i at each iteration.

There are two different reasons why the iteration could stop. The first one is that myVector[i]is a negative integer. In that case, i is greater than 0, and we can state that the program foundthe last negative number in the array. Alternatively, it could be that there is no negatives inthe array. In that case, the program would iterate until i becomes 0. Then, the first conditionof the while would become false, and the program would stop iterating. Hence, it is clear thatthe value of i after exiting the while is the indicator we need to know which of the previousscenarios happened.

Program 86: Exercise 4.8

program c04e08;const

N=10;type

intVector=ARRAY[1..N] OF integer;var

i:integer;myVector:intVector;

begin(* Reading *)writeln(’Introduce the vector of ’,N,’ elements, splitted by blank spaces.’);for i:=1 to N doread(myVector[i]);

(* Seeking the last negative *)i:=N;while (i>=1) and (myVector[i]>=0) do

i:=i-1;(* Checking out what happened at the loop *)if (i>=1) thenwriteln(’The last negative is ’,myVector[i],’, in pos ’,i,’.’)

elsewriteln(’There are no negatives in the vector’)

end.

74

Page 76: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Data structures

Exercise 4.9. Create a program that reads a vector of N integers (being N a constant), then findsthe first negative number after a positive number.

�The previous exercise is the classical example of search exercise. This one goes one step

further, since we need to perform a double search. First, we need to find the first position ofthe array containing a positive number. Then, from that position on, we need to find the firstnegative.

The first part of the program is very similar to the one in the exercise before. In the second,we have to proceed for searching for a negative number. Note that there might be no positivesin the array, so we have to include an if statement to display the corresponding result.

Program 87: Exercise 4.9

program c04e09;const

N=10;type

intVector=ARRAY[1..N] OF integer;var

i:integer;myVector:intVector;

begin(* Reading the vector *)writeln(’Introduce the vector of ’,N,’ elements, splitted by blanks.’);for i:=1 to N do

read(myVector[i]);(* Go over positions as long as you find negatives *)i:=1;while (i<=N) and (myVector[i]<0) do

i:=i+1;(* Checking what happened when seeking a positive *)if (i>N) then

writeln(’There are no positives in the vector’)else

begin(* Now we know that the first positive is at pos i *)(* We find the first (following) negative *)while (i<=N) and (myVector[i]>=0) do

i:=i+1;if (i>N) then

writeln(’There are no negatives after the first positive.’)else

writeln(’The first negative after one positive is ’,myVector[i],’, in pos’,i,’.’)

endend.

Exercise 4.10. Create a program that reads a vector of N integers (being N a constant), then findsthe last positive number before the first negative one.

�This program is very similar to the previous. Indeed, most of the searching algorithms

are very similar to each other, holding a similar structure, which can be broken down into thefollowing:

• Initializing the pointing variable.

75

Page 77: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

• Iterating in the search of the position. In this loop the pointing variable must be evolved.The condition for keeping on iterating is always composed of two facts: (a) the pointingvariable is in the range and (b) the fact we look for does not occur.

• Discriminating the potential outcomes of the iteration by checking the value of the pointingvariable.

Program 88: Exercise 4.10

program c04e10;const

N=10;type

intVector=ARRAY[1..N] OF integer;var

i:integer;myVector:intVector;

begin(* Reading the vector *)writeln(’Introduce the vector of ’,N,’ elements, splitted by blanks.’);for i:=1 to N do

read(myVector[i]);(* Checking the first position *)if (myVector[1]<0) then

writeln(’The first value is already a negative’)else

begin(* Go over the positives *)i:=2;while (i<=N) and (myVector[i]>=0) do

i:=i+1;(* Checking the result after the search *)if (i>N) then

writeln(’There are no negatives after the positives.’)else

writeln(’The last positive before the first negative is ’,myVector[i-1],’,at pos ’,i-1,’.’)

endend.

Exercise 4.11. Create a program that reads a matrix of N×M integers (being N and M constants)and finds the first negative number. In this exercise, consider that any position in a given row i,precedes those positions in any other row j > i.

�In this exercise the novelty lies on the fact that we use a double pointing variable, i for the

columns and j for the rows. Obviously, we need to coordinate the increase of both in ordersuccessfully explore the positions of the array.

Program 89: Exercise 4.11

program c04e11;const

N=3;M=2;

typeintMatrix=ARRAY[1..N,1..M] OF integer;

76

Page 78: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Data structures

vari,j:integer;matA:intMatrix;

begin(* Reading the matrix *)writeln(’Introduce the matrix.’);for i:=1 to N dofor j:=1 to M dobegin

write(’Introduce the value at row ’,i,’ and col ’,j,’: ’);read(matA[i][j])

end;(* Perform the search *)i:=1;j:=1;while ( (i<=N) and (j<=M) and (matA[i][j]>=0)) do

begini:=i+1;if (i>N) then (* This means that a new line has to be analyzed *)

beginj:=j+1;i:=i+1

endend;

(* Checking out the result *)if (i<=N) thenwriteln(’The first negative is ’,matA[i][j],’.’)

elsewriteln(’There are no negatives.’)

end.

Exercise 4.12. Create a program that reads a matrix of N ×N integers (being N a constant). Theuser then inputs a number a in {1, . . . ,N} and the program must compute the sum of the elementsplaced in either row i or column a.

�This problem reduces to counting in a for loop the values at a incresing position of the a-th

row and column. Note that we need to remove the value at row a and column a, since we countit twice in the loop.

Program 90: Exercise 4.12

program c04e12;const

N=3;type

intMatrix=ARRAY[1..N,1..N] OF integer;var

i,j,a,sum:integer;matA:intMatrix;

begin(* Reading the matrix *)writeln(’Introduce the matrix.’);for i:=1 to N dofor j:=1 to N dobegin

write(’Introduce the value at row ’,i,’ and col ’,j,’: ’);read(matA[i][j])

end;

77

Page 79: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

(* Ask the user *)write(’Introduce the number a: ’);readln(a);(* Count *)sum:=0;for i:=1 to N dosum:=sum+matA[i][a]+matA[a][i];

sum:=sum-matA[a][a];(* Display *)writeln(’The final value is ’,sum,’.’)

end.

Exercise 4.13. Create a program that reads a matrix of N ×N integers (being N a constant), thenfinds the greater sum of the elements of a row or column.

�In this exercise we need to sum the elements of each row and column. Then, we have to find

out which one produces the greater sum. Conceptually, it is very similar to the Exercise 4.4 inwhich we had to find the greatest element of a table. In fact, we also have to address the problemof setting maxSum to some initial value.

Program 91: Exercise 4.13

program c04e13;const

N=3;M=5;

typeintMatrix=ARRAY[1..N,1..M] OF integer;

vari,j:integer;matA:intMatrix;maxSum,currentSum:integer;

begin(* Reading the matrix *)writeln(’Introduce the matrix.’);for i:=1 to N dobegin

writeln(’Introduce the row ’,i,’: ’);for j:=1 to M doread(matA[i][j])

end;(* Initialize the variable *)maxSum:=-32000;(* Checking rows *)for i:=1 to N dobegincurrentSum:=0;for j:=1 to M do

currentSum:=currentSum+matA[i][j];if (currentSum>maxSum) then

maxSum:=currentSumend;

(* Checking colums *)for j:=1 to M dobegincurrentSum:=0;for i:=1 to N do

currentSum:=currentSum+matA[i][j];

78

Page 80: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Data structures

if (currentSum>maxSum) thenmaxSum:=currentSum

end;(* Displaying the result *)writeln(’The max such is is ’,maxSum,’.’)

end.

Exercise 4.14. Create a program that reads a vector of N integers (being N a constant) and sortsthem in increasing order.

�Sorting an array is a classical problem in basic algorithmics. Some decades ago, it was deeply

studied, and very efficient methods appeared (e.g. mergesort or quicksort). In this exercise wewill use the simplest of the approaches to the problem. In short, for each position i we findthe smallest value in the range [i..N]. Hence, at each position i we leave the smallest value ofthose that haven’t been sorted yet. Note some facts:

• For any i, the positions on the left are already sorted in increasing order. Moreover, theycontain the i-1 smallest values in the table.

• The last position for which we have to repeat the operation is N-1, since the last position(N) holds by the the greatest element in N.

Program 92: Exercise 4.14

program c04e14;const

N=10;var

vec:ARRAY[1..N] of integer;i,j,aux:integer;

begin(* Reading the vector *)writeln(’Please introduce the ’,N,’ elements.’);for i:=1 to N doread(vec[i]);

(* Sorting the vector *)for i:=1 to N-1 dofor j:=i+1 to N do(* Checking wether the value at j is greater... *)(* ... than the one at i *)if (vec[i]>vec[j]) then

beginaux:=vec[i];vec[i]:=vec[j];vec[j]:=aux

end;(* Displaying the vector *)writeln(’The final vector is: ’);for i:=1 to N dowrite(’ ’,vec[i],’ ’)

end.

79

Page 81: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

Exercise 4.15. Create a program that reads a vector of N integers (being N a constant) andthen reconstructs it so that all the even numbers are placed before the odd ones. Do not use asecondary vector in this exercise.

�This problem is considerably more tricky than the previous, and demand an slightly more

intelligent approach. Our idea is to push behind every odd number in the table, until no oddintegers appear before the last even one. In order to do so, we go over the positions in the arrayand, in case we come across an odd integer, we swap it by the next following even number.Eventually, there might be no even integers on the right side of that position, so that we don’tneed to proceed for the swap. Two different situations might happen preventing us from stayingin the iteration:

• If i has the value N-1, we reached the end of the array.

• If the value at the position i is odd, it means that all the values on the right are also odd(otherwise we would have swapped). Hence, the array is sorted as demanded.

Program 93: Exercise 4.15

program c04e15;const

N=10;var

vec:ARRAY[1..N] of integer;i,j:integer;aux:integer;

begin(* Reading the vector *)writeln(’Please introduce the ’,N,’ elements.’);for i:=1 to N doread(vec[i]);

(* Find the position *)i:=0;repeat

i:=i+1;if (vec[i] mod 2 = 1) then

begin(* Find the first to swap *)j:=i;while ((j<=N) and (vec[j] mod 2 = 1)) doj:=j+1;

if (j<=N) thenbegin(* swap *)aux:=vec[j];vec[j]:=vec[i];vec[i]:=aux

end(* Else they are all odds *)

end;until (i>=N-1) or (vec[i] mod 2 = 1);(* Displaying the vector *)writeln(’The second vector is: ’);for i:=1 to N dowrite(’ ’,vec[i],’ ’);

end.

80

Page 82: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Data structures

Exercise 4.16. Create a string that reads a real number as text (in a string) and stores the value itrepresents in a real variable. Note that the text must represent a valid real number with at leastone digit and one or no dots to separate the integer- and real-valued part.

The easiest solution to this problem is based on finding the position at which the dot (ifany) appears. Hence, the first part of the program features a while-based search Because ofthe configuration of the subsequent for loops, if no dot was found (i.e. if posDot>length(a))the first for traverses the whole string, and the second is never executed. The use of twodifferent variables for the real and integer parts, plus a third one for the final result is not strictlymandatory, but enhances the overall comprehensibility of the program.

Program 94: Exercise 4.16 (Version A)

program c04e16;const

N=10;var

a:STRING[N];realPart,intPart,r:real;i,posDot:integer;

begin(* Reading *)write(’Introduce the real number: ’);readln(a);(* Looking for the dot *)posDot:=1;while( (posDot<=length(a)) and (a[posDot]<>’.’) ) do

posDot:=posDot+1;(* Computing the integer part*)intPart:=0;for i:=1 to posDot-1 dointPart:=(intPart*10)+(ord(a[i])-ord(’0’));

(*Computing the real part *)realPart:=0;for i:=length(a) downto posDot+1 do

realPart:=(realPart/10)+(ord(a[i])-ord(’0’))/10;(* Final *)r:=intPart+realPart;writeln(’The final result is ’,r:4:4,’.’);

end.

A more compact solution ignores the explicit search for the dot, but still makes use of twoiterations to go over the real and integer parts.

Program 95: Exercise 4.16 (Version B)

program c04e16;const

N=10;var

a:STRING[N];r,quotient:real;i:integer;

begin(* Reading *)write(’Introduce the real number: ’);readln(a);(* Computing the integer part*)i:=1;r:=0;

81

Page 83: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

while( (i<=length(a)) and (a[i]<>’.’) ) dobegin

r:=(r*10)+(ord(a[i])-ord(’0’));i:=i+1

end;i:=i+1;(*Computing the real part, if any *)quotient:=0.1;while (i<=length(a)) dobegin

r:=r+quotient*(ord(a[i])-ord(’0’));quotient:=quotient/10;i:=i+1;

end;(* Final *)writeln(’The final result is ’,r:4:4,’.’)

end.

4.3.2 Working with strings

Exercise 4.17. Create a program that reads a string of up to N position (being N a constant) anddisplay its contents and length. Then, it displays the concatenation of the word with itself.

�As explained earlier in this chapter, managing text is slightly different than managing any

other type of information, since Pascal offers some extra functionalities for this kind of data.If using the type string (instead of ARRAY of char) there is no need to read all the elementsone by one using an iterative construction. Note that the length of the word, as extracted usinglength(w) is not the maximal length of the word, but the number of chars stored in it. Notealso that if the user inputs more than N characters before pressing enter, only the first N will besaved, being all the others discarded.

Program 96: Exercise 4.17 (version A)

program c04e17;const

N=10;type

nPosWord=STRING[N];var

w:nPosWord;begin

write(’Please introduce a sentence of up to ’,N,’ positions: ’);readln(w);writeln(’The sentence is [’,w,’], and has length ’,length(w),’.’);writeln(’The concatenation with itself is [’,w,w,’].’)

end.

There is a more elegant way of dealing with text concatenation, which is the function concat.The execution of the following code looks like the same as the one before, but has an slightlyincreased readability.

82

Page 84: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Data structures

Program 97: Exercise 4.17 (version B)

program c04e17;const

N=10;type

nPosWord=STRING[N];var

w:nPosWord;begin

write(’Please introduce a sentence of up to ’,N,’ positions: ’);readln(w);writeln(’The sentence is [’,w,’], and has length ’,length(w),’.’);writeln(’The concatenation with itself is [’,concat(w,w),’].’)

end.

Exercise 4.18. Create a program that reads a string and checks whether it is symmetric or not.

�Checking whether an array (in this case, a string) is symmetric restricts to finding a position

i so that the mirror position (N− i + 1, being N the length of the array) contains a different value.If such position exists, then the array is asymmetric. Otherwise, it is symmetric. Hence, theproblem is in fact a search problem, exactly as the previous ones.

In this solution we only need to compare each of the chars of the string with its mirroringelement. If the string is symmetric, the iteration will only stop when i>length(str). Note thatwe use length(str) instead of N, since that gives us the real length of the sentence.

Program 98: Exercise 4.18 (version A)

program c04e18;const

N=15;var

str:STRING[N];i:integer;

begin(* Reading *)write(’Please introduce the string: ’);readln(str);(* Checking *)i:=1;while ((i<=length(str)) and (str[i]=str[length(str)-i+1])) do

i:=i+1;(* Displaying *)if (i>length(str)) thenwriteln(’The word is symmetric’)

elsewriteln(’The word is not symmetric’)

end.

The previous solution is inefficient, for it compares every pair of characters twice. Forexample, in the first iteration the first and last positions are compared to each other, exactly thesame as in the last iteration. We only have to iterate over the first half of the elements, and hencethe pointing variable must only reach the middle of the string.

83

Page 85: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

Program 99: Exercise 4.18 (version B)

program c04e18;uses math;const

N=15;var

str:STRING[N];i:integer;

begin(* Reading *)write(’Please introduce the string: ’);readln(str);(* Checking *)i:=1;while ((i<=floor(length(str)/2)) and (str[i]=str[length(str)-i+1])) doi:=i+1;

(* Displaying *)if (i>floor(length(str)/2)) thenwriteln(’The word is symmetric’)

elsewriteln(’The word is not symmetric’)

end.

Exercise 4.19. Create a program that reads a string and reports the number of occurrences ofeach letter. The case of the characters is irrelevant, but those characters not appearing in thestring must not be displayed in the report.

�To solve this problem we need a so-called counting table. A counting table is an 1D array of

integers so that it contains at position i-th the number of appearances of the i-th character of thealphabet. In our exercise we will name this variable counter, and will have 26 positions, sincethat is the number of elements in the considered alphabet.

First, we need to initialize the counter setting all its positions to 0. Very ofter this is done bydefault by the compiler or the memory management system, but it is not a good practice to leave(and use) the default values. Second, we have to go over the string annotating the appearanceof each char. In order to do so we first compute the position of the character with respect to thecharacter ’A’ in the ASCII table, which we denote positionInTable. If that value is between 1and NUMLETTERS, it must be a character in the alphabet, and must be accounted for in counter.Notice that in the computation of positionInTable we use the function upcase, so that weavoid double-checking for upper and lower case letters. Finally, in the displaying of the numberof occurrences of each letter we must avoid those not appearing in the string, that is those whichcorresponding position in counter contains the value 0.

Program 100: Exercise 4.19

program c04e19;const

N=30;NUMLETTERS=26;

varstr:STRING[N];counter:ARRAY[1..NUMLETTERS] of integer;i,positionInTable:integer;

begin(* Read the text *)

84

Page 86: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Data structures

writeln(’Please introduce the word: ’);readln(str);(* Initialize the counters *)for i:=1 to NUMLETTERS docounter[i]:=0;

(* Start counting up *)for i:=1 to length(str) dobegin

positionInTable:=ord(upcase(str[i]))-ord(’A’)+1;if ( (1<=positionInTable) and (positionInTable<=NUMLETTERS)) then

counter[positionInTable]:=counter[positionInTable]+1end;

(* Displaying *)for i:=1 to NUMLETTERS doif (counter[i]>0) then

writeln(’The letter ’, chr(ord(’A’)+i-1) ,’ appears ’,counter[i],’ times.’);

end.

Exercise 4.20. Create a program that reads a vector of N integers (being N a constant) and thencreates another one with the same values, but having all the even numbers before the odd ones.

�This problem is solved by using a non-linear filling of the second vector, which we refer to as

vecB. More specifically, we use a double pointer, so that the first (posEven) points to the positionat which the next even in vecA has to be placed, while the second (posOdd) points to the positionat which the next odd has to be. Everytime a new even is added at the position posEven, thepointer is increased by one unit. Alternatively, if we add an odd number at position posOdd,the pointer us decreased. In this way, we fill vecB with the values in vecA, having that the evennumbers go to the left side and the odd ones go to the right one.

Program 101: Exercise 4.20

program c04e20;const

N=10;var

vecA,vecB:ARRAY[1..N] of integer;i,posEvens,posOdds:integer;

begin(* Reading the vector *)writeln(’Please introduce the ’,N,’ elements.’);for i:=1 to N doread(vecA[i]);

(* Fill the second one *)posEvens:=1;posOdds:=N;for i:=1 to N doif (vecA[i] mod 2 =0) then

beginvecB[posEvens]:=vecA[i];posEvens:=posEvens+1

endelse

beginvecB[posOdds]:=vecA[i];posOdds:=posOdds-1

end;

85

Page 87: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

(* Displaying the vector *)writeln(’The second vector is: ’);for i:=1 to N dowrite(’ ’,vecB[i],’ ’)

end.

4.3.3 On-screen matrix displaying

Exercise 4.21. Create a program that reads a string and draws it diagonally. For example, theword computer must look like:

co

mp

ut

er

�The key question in this kind of exercises is understanding (and being able to write code for)

what has to be displayed at each line. Consequently, this program is rather simple, since it isclear that at each line i we need to print the i-th character of the string after i − 1 blank spaces.Note that the letters are displayed using the command writeln, in order to prompt to jump tothe next line. In this way, the blank spaces on the right of the characters are not written.

Program 102: Exercise 4.21

program c04e21;const

N=15;var

str:STRING[N];i,j:integer;

begin(* Reading the text *)write(’Please input the string of, at most, ’,N,’ chars: ’);readln(str);(* Writing the matrix *)for i:=1 to length(str) dobegin

for j:=1 to i-1 dowrite(’ ’);

writeln(str[i])end

end.

86

Page 88: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Data structures

Exercise 4.22. Create a program that reads a string and draws it as a left-based pyramid. Forexample, the word computer must look like:

co

mpu

te

r

�This program consists of writing, at line i, the i-th char of the string preceded by a given

number of blank spaces. The key is being able to summarize such number in a single formula, sothat the program becomes readable. In this case, such formula is min(i-1,length(str)-1. Notethat by finding out the expression we avoid using extra alternative constructions to discriminatebetween the first and the last half of the string.

Program 103: Exercise 4.22

program c04e22;uses math;const

N=15;var

str:STRING[N];i,j:integer;

begin(* Reading the text *)write(’Please input the string of, at most, ’,N,’ chars: ’);readln(str);(* Writing the matrix *)for i:=1 to length(str) dobegin

for j:=1 to min(i-1,length(str)-i) dowrite(’ ’);

writeln(str[i])end

end.

Exercise 4.23. Create a program that reads a string and draws it as an upside down pyramid.For example, the word computer must look like:

c ro e

m tp u

�In order to display this structure we have to realize that, between each pair of chars, we need

to put blank spaces. Hence, again it becomes a problem of epitomizing the number of blankspaces depending upon the number of the row we are in. First, we have to decide how manyblank spaces must be written before the first char, and then how many before the second. On

87

Page 89: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

the leftmost part of the i-th line we have to include as many as i − 1 blank spaces. Then, afterthe first char we have to write as many black spaces as the length of the line minus 2 (the spaceoccupied by the chars) and 2 · (i − 1) (the number of blanks paces on the left and right of suchchars). Hence, for a line i we need length(str) − 2 ∗ i blank spaces.

Program 104: Exercise 4.23

program c04e23;uses math;const

N=15;var

str:STRING[N];i,j:integer;

begin(* Reading the string *)write(’Please input the string of, at most, ’,N,’ chars: ’);readln(str);(* Writing the matrix *)for i:=1 to ceil(length(str)/2) dobegin

for j:=1 to min(i-1,length(str)-i) dowrite(’ ’);

write(str[i]);for j:=1 to length(str)-(2*i) do

write(’ ’);if (abs( (i-1)-(length(str)-i))-1)>=0 thenwriteln(str[length(str)-i+1])

elsewriteln

endend.

Exercise 4.24. Create a program that reads a string and draws it as a bottom-based pyramid.For example, the word computer must look like:

p um t

o ec r

�We can understand this problem as a derivation of the preceding one. Indeed, we can achieve

the solution by tweaking the value of the variable used in the outer for iterative construction,and changing the to clause by downto.

Program 105: Exercise 4.24

program c04e24;uses math;const

N=15;var

str:STRING[N];i,j:integer;

begin(* Reading the string *)

88

Page 90: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

Data structures

write(’Please input the string of, at most, ’,N,’ chars: ’);readln(str);(* Writing the matrix *)for i:=ceil(length(str)/2) downto 1 do

begin(* Write the leftmost blank spaces + first char *)for j:=1 to min(i-1,length(str)-i) do

write(’ ’);write(str[i]);(* Write the middle *)for j:=1 to abs( (i-1)-(length(str)-i))-1 do

write(’ ’);(* Depending on the length, and whether its even or odds, last row *)(* might have one single char *)if (abs( (i-1)-(length(str)-i))-1)>=0 then

writeln(str[length(str)-i+1])else

writelnend

end.

Exercise 4.25. Create a program that reads a string and draws it twice with cross diagonals. Forexample, the word computer must look like:

c co o

m mp pu u

t te e

r r

�This exercise is tackled here as a combination of the previous two. Note that, in order

to produce a more compact solution, we write everything inside the same for. Hence, somesmall changes have to be performed in the definition of the limits of each of the for iterativeconstructions.

Program 106: Exercise 4.25

program c04e25;uses math;const

N=15;var

str:STRING[N];i,j:integer;

begin(* Reading the text *)write(’Please input the string of, at most, ’,N,’ chars: ’);readln(str);(* Writing the matrix *)for i:=1 to length(str) dobegin

for j:=1 to min(i-1,length(str)-i) dowrite(’ ’);

89

Page 91: A practical introduction to Pascal programming languagegiara.unavarra.es/pdfs/APITPPL.pdf · A practical introduction to Pascal programming language Carlos Lopez-Molina Humberto Bustince

A Practical Introduction to Pascal Programming Language

write(str[i]);

for j:=1 to abs((i-1)-(length(str)-i))-1 dowrite(’ ’);

if (abs((i-1)-(length(str)-i))-1>=1) thenwriteln(str[i])

elsewriteln

endend.

90