13.07.2015 Views

A practical introduction to Pascal programming language - GIARA

A practical introduction to Pascal programming language - GIARA

A practical introduction to Pascal programming language - GIARA

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming LanguageC. Lopez-Molina, H. Bustince, J. Fernández○CCThe authorsISBN-10: 84-695-7278-4ISBN-13: 978-84-695-7278-8Front illustration: Manche Menschen ändern sich nie○CCC. Lopez-MolinaPamplona, March 2013


This book is distributed under the licenseCreative Commonts Attribution-NonCommercial-ShareAlike 3.0 Unported(CC BY-NC-SA 3.0)You are free:• To share: <strong>to</strong> copy, distribute and transmit the work, and• To remix: <strong>to</strong> 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 <strong>to</strong>this one.With the understanding that:• Waiver- Any of the above conditions can be waived if you get permission from the copyrightholder.• 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 <strong>to</strong> others the license terms ofthis work. The best way <strong>to</strong> do this is with the link below.For more information, visit: http://creativecommons.org/licenses/by-nc-sa/3.0/


ContentsIntroduction <strong>to</strong> this book 9Aims and scopes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Guidelines and structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 Basic read/write operations 111.1 Contents of this chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111.2 Brief review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121.3.1 Basic input and output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121.3.2 Using functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152 Alternative constructions 192.1 Contents of this chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192.2 Brief review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223 Iterative constructions 353.1 Contents of this chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353.2 Brief review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353.3 On the selection of an iterative structure . . . . . . . . . . . . . . . . . . . . . . . . 373.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383.4.1 Iterative processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383.4.2 Computing with sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . 453.4.3 On-screen matrix displaying . . . . . . . . . . . . . . . . . . . . . . . . . . 614 Data structures 654.1 Contents of this chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 654.2 Brief review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 654.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 674.3.1 Working with arrays and matrices . . . . . . . . . . . . . . . . . . . . . . . 674.3.2 Working with strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 824.3.3 On-screen matrix displaying . . . . . . . . . . . . . . . . . . . . . . . . . . 867


Introduction <strong>to</strong> this bookThe first contacts with <strong>programming</strong> <strong>language</strong>s are never easy, specially for first-year students,which haven’t developed structured mathematical routines. Hence, they have frequent troubles<strong>to</strong> understand what is going on in a program and why do things happen. Although the bestway of dealing with such symp<strong>to</strong>ms is personal work, the instruc<strong>to</strong>rs usually find themselvesproviding the students with a large number of solved examples than might enhance the comprehensionof the students. This task is tedious and time-consuming. Moreover, the instruc<strong>to</strong>rfrequently has problems <strong>to</strong> find exercises and examples which are rich and diverse enough <strong>to</strong>shed light on all the aspects of the <strong>programming</strong> <strong>language</strong>. As a consequence of all the previousinstruc<strong>to</strong>rs devote, year after year, a large amount of time <strong>to</strong> prepare sets of solved exercises.Since this is our experience, we have decided <strong>to</strong> create a book which can be used <strong>to</strong> complementan introduc<strong>to</strong>ry course <strong>to</strong> <strong>programming</strong>. That is, a book the students can use a support fortesting their knowledge, but also for getting more used <strong>to</strong> read and develope code.For a long time, students in our University have used <strong>Pascal</strong> in basic <strong>programming</strong> courses.The reasons are diverse, but ground mostly on the fact that the <strong>language</strong> has tight grammarand also that higher-level aspects, such as memory management, are simplified. Althoughits applicability <strong>to</strong> professional environments is much lower than that of other <strong>programming</strong><strong>language</strong>s, we believe that <strong>Pascal</strong> is very suitable for learning good <strong>programming</strong> practices.Indeed, from our experience we can state that acquiring the fundamentals on <strong>programming</strong><strong>language</strong>s is much easier with <strong>Pascal</strong> than with any other <strong>language</strong>. Hence, we consider worthusing this <strong>language</strong> the first and second semester of their higher education, despite it is neverused again in subsequent years.Aims and scopesThis book aims at providing both the instruc<strong>to</strong>r and the studentsg a large collection of exercises<strong>to</strong> fulfill the following goals:• Alleviating the workload of the instruc<strong>to</strong>r by proving him with a large set of exampleexercises.• Allowing the student <strong>to</strong> become familiar with <strong>Pascal</strong> by accessing a large number ofprograms.• Illustrating the student with a large number of examples of well-written code, in whichgood <strong>programming</strong> and coding practices are considered.9


Guidelines and structureThis book is divided in<strong>to</strong> four units, according <strong>to</strong> the structure we have followed in the pastacademic years. Each one covers a specific aspect of the <strong>programming</strong> <strong>language</strong>, so that thestudent acquires the knowledge in an incremental way. The four units the book is broken downin<strong>to</strong> are:• Basic read/write operations;• Alternative structures;• Iterative structures;• Advanced data structures.Each of the units is subsequently divided in<strong>to</strong> more specific goals, as explained at the beginningof each of the chapters. Note that this book is not intended <strong>to</strong> be used for theoreticalteaching, but <strong>to</strong> support the theoretical contents instead. Hence, despite a brief theoretical <strong>introduction</strong>is included at the beginning of each unit, our intention is <strong>to</strong> 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 <strong>to</strong> readthe whole book, since the list of exercises is intented <strong>to</strong> have some sense of linearity. Otherwise,students might get lost in references <strong>to</strong> previous exercises or explanations. At the end of thebook, the student is expected <strong>to</strong> understanding structured programs, as well as of implementingmost of the algorithms required for mid-level courses.


Chapter 1Basic read/write operations1.1 Contents of this chapterThis chapter covers the instructions used <strong>to</strong> 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 <strong>programming</strong> framework.1.2 Brief reviewThis section cover the most basic read/write operations. There are two operations we can use <strong>to</strong>write 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 <strong>to</strong> be displayed by write/writeln can be performed in differentways. These are the options:• Simple static text between simple quotations.writeln(’computer’).Some examples are write(’hello’) or• Concatenation of static texts. To do so, we only have <strong>to</strong> 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 example,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(’211


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming LanguageFunction Usage Input OutputAbsolute value abs(x) Int Same as inputSquared value sqr(x) Int./Real Same as inputSquared root sqrt(x) Int./Real Same as inputTrigonometric Sine sin(x) Int./Real RealTrigonometric Cosine cos(x) Int./Real RealNatural logarithm ln(x) Int./Real Reale-power exp(x) Int./Real RealTruncated value trunc(x) Real Int.Rounded value round(x) Real Int.Fractionary part frac(x) Real RealReal part int(x) Real RealTable 1.1: Some of the most important functions in <strong>Pascal</strong>, <strong>to</strong>gether 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 au<strong>to</strong>maticallyconvert it <strong>to</strong> 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 <strong>to</strong> input information on the command line and s<strong>to</strong>res it in thevariable a. readln(a) - Waits for the user <strong>to</strong> input information and press enter on the command line.Then, it s<strong>to</strong>res all the information the user typed in the variable a.After the execution of any of such functions, the value of the variable put in<strong>to</strong> parenthesis isthe one the user input. In case the contents input by the user cannot be appropriately converted<strong>to</strong> the type of the variable, an error is raised, and the execution of the program is aborted.Apart from the read/write operations, <strong>Pascal</strong> 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 <strong>to</strong>gether 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 opera<strong>to</strong>rs.1.3 Exercises1.3.1 Basic input and outputExercise 1.1. Write a program that reads an integer from the keyboard and shows it <strong>to</strong> the user.□For doing this exercise we only need <strong>to</strong> declare one variable, which is read and displayedusing two different operations. Note that, by using readln, we save in<strong>to</strong> int all the digits typedby the user before an enter, not only the first one.12


Basic read/write operationsProgram 1: Exercise 1.1program c01e01;varint:integer;beginwrite(’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 onscreen.□This program is very similar <strong>to</strong> the previous, except for the fact that we now need twovariables instead of one.Program 2: Exercise 1.2program c01e02;varfirstChar,secondChar:char;beginwrite(’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 <strong>to</strong> the user using one single line of code.□Now the only difference with respect <strong>to</strong> the previous is the number of variables we need andtheir type.Program 3: Exercise 1.3program c01e03;varint: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


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming LanguageExercise 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 <strong>to</strong> create a new variable <strong>to</strong> s<strong>to</strong>re the result, since we can perform the mathematical operation(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 <strong>to</strong> adjust how the result is displayed, we force the program <strong>to</strong> display at most 5 digits onthe integer part and 4 in the non-integer one.Program 4: Exercise 1.4program c01e04;varfirstReal,secondReal:real;beginwrite(’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 <strong>to</strong> temporarily s<strong>to</strong>re the value of one of thevariables. Notice how the variable aux must be used at the beginning of the swapping operation<strong>to</strong> s<strong>to</strong>re the value of one of the integers (firstInt), then at the end <strong>to</strong> res<strong>to</strong>re such value <strong>to</strong> theother one (secondInt).Program 5: Exercise 1.5program c01e05;varfirstInt,secondInt,aux:integer;beginwrite(’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


Basic read/write operations1.3.2 Using functionsExercise 1.6. Write a program that reads an integer from the keyboard and displays its absolutevalue.□The easiest option <strong>to</strong> complete this exercise is using the abs function, that takes as singleargument 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;vari:integer;beginwrite(’Please type an integer number and press enter: ’);readln(i);writeln(’Its absolute value is: ’,abs(i),’.’)endIn case we do not want <strong>to</strong> use such function, alternative options include the use of squareroots. In the following program we employ sqrt(x*x), which is equivalent <strong>to</strong> 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;varr:integer;beginwrite(’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 <strong>to</strong> obtain that information is using the functions provided by <strong>Pascal</strong>: sin(x)and cos(x).Program 8: Exercise 1.7program c01e07;varr:real;beginwrite(’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


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming LanguageExercise 1.8. Write a program that reads a real and displays separately its integer and real parts.□There are different ways <strong>to</strong> do so. The simplest one is employing the functions int(x) andfrac(x), where x is a real number.Program 9: Exercise 1.8 (Version A)program c01e08;varr:real;beginwrite(’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),’.’)endIf 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;varr:real;beginwrite(’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 functionthat takes as argument a real and produces an integer number.Program 11: Exercise 1.9program c01e09;varfirstReal,secondReal:real;beginwrite(’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


Basic read/write operationsExercise 1.10. Write a program that reads a char and displays its upper case version.□For converting any character <strong>to</strong> upper case, we can use the function upcase(x), where xmust 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.10program c01e10;varc:real;beginwrite(’Please type a char and press enter: ’);readln(c);writeln(’The char is: ’,c,’, and its upper case version: ’,upcase(c),’.’)end17


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming Language18


Chapter 2Alternative constructions2.1 Contents of this chapterThis 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 reviewSequential programs are <strong>to</strong>o simple <strong>to</strong> solve most of the problems in real world computing. Veryoften, we need a program <strong>to</strong> act in different ways depending upon the values it is working with.Since this book is addressed <strong>to</strong> 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 <strong>to</strong> 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 <strong>to</strong> be used. Hence, in some sense,they allow dynamic selection of the instructions <strong>to</strong> 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 <strong>to</strong>solve in an elegant way scenarios in which a large number of options are available.The if-then-else structures enables the program <strong>to</strong> take a boolean decision on the executionof some instructions. That is, they capacitate the program <strong>to</strong> decide whether some code has <strong>to</strong>be executed or not. In order <strong>to</strong> 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 <strong>to</strong> be executed in case the program determined that the first block ofcode was not <strong>to</strong> be executed.The semantics of the structure, <strong>to</strong>gether 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 <strong>to</strong> execute (or not) the19


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming Language...[Precedent code]if (Boolean condition) thenInstruction Block[Following code]...[Precedent code]❄Boolean conditiontrue❄Instruction block✛❄[Following code]false...[Precedent code]if (Boolean condition) thenInstruction Block AelseInstruction Block B[Following code]...(a) If-then clausetrue❄Instruction block A[Precedent code]❄Boolean condition❄[Following code]false❄Instruction block B(b) If-then-else clauseFigure 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 thenclauses. The if-then-else works exactly as the if-then one, exception made that it demandsan alternative instruction block <strong>to</strong> be executed in case the boolean condition was evaluated asfalse.Eventually, a program has more than 2 alternatives <strong>to</strong> decide what code it must execute.The case-of structure is a commodity designed <strong>to</strong> simplify such situations. In order <strong>to</strong> 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, <strong>to</strong>gether 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 <strong>to</strong> include certain instructions <strong>to</strong> 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


Alternative constructions...[Precedent code]case ( int or char expression ) ofvalue1 :Instruction Block 1value2 :Instruction Block 2...valueN :Instruction Block Nend[Following code]......[Precedent code]case ( int or char expression ) ofvalue1 :Instruction Block 1value2 :Instruction Block 2...valueN :Instruction Block NelseInstruction Block Xend[Following code]...[Precedent code]❄Computing expression=value1=value2=valueN✛❄[Following code](a) Case-of clause[Precedent code]❄Computing expression✲✲✲Instruction Block 1Instruction Block 2 =value1=value2=valueN❄[Following code]✲✲✲✲Instruction Block NInstruction Block 1Instruction Block 2 Instruction Block NInstruction Block X(b) Case-of clause with else statementFigure 2.2: Schematic representation of the case-of-else constructions.21


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming Language• Instruction Block- Instruction or list of instructions <strong>to</strong> 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 <strong>to</strong> 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 ExercisesExercise 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 ornegative (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;vara,b:real;beginwrite(’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 ( (a0 thenwriteln(’The expected result is: ’,a*b:4:2)22


Alternative constructionselsewriteln(’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 <strong>to</strong> 0. Hence, we must change the comparison opera<strong>to</strong>r ≥ by > and add a clause <strong>to</strong> thefirst if.⊡Program 15: Exercise 2.1 (Version C)program c02e01;vara,b:real;beginwrite(’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)) thenwriteln(’The expected result is: ’,a*b:4:2)elsewriteln(’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 thanthe other two. Then, we select the smallest of the remaining two variables.Program 16: Exercise 2.2 (Version A)program c02e02;vara,b,c:integer;beginwrite(’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


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming Languageelseif (b


Alternative constructionswriteln(’The value in the middle is: ’,b)else if (min(b,c)


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming LanguageExercise 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 <strong>to</strong> proceed in two consecutive steps: (1) checking the validity of thevalues input by the user and (2) deciding which is the precedent in alphabetical order. In order<strong>to</strong> 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 <strong>to</strong> compare the letters regardless of their case, we turn both <strong>to</strong>upper case and compare.Program 21: Exercise 2.5program c02e05;varc1,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 divisionby 2 is 0 if and only the number is even.Program 22: Exercise 2.6program c02e06;varn:integer;beginwriteln(’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


Alternative constructionsExercise 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 smallerthan 5.Program 23: Exercise 2.7 (Version A)program c02e07;varvalue:real;beginwrite(’Input a number: ’);readln(value);(* Basic double comparison*)if (-5


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming LanguageProgram 25: Exercise 2.8program c02e08;uses math;varaLow,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 <strong>to</strong> 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.9program c02e09;varn1,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)) thenwriteln(’The result is ’,n1*(n2+n3),’.’)else if (n2>=n3) thenwriteln(’The result is ’,n2*(n1+n3),’.’)elsewriteln(’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 <strong>to</strong> the previous. Note how, after the first two if-then structureswe already know that the smallest value of the three is in n3.28


Alternative constructionsProgram 27: Exercise 2.10program c02e09;varn1,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 (n1n2*)if (n2


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming LanguageProgram 28: Exercise 2.11program c02e11;varm: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’)elsewriteln(’The mark is not valid.’)endend.The surrogate version, not making use of the case-of construction, is not as clear as theprevious. Hence, if a multi-branch alternative is <strong>to</strong> be taken based upon the value of an integeror char, case-of is preferred.Program 29: Exercise 2.11program c02e11;varm:integer;begin(* Reading the values*)write(’Please type the mark: ’);readln(m);(* We now use 2-fold alternatives*)if (m


Alternative constructionsProgram 30: Exercise 2.12program c02e12;constPI=3.14159;vara1,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 <strong>to</strong>tal 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 magnitudeof the greatest vec<strong>to</strong>r (cross) product than can be produced with two of them, assumingthey represent vec<strong>to</strong>rs of magnitude 1.□The magnitude cross product is given by the product of the magnitude of the vec<strong>to</strong>rs multipliedby the sine of the angle they generate. Since the magnitudes are assumed <strong>to</strong> be 1, werestrict the analysis <strong>to</strong> 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 vec<strong>to</strong>r, we canapply the difference of angles in any order, then calculate the absolute value. Second, we need<strong>to</strong> apply the max opera<strong>to</strong>r twice <strong>to</strong> be able <strong>to</strong> handle 3 elements.Program 31: Exercise 2.13program c02e13;uses math;constPI=3.14159;vara1,a2,a3:real;begin(* Reading the values*)write(’Please type the three angles (in radians): ’);read(a1);read(a2);readln(a3);(* Calculating the maximum vec<strong>to</strong>rial product.*)write(’The max vec<strong>to</strong>rial product is: ’);writeln(abs(max(sin(a1-a3),max(sin(a1-a2),sin(a2-a3)))):1:3,’.’)end.⊡31


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming LanguageExercise 2.14. Write a program that reads the coefficients of a 2 nd order equation ax 2 + bx + c = 0and obtains all the real solutions it has.□There are different considerations <strong>to</strong> be taken in the resolution of this program, that lead <strong>to</strong>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 formulax = −b ± √ b 2 − 4ac2aIn case √ b 2 − 4ac has no real solution, then there are no real solutions for the equation either.If √ b 2 − 4ac has a single real solution (because b 2 − 4ac = 0), the solution for the equation isunique. Otherwise, we must consider the two options in the ± opera<strong>to</strong>r.⊡Program 32: Exercise 2.14program c02e14;uses math;constPI=3.14159;vara,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) thenif (b=0) thenwriteln(’The equation is wrongly posed’)elsewriteln(’The single solution is ’,-c/b:3:4,’.’)elseif ((b*b-4*a*c)


Alternative constructionsThis program is yet another example of the use of case-of for the organization of severaloptions in the program.⊡Program 33: Exercise 2.15program c02e15;varval1,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 s<strong>to</strong>red 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);elsewriteln(’Invalid command’)endend.33


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming Language34


Chapter 3Iterative constructions3.1 Contents of this chapterThis chapter covers the following contents:1.a Iterative structure for using <strong>to</strong> and down<strong>to</strong> clauses.1.b Iterative structure while.1.c Iterative structure repeat.3.2 Brief reviewComputer programs are usually based on the repetition of a sequence of instructions. It wouldbe very inconvenient for a programmer <strong>to</strong> 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 <strong>programming</strong> <strong>language</strong>s allow for the use of theso-called iterative constructions, that is, constructions that force the program <strong>to</strong> repeat (iterate)the same sequences several times. Moreover, the number of times the code is <strong>to</strong> be repeated canbe dependent upon the data input by the user so that there is no need for the programmer <strong>to</strong>have that knowledge in advance.There are three iterative constructions considered in this chapter: for, while and repeatstructures. Very often, two or even three of them can be applied <strong>to</strong> 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 s<strong>to</strong>ps.In a for structure, we can use either a <strong>to</strong> or a down<strong>to</strong> clause. The only difference betweenthem is whether the counter variable (var) is increased or decreased at each iteration. When the<strong>to</strong> clause is used, the iteration is kept until the counter is greater than finalVal. Alternatively,if down<strong>to</strong> is used instead, the iteration is hold until the counter is lower than finalVal. Notethat, if using the <strong>to</strong> clause, we should use a finalVal greater than initVal. Otherwise, as seen35


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming Language...[Precedent code]❄[Precedent code]for var:=initVal <strong>to</strong> finalVal doInstruction Block[Following code]...var:=var+1✲var:=initVal❄var ≤ finalValtrue❄Instruction blockfalse❄[Following code](a) for structure with <strong>to</strong> clause...[Precedent code]❄[Precedent code]for var:=initVal down<strong>to</strong> finalVal doInstruction Block[Following code]...var:=var-1✲var:=initVal❄var ≥ finalValtrue❄Instruction blockfalse❄[Following code](b) for structure with down<strong>to</strong> clauseFigure 3.1: Schematic representation of the if-then-else constructions36


Iterative constructions...[Precedent code]while booleanExpression doInstruction Block[Following code]✲[Precedent code]❄booleanExpressiontrue❄Instruction blockfalse...❄[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 down<strong>to</strong>, 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 <strong>to</strong> do something until some conditionholds. For example, we might be interested in the program <strong>to</strong> ask the user for some piece ofdata until he or she inputs one satifying some criterion of validity. Hence, we would expect theprogram <strong>to</strong> repeat the inquiry until the value input by the user is satisfac<strong>to</strong>ry. It is impossible<strong>to</strong> characterize how many iterations the program has <strong>to</strong> perform in numerical terms, but it ishowever rather easy <strong>to</strong> explain it as a boolean condition. Consequently, the while structure wascreated as a commodity <strong>to</strong> ease the work of the programmer in such situations.The while structure, included in Fig. 3.2, iterates over an instruction block until some conditionis 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 <strong>to</strong> exit the iteration. That is, there are no embedded modification of a variable(as in the for), which will eventually lead <strong>to</strong> the exiting of the iteration. When using while, wehave <strong>to</strong> 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 <strong>to</strong> the while, since it also relies on a boolean condition <strong>to</strong> decide whether <strong>to</strong> 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 <strong>to</strong> be executed at least once, differently from what happened in thewhile structure.3.3 On the selection of an iterative structureAs 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 <strong>to</strong> preserve the readability of the37


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming Language...[Precedent code]repeatInstruction Blockuntil booleanExpression[Following code]...false✲[Precedent code]❄Instruction block❄booleanExpression❄[Following code]true(a) repeat structure.Figure 3.3: Schematic representation of the repeat construction.code, as well as the best-possible <strong>programming</strong> manners, we should always use the structurethat better suits the semantics of the problem. As a general rule, we have <strong>to</strong> 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 <strong>to</strong> be performed before entering theiterative structure, we should use for. Alternatively, if we cannot know before entering howmany times we have <strong>to</strong> iterate over the instruction block, then either while or repeat shouldbe used. In order <strong>to</strong> pick up one of these, a rule of thumb is considering that, if the instructionblock has <strong>to</strong> 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 impossible<strong>to</strong> define strict rules. The best <strong>to</strong>ol the programmer has <strong>to</strong> 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 <strong>to</strong> judiciously evaluate each situation he or she comes across.3.4 ExercisesThis chapter contains three different blocks of exercises. In Section 3.4.1 we present simplisticexercises <strong>to</strong> get in <strong>to</strong>uch 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 <strong>to</strong> generate uncommon on-screen displays.3.4.1 Iterative processingExercise 3.1. Write a program that asks a user <strong>to</strong> introduce an integer as many times as necessaryuntil it is positive.□In this case we enclose the typical write/read instruction pair in<strong>to</strong> a repeat structure. Theselection of repeat over the other options is due <strong>to</strong> two facts: (a) we don’t know in advance howmany attempts it will take the user <strong>to</strong> input a valid number and (b) we have <strong>to</strong> read the valueinput by the user at least once, so the semantic fits better in<strong>to</strong> a repeat than in<strong>to</strong> a while.38


Iterative constructionsProgram 34: Exercise 3.1 (Version A)program c03e01;vara:integer;beginrepeatwrite(’Please input a positive integer: ’);readln(a)until (a>=0);writeln(’The number is ’,a,’.’)end.In case we prefer <strong>to</strong> use while instead of a repeat, we need <strong>to</strong> 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;vara:integer;beginwrite(’Please input a positive integer: ’);readln(a);while (a=(5*abs(a)));writeln(’The numbers are a=’,a,’ and b=’,b,’.’)end.39


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming LanguageExercise 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. Consequently,the program needs <strong>to</strong> check all the values between the first integer (say a) and thesecond one (b). Note that now, opposedly <strong>to</strong> what happened in previous exercises, we knowhow many iterations we have <strong>to</strong> 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;vara,b,i:integer;beginwrite(’Please input the first integer: ’);readln(a);write(’Please input the second integer: ’);readln(b);for i:=a <strong>to</strong> b doif (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 <strong>to</strong> 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;vara,b,i:integer;beginwrite(’Please input the first integer: ’);readln(a);write(’Please input the second integer: ’);readln(b);i:=a;while (i


Iterative constructionsExercise 3.4. Write a program that demands the user <strong>to</strong> 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 valueof both variables, until their product reaches the expected value. We prefer for this the whilestructure 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;vara,b:integer;beginwrite(’Input a integer number: ’);readln(a);write(’Input another integer number: ’);readln(b);while (a*b 1000, we can compute k and avoid using iterative structures of any kind.Program 40: Exercise 3.4 (Version B)program c03e04;uses math;vara,b:integer;k:real;beginwrite(’Input a integer number: ’);readln(a);write(’Input another integer number: ’);readln(b);if (a*b


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming LanguageExercise 3.5. Write a program that asks a user for two integers and calculates their product notusing the neither product ( * ) nor division (div, /) opera<strong>to</strong>rs.□To solve this exercise we only need <strong>to</strong> sum the first integer (a) as many times as the value ofthe second integer (b). That is, we have <strong>to</strong> iterate the sum of a a fixed number of times, which isgiven by b, what intuitively leads <strong>to</strong> the use of a for construction. Note that the result is s<strong>to</strong>redin a variable result that must be initialized <strong>to</strong> 0. An alternative <strong>to</strong> 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;vara,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 <strong>to</strong> a doresult:=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 <strong>to</strong> 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 <strong>to</strong> read, compared <strong>to</strong> the previous one.Program 42: Exercise 3.5 (Version B)program c03e05;uses math;vara,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 <strong>to</strong> min(a,b) doresult:=result+max(a,b);writeln(’The result is ’,result)end.42


Iterative constructionsInstead of using max/min functions, we could also force a <strong>to</strong> 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 <strong>to</strong> 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;vara,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 Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming Languagewrite(a,’, ’);b:=1;write(b,’, ’);(* Now comes the sequence from second position on *)for i:=3 <strong>to</strong> num dobeginaux:=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 <strong>to</strong> use a for statement <strong>to</strong> go though the numbers. The clause used<strong>to</strong> modify the counting variable is down<strong>to</strong>, since the sequence has <strong>to</strong> be decreasing.Program 45: Exercise 3.7program c03e07;vara,b,i:integer;beginwrite(’Please input the first integer: ’);readln(a);write(’Please input the second integer: ’);readln(b);for i:=b down<strong>to</strong> 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 <strong>to</strong> go twice through the numbers in the sequence of numberscontained 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 down<strong>to</strong> clause, while the second uses a <strong>to</strong>. To complete the exercise we need<strong>to</strong> consider the use of mod 2 for discriminating even and odd numbers.44


Iterative constructionsProgram 46: Exercise 3.8program c03e08;vara,b,i:integer;beginwrite(’Please input the first integer: ’);readln(a);write(’Please input the second integer: ’);readln(b);for i:=b down<strong>to</strong> a doif (i mod 2 =1) thenwrite(i,’ ’);writeln;(* Jumping the line *)for i:=a <strong>to</strong> b doif (i mod 2 =0) thenwrite(i,’ ’);writelnend.⊡3.4.2 Computing with sequencesThe 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 <strong>to</strong> handle the iteration. Moreover, the program is required <strong>to</strong> capturesome information about the elements of the sequence, so that we need <strong>to</strong> mantain some kindof data about what we have seen so far, but at the same time having the ability <strong>to</strong> 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 <strong>to</strong> satisfy thecondition. Hence, we use a while structure. In this exercise we use the variable b <strong>to</strong> save thelast value, while the one before the last one is s<strong>to</strong>red in a. In this way, each time the user inputs anew number, a is updated (taking the value in b), while b s<strong>to</strong>res the new one.⊡Program 47: Exercise 3.9program c03e09;vara,b:char;beginwrite(’Please input a char and press enter: ’);readln(a);write(’Please input the second char and press enter: ’);readln(b);while (ab) dobegina:=b;write(’Please another char and press enter: ’);readln(b)endend.45


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming LanguageExercise 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 <strong>to</strong> solve the problem we need <strong>to</strong> 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 <strong>to</strong> s<strong>to</strong>re, at each position of thesequence, the last three values. Hence, each iteration they have <strong>to</strong> be updated as if they castsome sort of chaing Every time we read an integer, it will be s<strong>to</strong>red in a3). At the same time, a1and a2 need <strong>to</strong> be updated using the values obtained from the previous iteration The iterativeprocess s<strong>to</strong>ps when the comparison of a1 and a3 satisfies the exiting condition.Program 48: Exercise 3.10program c03e10;vara1,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


Iterative constructionsProgram 49: Exercise 3.11program c03e11;vara: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) dobegin(* 1- Reading the number *)write(’Please input another integer and press enter: ’);readln(a);(* 2- Processing the number *)if (evenPos) thenevenSum:=evenSum+aelseif (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 <strong>to</strong> count the number of letters using one integers. To do sowe only need <strong>to</strong> distinguish between letter and non-letter chars. In this case we do it with an ifstatement 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;varc: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’


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming LanguageIn order <strong>to</strong> make the comparison simpler we might use the function lowercase, whichconverts any char (if possible) <strong>to</strong> its lower case representation. If using this function, we onlyneed <strong>to</strong> know if the letter is included in the lower-case range of letters.Program 51: Exercise 3.12 (Version B)program c03e12;varc: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’


Iterative constructionsExercise 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 s<strong>to</strong>re all theprevious 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 s<strong>to</strong>res the next value we are waiting for in such subsequence. This variable is initialized <strong>to</strong>1, 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 <strong>to</strong> 1.Program 53: Exercise 3.14program c03e14;vara: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) thenbeginnowWaiting:=nowWaiting+1;if (nowWaiting=4) thenbeginnowWaiting:=1;counter:=counter+1endenduntil(a


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming Language⊡Program 54: Exercise 3.15program c03e15;varc: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+1elsecurrentLength:=0end;if (currentLength>maxLength) thenmaxLength:=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 <strong>to</strong> solve this exercise is maintaining the last two chars in thesequence. 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 <strong>to</strong> decide whether the upper-lowercase combination has taken place.⊡Program 55: Exercise 3.16program c03e16;varc: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’


Iterative constructionsExercise 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 werefer <strong>to</strong> as c (for the current), prevC and prevPrevC (for the past ones). Then, we only need <strong>to</strong>compare at each iteration whether the requirements are fulfilled <strong>to</strong> increase the counter.There is a reason why we cannot repeat the schema in the previous exercise, using a booleanvariable <strong>to</strong> 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 <strong>to</strong> 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.17program c03e17;varc: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’


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming LanguageProgram 57: Exercise 3.18program c03e18;varc: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’) thenbeginif (currentDistance>maxDistance) thenmaxDistance:=currentDistance;currentDistance:=0endelseif (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 <strong>to</strong> keep track of (a) the length of the current same-char sequenceand (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 equal<strong>to</strong> 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 s<strong>to</strong>red in lower case, so we do not have <strong>to</strong> worry about the case anymore.Program 58: Exercise 3.19program c03e19;varc: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


Iterative constructionsif (lowercase(c)=currentChar) thencurrentLength:=currentLength+1elsebeginif (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 <strong>to</strong> complete this exercise we need five boolean variables <strong>to</strong> know whether each ofthe vowels already appeared in the sequence, plus a variable <strong>to</strong> save the letter that was the last <strong>to</strong>appear. 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 <strong>to</strong> true, i.e. right after the last vowel appears for the firsttime.⊡Program 59: Exercise 3.20program c03e20;varc,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:=trueelse if (lowercase(c)=’i’) then hasI:=trueelse if (lowercase(c)=’o’) then hasO:=trueelse 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


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming LanguageExercise 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 <strong>to</strong> 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 <strong>to</strong> use the minimum value an integer can take, and hence we setsuch variables <strong>to</strong> -32500. The reason is that this value will au<strong>to</strong>matically prevent the 2 firstelements of the sequence from being considered as belonging <strong>to</strong> the heaviest sequences. Ofcourse, alternatives could be taken. An example would be reading the first two numbers outsidethe iteration in order <strong>to</strong> provide maxWeight with a meaningful initial valueProgram 60: Exercise 3.21program c03e21;constMIN_INTEGER=-32500;varn: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) thenmaxWeight:=n+prevN+prevPrevN;prevPrevN:=prevN;prevN:=nuntil(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 <strong>to</strong> 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 <strong>to</strong> the previous, provided two differences. First, we havethe need <strong>to</strong> convert each letter <strong>to</strong> its numerical value; Second, the initialization of maxWeight,prevWeight and prevPrevWeight is easier, since we can set them <strong>to</strong> 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


Iterative constructionsProgram 61: Exercise 3.22program c03e22;varc: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’


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming Language⊡if (c=’(’) thenparCount:=parCount+1else if(c=’)’) thenbeginparCount:=parCount-1;if (parCount


Iterative constructionsAlthough the exercise appears <strong>to</strong> 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 <strong>to</strong> true, and hence thesequence is classified as illegal. To solve it, we use a boolean variable <strong>to</strong> know whether an ’a’was found in the sequence. Note that, otherwise, any of such sequences is going <strong>to</strong> be valid.⊡Program 64: Exercise 3.24 (Version B)program c03e24;varc: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’) thenbeginsomeAappear:=true;if (expectingB) thenresult:=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) thenwriteln(’The condition is not satisfied’)elsewriteln(’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 <strong>to</strong> remember whether the previous number was even or not. We usea boolean variable (prevIsEven) <strong>to</strong> 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.25program c03e25;varn:integer;prevIntIsEven:boolean;counter:integer;beginwriteln(’Please input the sequence of integers ended by zero (0): ’);57


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> 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)) thencounter:=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 <strong>to</strong> 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 <strong>to</strong> sum the up each time<strong>to</strong> see if the result is equal <strong>to</strong> 0.⊡Program 66: Exercise 3.26program c03e26;constMIN_INTEGER=-32500;varn: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) thenresult:=true;prevPrevInt:=prevInt;prevInt:=nuntil(n=0);if (result) thenwriteln(’The situation happens at least once.’)elsewriteln(’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 <strong>to</strong> the one in the Exercise 3.26, exception made that we are nowchecking the ordering of the values, instead of their sum.58


Iterative constructionsProgram 67: Exercise 3.27program c03e27;constMAX_INTEGER=32500;varn: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


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming LanguageExercise 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 <strong>to</strong> the one in the Exercise 3.26.Program 69: Exercise 3.29program c03e29;varn,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=3*prevPrevReal*r) thencounter:=counter+1;prevPrevReal:=prevReal;prevReal:=runtil(r


Iterative constructions3.4.3 On-screen matrix displayingThis 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 able<strong>to</strong> represent the information <strong>to</strong> be displayed at every position of the matrix. If such expression isfound, we only have the need of using a double for statement <strong>to</strong> 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 suchas1 2 3 . . . N2 4 6 . . . 2 · N3 6 9 . . . 3 · N. . . . . . . . . . . . . . .N 2 · N 3 · N . . . N 2□In this case the expression <strong>to</strong> be applied at each position is simply i · j, where i representsthe 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.31program c03e31;varn:integer;i,j:integer;beginwrite(’Please input the value of n: ’);readln(n);for i:=1 <strong>to</strong> n dobeginfor j:=1 <strong>to</strong> n dowrite(’ ’,i*j:4,’ ’);writelnendend.⊡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 <strong>to</strong> the main diagonal.That is, a matrix such as0 1 2 . . . N1 0 1 . . . N − 12 1 0 . . . N − 2 .. . . . . . . . . . . . . . .N N − 1 N − 2 . . . 0□The distance <strong>to</strong> the main diagonal is always the either the distance in horizontal or the distancein vertical (it is always the same). Hence, at each position (i, j) we must display either |i − j| or|j − i|.61


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming LanguageProgram 72: Exercise 3.32program c03e32;uses math;varn:integer;i,j:integer;beginwrite(’Please input the value of n: ’);readln(n);for i:=1 <strong>to</strong> n dobeginfor j:=1 <strong>to</strong> n dowrite(’ ’,abs(i-j):4,’ ’);writelnendend.⊡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 <strong>to</strong> one of the matrix diagonals. That is, a matrix such as1 . . . n4 . . .9 . . . .. . . . . . . . . . . . . . .n . . . n 2□An position (i, j) a matrix belongs <strong>to</strong> a diagonal (a) if i = j or (b) if i = j − n + 1. Hence, wejust need <strong>to</strong> use an if statement <strong>to</strong> discriminate those situations from the others. Note that, inorder for the matrix <strong>to</strong> be well aligned, we have <strong>to</strong> write some blank spaces even when there isno number <strong>to</strong> be displayed.Program 73: Exercise 3.33program c03e33;varn:integer;i,j:integer;beginwrite(’Please input the value of n: ’);readln(n);for i:=1 <strong>to</strong> n dobeginfor j:=1 <strong>to</strong> n doif ((i=j) or (i=n-j+1)) thenwrite(’ ’,i*j:4,’ ’)elsewrite(’ ’);writelnendend.⊡62


Iterative constructionsExercise 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 016 0 18 0 200 22 0 24 026 0 28 0 30In this exercise we also have <strong>to</strong> perform a discrimination based upon the values of i and j.Program 74: Exercise 3.34program c03e34;varn:integer;i,j:integer;beginwrite(’Please input the value of n: ’);readln(n);for i:=1 <strong>to</strong> n dobeginfor j:=1 <strong>to</strong> n doif (((i* N) +j) mod 2=0) thenwrite(’ ’,(i* N) +j:4,’ ’)elsewrite(’ ’);writelnendend.⊡Exercise 3.35. Create a program that reads an integer n from the keyboard and writes a matrixof n × n elements such as1 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 <strong>to</strong> display a value. Hence,we nested if-else-if structure within the iteration.Program 75: Exercise 3.35program c03e35;varn:integer;i,j:integer;beginwrite(’Please input the value of n: ’);readln(n);63


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming Languagefor i:=1 <strong>to</strong> n dobeginfor j:=1 <strong>to</strong> 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(’ ’);writelnendend.⊡64


Chapter 4Data structures4.1 Contents of this chapterThis chapter covers the following contents:4.a Use of vec<strong>to</strong>rs (one dimensional arrays).4.b Use of matrices (two dimensional arrays).4.c Use of strings.4.2 Brief reviewSo far we have only used scalar variables, that is variables that contain one single elemen<strong>to</strong>f 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 <strong>to</strong>handle huge amounts of data. If restricting <strong>to</strong> the contents of the previous chapters, in order <strong>to</strong>handle 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, modern<strong>programming</strong> <strong>language</strong>s 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 <strong>to</strong> itsposition in the grid. In a sense, the concept of array in <strong>programming</strong> <strong>language</strong>s 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 <strong>to</strong>define 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 <strong>to</strong> 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 <strong>Pascal</strong> offers extra commodities in order <strong>to</strong> simplifythe task. More specifically, it offers the type string, which is a wrapper of an array of chars. A65


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming Languagea[1] a[2] a[3] a[N-1] a[N](a) Unidimensional array (vec<strong>to</strong>r) declared as a:array[1..N] of integer.a[1][1] a[1][2] a[1][3] a[1][N-1] a[1][N]a[2][1] a[2][2] a[2][3] a[2][N-1] a[2][N] a[M][1] a[M][2] a[M][3] 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 <strong>to</strong> be defined in the declarison of thevariable. However, it might be s<strong>to</strong>ring 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 s<strong>to</strong>red in the variable w. If thelength of w does not allow for all the text <strong>to</strong> fit in the variable, only the first chars are s<strong>to</strong>red.After using this functionality, the length(w) returns the number of chars s<strong>to</strong>red in thevariable.In addition <strong>to</strong> the previous, there are special functions available for functions: [+] - The + symbol can act as concatena<strong>to</strong>r 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 + opera<strong>to</strong>rdoes. [=] - 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


Data structures str(num,w) - S<strong>to</strong>res in the variable w the text representation of num, where num is anynumeric (real or integer) variable. val(w,num,cod) - S<strong>to</strong>res 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 <strong>practical</strong> <strong>to</strong> use stringsinstead of arrays of chars when handling sentences or words. However, note that string canonly hold lines of text, and cannot be used <strong>to</strong> substitute arrays of chars with more than onedimension (e.g. 2D matrices).4.3 Exercises4.3.1 Working with arrays and matricesExercise 4.1. Create a program that reads a vec<strong>to</strong>r 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 <strong>to</strong> 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.1program c04e01;constN=10;typerealVec<strong>to</strong>r=ARRAY[1..N] OF real;vari:integer;myVec<strong>to</strong>r:realVec<strong>to</strong>r;begin(* 1- Reading the vec<strong>to</strong>r *)writeln(’About <strong>to</strong> start’);for i:=1 <strong>to</strong> N dobeginwrite(’Enter value ’,i,’: ’);readln(myVec<strong>to</strong>r[i]);end;(* 2- Displaying the values *)writeln(’The contents of the vec<strong>to</strong>r are:’);for i:=1 <strong>to</strong> N dowriteln(’At pos ’,i,’: ’,myVec<strong>to</strong>r[i]:4:3)end.⊡67


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming LanguageExercise 4.2. Create a program that reads two vec<strong>to</strong>rs of N elements (being N a constant) andcalculates their scalar product. Each vec<strong>to</strong>r must be read at one single line, in which the user has<strong>to</strong> input N numbers split by blank spaces.□This exercise brings forward two different tasks: reading several values in the same lineand computing the scalar product of two vec<strong>to</strong>rs. For the former one, we have <strong>to</strong> use theread command, which reads all the consecutive digits until the user inputs a blank space, thencombines them <strong>to</strong> 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 <strong>to</strong> 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 vec<strong>to</strong>rs.Program 77: Exercise 4.2program c04e03;constN=5;typerealVec<strong>to</strong>r=ARRAY[1..N] OF real;vari:integer;vecA,vecB:realVec<strong>to</strong>r;result:real;begin(* Reading the first vec<strong>to</strong>r *)writeln(’Introduce the first vec<strong>to</strong>r of ’,N,’ elements, splitted by blank spaces.’);for i:=1 <strong>to</strong> N doread(vecA[i]);(* Reading the second one *)writeln(’Introduce the second vec<strong>to</strong>r of ’,N,’ elements, splitted by blank spaces.’);for i:=1 <strong>to</strong> N doread(vecB[i]);(* Initializing the variable and computing the result *)result:=0;for i:=1 <strong>to</strong> 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. Inthis 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 program68


Data structuresProgram 78: Exercise 4.3program c04e03;constN=10;typeintMatrix=ARRAY[1..N,1..N] OF integer;vari,j:integer;matA:intMatrix;begin(* 1- Reading the vec<strong>to</strong>r *)writeln(’Introduce the matrix.’);for i:=1 <strong>to</strong> N dofor j:=1 <strong>to</strong> N dobeginwrite(’Introduce the value at row ’,i,’ and col ’,j,’: ’);read(matA[i][j])end;(* 2- Displaying the values *)for i:=1 <strong>to</strong> N dobeginfor j:=1 <strong>to</strong> N dowrite(matA[i][j],’ ’);writelnendend.⊡Exercise 4.4. Create a program that reads a vec<strong>to</strong>r 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 <strong>to</strong> read the whole array,for later going trough all the values. Note that the variables minVal and maxVal must be set<strong>to</strong> some value before analyzing the first position of the array. In this case we set them <strong>to</strong> 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 <strong>to</strong> its value.Program 79: Exercise 4.4 (version A)program c04e04;constN=10;typeintVec<strong>to</strong>r=ARRAY[1..N] OF integer;vari:integer;myVec<strong>to</strong>r:intVec<strong>to</strong>r;minVal,maxVal,sum:integer;mean:real;begin(* 1- Reading the vec<strong>to</strong>r *)writeln(’Introduce the vec<strong>to</strong>r of ’,N,’ elements, splitted by blank spaces.’);for i:=1 <strong>to</strong> N doread(myVec<strong>to</strong>r[i]);(* 2- Obtaining the information *)minVal:=32000;maxVal:=-32000;69


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming Languagesum:=0;for i:=1 <strong>to</strong> N dobeginif (myVec<strong>to</strong>r[i]maxVal) thenmaxVal:=myVec<strong>to</strong>r[i];sum:=sum+myVec<strong>to</strong>r[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 <strong>to</strong> 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 <strong>to</strong> start thesecond for at the second position (i:=2), in order not <strong>to</strong> count the value of the first positiontwice in the computation of the mean.Program 80: Exercise 4.5 (version B)program c04e04;constN=10;typeintVec<strong>to</strong>r=ARRAY[1..N] OF integer;vari:integer;myVec<strong>to</strong>r:intVec<strong>to</strong>r;min,max,sum:integer;mean:real;begin(* 1- Reading the vec<strong>to</strong>r *)writeln(’Introduce the vec<strong>to</strong>r of ’,N,’ elements, splitted by blank spaces.’);for i:=1 <strong>to</strong> N doread(myVec<strong>to</strong>r[i]);(* 2- Obtaining the information *)min:=myVec<strong>to</strong>r[1];max:=myVec<strong>to</strong>r[1];sum:=myVec<strong>to</strong>r[1];for i:=2 <strong>to</strong> N dobeginif (myVec<strong>to</strong>r[i]max) thenmax:=myVec<strong>to</strong>r[i];sum:=sum+myVec<strong>to</strong>r[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 <strong>to</strong> the previous structure in the upcoming exercises, with thepourpose of making the programs as readable as possible.70


Data structuresProgram 81: Exercise 4.4 (version C)program c04e04;constN=10;typeintVec<strong>to</strong>r=ARRAY[1..N] OF integer;vari:integer;myVec<strong>to</strong>r:intVec<strong>to</strong>r;min,max,sum:integer;mean:real;beginwriteln(’Introduce the vec<strong>to</strong>r of ’,N,’ elements, splitted by blank spaces.’);(* Reading the first value *)read(myVec<strong>to</strong>r[1]);(* Setting the initial values *)min:=myVec<strong>to</strong>r[1];max:=myVec<strong>to</strong>r[1];sum:=myVec<strong>to</strong>r[1];(* Reading and processing the remaining values *)for i:=2 <strong>to</strong> N dobeginread(myVec<strong>to</strong>r[i]);if (myVec<strong>to</strong>r[i]max) thenmax:=myVec<strong>to</strong>r[i];sum:=sum+myVec<strong>to</strong>r[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 vec<strong>to</strong>r 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 twoiterations over the values of the array <strong>to</strong> compute the expected result. The reason is that, inorder <strong>to</strong> compute the standard deviation, we need <strong>to</strong> know the mean of the values. Hence, afirst pass through the vec<strong>to</strong>r has <strong>to</strong> be accomplish <strong>to</strong> compute the mean, followed by a secondone <strong>to</strong> compute the standard deviation.Program 82: Exercise 4.5program c04e05;constN=5;typeintVec<strong>to</strong>r=ARRAY[1..N] OF integer;vari:integer;myVec<strong>to</strong>r:intVec<strong>to</strong>r;mean,std:real;begin(* Reading *)71


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming Language⊡writeln(’Introduce the vec<strong>to</strong>r of ’,N,’ elements, splitted by blank spaces.’);(* First pass computing the mean *)mean:=0;for i:=1 <strong>to</strong> N dobeginread(myVec<strong>to</strong>r[i]);mean:=mean+(myVec<strong>to</strong>r[i]/N)end;(* Second pass computing the standard deviation *)std:=0;for i:=1 <strong>to</strong> N dostd:=std+( (sqr(myVec<strong>to</strong>r[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 vec<strong>to</strong>r A of N reals (being N a constant), and creates anew vec<strong>to</strong>r so that at every position i it contains the sum of all the values of A up <strong>to</strong> that position.□Initially, this problem is solved by using a double loop. First, we have <strong>to</strong> read the vec<strong>to</strong>r A.Then, for each position i, we perform an iteration up <strong>to</strong> that position accumulating the valuess<strong>to</strong>red in the vec<strong>to</strong>r A. Note that it is necessary a good practice <strong>to</strong> initialize the values in thevec<strong>to</strong>r B <strong>to</strong> 0.Program 83: Exercise 4.6 (Version A)program c04e06;constN=5;typeintVec<strong>to</strong>r=ARRAY[1..N] OF integer;vari,j:integer;A,B:intVec<strong>to</strong>r;begin(* Reading *)writeln(’Introduce the vec<strong>to</strong>r of ’,N,’ elements, splitted by blank spaces.’);for i:=1 <strong>to</strong> N dobeginread(A[i]);end;(* Accumulating *)for i:=1 <strong>to</strong> N dobeginB[i]:=0;for j:=1 <strong>to</strong> i doB[i]:=B[i]+A[j]end;(* Accumulating *)write(’The values in the vec<strong>to</strong>r are: ’);for i:=1 <strong>to</strong> 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 <strong>to</strong> i-1. However, that sum is already s<strong>to</strong>red in B[i].Hence, the solution can be simplified (and enhanced) by making use of such values72


Data structuresProgram 84: Exercise 4.6 (Version B)program c04e06;constN=5;typeintVec<strong>to</strong>r=ARRAY[1..N] OF integer;vari:integer;A,B:intVec<strong>to</strong>r;begin(* Reading *)writeln(’Introduce the vec<strong>to</strong>r of ’,N,’ elements, splitted by blank spaces.’);for i:=1 <strong>to</strong> N dobeginread(A[i]);end;(* Accumulating *)B[1]:=A[1];for i:=2 <strong>to</strong> N doB[i]:=B[i-1]+A[i];(* Accumulating *)write(’The values in the vec<strong>to</strong>r are: ’);for i:=1 <strong>to</strong> N dowrite(B[i],’ ’);end.⊡Exercise 4.7. Create a program that reads a vec<strong>to</strong>r A of N reals (being N a constant), and createsa new vec<strong>to</strong>r 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 <strong>to</strong> the previous, but the solution cannot be as elegant as that inProgram 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 <strong>to</strong> remove one of the values from the count in B[i-1], since the value in theposition i-3 should not be taken in<strong>to</strong> account in the sum for a given B[i].Program 85: Exercise 4.7program c04e07;constN=10;typeintVec<strong>to</strong>r=ARRAY[1..N] OF integer;vari:integer;A,B:intVec<strong>to</strong>r;begin(* Reading *)writeln(’Introduce the vec<strong>to</strong>r of ’,N,’ elements, splitted by blank spaces.’);for i:=1 <strong>to</strong> N doread(A[i]);(* Accumulating *)B[1]:=A[1];(* Initial values *)for i:=2 <strong>to</strong> 3 do73


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming Language⊡B[i]:=B[i-1]+A[i];(* General schema and, then, accumulation *)for i:=4 <strong>to</strong> N doB[i]:=B[i-1]-A[i-3]+A[i];write(’The values in the vec<strong>to</strong>r are: ’);for i:=1 <strong>to</strong> N dowrite(B[i],’ ’);end.Exercise 4.8. Create a program that reads a vec<strong>to</strong>r of N integers (being N a constant), then findsthe last negative number.□The previous exercises had something in common: we needed an exhaustive examination ofthe array in order <strong>to</strong> obtain the results. That is, all the elements of the array had <strong>to</strong> be checked<strong>to</strong> 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 <strong>to</strong> examine all the elementsin the array, but <strong>to</strong> s<strong>to</strong>p when we find the last (first starting by the end) negative instead. Thewhile iterative structure seems now more appropriate. Note that we need <strong>to</strong> update the valueof i at each iteration.There are two different reasons why the iteration could s<strong>to</strong>p. The first one is that myVec<strong>to</strong>r[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 s<strong>to</strong>p iterating. Hence, it is clear thatthe value of i after exiting the while is the indica<strong>to</strong>r we need <strong>to</strong> know which of the previousscenarios happened.⊡Program 86: Exercise 4.8program c04e08;constN=10;typeintVec<strong>to</strong>r=ARRAY[1..N] OF integer;vari:integer;myVec<strong>to</strong>r:intVec<strong>to</strong>r;begin(* Reading *)writeln(’Introduce the vec<strong>to</strong>r of ’,N,’ elements, splitted by blank spaces.’);for i:=1 <strong>to</strong> N doread(myVec<strong>to</strong>r[i]);(* Seeking the last negative *)i:=N;while (i>=1) and (myVec<strong>to</strong>r[i]>=0) doi:=i-1;(* Checking out what happened at the loop *)if (i>=1) thenwriteln(’The last negative is ’,myVec<strong>to</strong>r[i],’, in pos ’,i,’.’)elsewriteln(’There are no negatives in the vec<strong>to</strong>r’)end.74


Data structuresExercise 4.9. Create a program that reads a vec<strong>to</strong>r 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 stepfurther, since we need <strong>to</strong> perform a double search. First, we need <strong>to</strong> find the first position ofthe array containing a positive number. Then, from that position on, we need <strong>to</strong> find the firstnegative.The first part of the program is very similar <strong>to</strong> the one in the exercise before. In the second,we have <strong>to</strong> proceed for searching for a negative number. Note that there might be no positivesin the array, so we have <strong>to</strong> include an if statement <strong>to</strong> display the corresponding result.⊡Program 87: Exercise 4.9program c04e09;constN=10;typeintVec<strong>to</strong>r=ARRAY[1..N] OF integer;vari:integer;myVec<strong>to</strong>r:intVec<strong>to</strong>r;begin(* Reading the vec<strong>to</strong>r *)writeln(’Introduce the vec<strong>to</strong>r of ’,N,’ elements, splitted by blanks.’);for i:=1 <strong>to</strong> N doread(myVec<strong>to</strong>r[i]);(* Go over positions as long as you find negatives *)i:=1;while (iN) thenwriteln(’There are no negatives after the first positive.’)elsewriteln(’The first negative after one positive is ’,myVec<strong>to</strong>r[i],’, in posendend.’,i,’.’)Exercise 4.10. Create a program that reads a vec<strong>to</strong>r of N integers (being N a constant), then findsthe last positive number before the first negative one.□This program is very similar <strong>to</strong> the previous. Indeed, most of the searching algorithmsare very similar <strong>to</strong> each other, holding a similar structure, which can be broken down in<strong>to</strong> thefollowing:• Initializing the pointing variable.75


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> 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.10program c04e10;constN=10;typeintVec<strong>to</strong>r=ARRAY[1..N] OF integer;vari:integer;myVec<strong>to</strong>r:intVec<strong>to</strong>r;begin(* Reading the vec<strong>to</strong>r *)writeln(’Introduce the vec<strong>to</strong>r of ’,N,’ elements, splitted by blanks.’);for i:=1 <strong>to</strong> N doread(myVec<strong>to</strong>r[i]);(* Checking the first position *)if (myVec<strong>to</strong>r[1]N) thenwriteln(’There are no negatives after the positives.’)elsewriteln(’The last positive before the first negative is ’,myVec<strong>to</strong>r[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 thecolumns and j for the rows. Obviously, we need <strong>to</strong> coordinate the increase of both in ordersuccessfully explore the positions of the array.Program 89: Exercise 4.11program c04e11;constN=3;M=2;typeintMatrix=ARRAY[1..N,1..M] OF integer;76


Data structuresvari,j:integer;matA:intMatrix;begin(* Reading the matrix *)writeln(’Introduce the matrix.’);for i:=1 <strong>to</strong> N dofor j:=1 <strong>to</strong> M dobeginwrite(’Introduce the value at row ’,i,’ and col ’,j,’: ’);read(matA[i][j])end;(* Perform the search *)i:=1;j:=1;while ( (iN) then (* This means that a new line has <strong>to</strong> be analyzed *)beginj:=j+1;i:=i+1endend;(* Checking out the result *)if (i


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming Language⊡(* Ask the user *)write(’Introduce the number a: ’);readln(a);(* Count *)sum:=0;for i:=1 <strong>to</strong> 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 <strong>to</strong> sum the elements of each row and column. Then, we have <strong>to</strong> findout which one produces the greater sum. Conceptually, it is very similar <strong>to</strong> the Exercise 4.4 inwhich we had <strong>to</strong> find the greatest element of a table. In fact, we also have <strong>to</strong> address the problemof setting maxSum <strong>to</strong> some initial value.Program 91: Exercise 4.13program c04e13;constN=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 <strong>to</strong> N dobeginwriteln(’Introduce the row ’,i,’: ’);for j:=1 <strong>to</strong> M doread(matA[i][j])end;(* Initialize the variable *)maxSum:=-32000;(* Checking rows *)for i:=1 <strong>to</strong> N dobegincurrentSum:=0;for j:=1 <strong>to</strong> M docurrentSum:=currentSum+matA[i][j];if (currentSum>maxSum) thenmaxSum:=currentSumend;(* Checking colums *)for j:=1 <strong>to</strong> M dobegincurrentSum:=0;for i:=1 <strong>to</strong> N docurrentSum:=currentSum+matA[i][j];78


Data structuresif (currentSum>maxSum) thenmaxSum:=currentSumend;(* Displaying the result *)writeln(’The max such is is ’,maxSum,’.’)end.⊡Exercise 4.14. Create a program that reads a vec<strong>to</strong>r 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 deeplystudied, and very efficient methods appeared (e.g. mergesort or quicksort). In this exercise wewill use the simplest of the approaches <strong>to</strong> 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 <strong>to</strong> repeat the operation is N-1, since the last position(N) holds by the the greatest element in N.Program 92: Exercise 4.14program c04e14;constN=10;varvec:ARRAY[1..N] of integer;i,j,aux:integer;begin(* Reading the vec<strong>to</strong>r *)writeln(’Please introduce the ’,N,’ elements.’);for i:=1 <strong>to</strong> N doread(vec[i]);(* Sorting the vec<strong>to</strong>r *)for i:=1 <strong>to</strong> N-1 dofor j:=i+1 <strong>to</strong> N do(* Checking wether the value at j is greater... *)(* ... than the one at i *)if (vec[i]>vec[j]) thenbeginaux:=vec[i];vec[i]:=vec[j];vec[j]:=auxend;(* Displaying the vec<strong>to</strong>r *)writeln(’The final vec<strong>to</strong>r is: ’);for i:=1 <strong>to</strong> N dowrite(’ ’,vec[i],’ ’)end.⊡79


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming LanguageExercise 4.15. Create a program that reads a vec<strong>to</strong>r 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 vec<strong>to</strong>r in this exercise.□This problem is considerably more tricky than the previous, and demand an slightly moreintelligent approach. Our idea is <strong>to</strong> push behind every odd number in the table, until no oddintegers appear before the last even one. In order <strong>to</strong> 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 <strong>to</strong> 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.15program c04e15;constN=10;varvec:ARRAY[1..N] of integer;i,j:integer;aux:integer;begin(* Reading the vec<strong>to</strong>r *)writeln(’Please introduce the ’,N,’ elements.’);for i:=1 <strong>to</strong> N doread(vec[i]);(* Find the position *)i:=0;repeati:=i+1;if (vec[i] mod 2 = 1) thenbegin(* Find the first <strong>to</strong> swap *)j:=i;while ((j


Data structuresExercise 4.16. Create a string that reads a real number as text (in a string) and s<strong>to</strong>res the value itrepresents in a real variable. Note that the text must represent a valid real number with at leas<strong>to</strong>ne digit and one or no dots <strong>to</strong> separate the integer- and real-valued part.The easiest solution <strong>to</strong> 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 strictlymanda<strong>to</strong>ry, but enhances the overall comprehensibility of the program.Program 94: Exercise 4.16 (Version A)program c04e16;constN=10;vara: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


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming Languagewhile( (i


Data structuresProgram 97: Exercise 4.17 (version B)program c04e17;constN=10;typenPosWord=STRING[N];varw:nPosWord;beginwrite(’Please introduce a sentence of up <strong>to</strong> ’,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 <strong>to</strong> finding a positioni 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 <strong>to</strong> compare each of the chars of the string with its mirroringelement. If the string is symmetric, the iteration will only s<strong>to</strong>p 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;constN=15;varstr:STRING[N];i:integer;begin(* Reading *)write(’Please introduce the string: ’);readln(str);(* Checking *)i:=1;while ((ilength(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 <strong>to</strong> each other, exactly thesame as in the last iteration. We only have <strong>to</strong> iterate over the first half of the elements, and hencethe pointing variable must only reach the middle of the string.83


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming LanguageProgram 99: Exercise 4.18 (version B)program c04e18;uses math;constN=15;varstr:STRING[N];i:integer;begin(* Reading *)write(’Please introduce the string: ’);readln(str);(* Checking *)i:=1;while ((ifloor(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 ofintegers 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 <strong>to</strong> initialize the counter setting all its positions <strong>to</strong> 0. Very ofter this is done bydefault by the compiler or the memory management system, but it is not a good practice <strong>to</strong> leave(and use) the default values. Second, we have <strong>to</strong> go over the string annotating the appearanceof each char. In order <strong>to</strong> do so we first compute the position of the character with respect <strong>to</strong> 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.19program c04e19;constN=30;NUMLETTERS=26;varstr:STRING[N];counter:ARRAY[1..NUMLETTERS] of integer;i,positionInTable:integer;begin(* Read the text *)84


Data structureswriteln(’Please introduce the word: ’);readln(str);(* Initialize the counters *)for i:=1 <strong>to</strong> NUMLETTERS docounter[i]:=0;(* Start counting up *)for i:=1 <strong>to</strong> length(str) dobeginpositionInTable:=ord(upcase(str[i]))-ord(’A’)+1;if ( (1


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming Language(* Displaying the vec<strong>to</strong>r *)writeln(’The second vec<strong>to</strong>r is: ’);for i:=1 <strong>to</strong> N dowrite(’ ’,vecB[i],’ ’)end.⊡4.3.3 On-screen matrix displayingExercise 4.21. Create a program that reads a string and draws it diagonally. For example, theword computer must look like:computer□The key question in this kind of exercises is understanding (and being able <strong>to</strong> write code for)what has <strong>to</strong> be displayed at each line. Consequently, this program is rather simple, since it isclear that at each line i we need <strong>to</strong> 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 <strong>to</strong> prompt <strong>to</strong> jump <strong>to</strong>the next line. In this way, the blank spaces on the right of the characters are not written.Program 102: Exercise 4.21program c04e21;constN=15;varstr: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 <strong>to</strong> length(str) dobeginfor j:=1 <strong>to</strong> i-1 dowrite(’ ’);writeln(str[i])endend.⊡86


Data structuresExercise 4.22. Create a program that reads a string and draws it as a left-based pyramid. Forexample, the word computer must look like:croemtpu□This program consists of writing, at line i, the i-th char of the string preceded by a givennumber of blank spaces. The key is being able <strong>to</strong> 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 <strong>to</strong> discriminatebetween the first and the last half of the string.Program 103: Exercise 4.22program c04e22;uses math;constN=15;varstr: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 <strong>to</strong> length(str) dobeginfor j:=1 <strong>to</strong> min(i-1,length(str)-i) dowrite(’ ’);writeln(str[i])endend.⊡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:computer□In order <strong>to</strong> display this structure we have <strong>to</strong> realize that, between each pair of chars, we need<strong>to</strong> put blank spaces. Hence, again it becomes a problem of epi<strong>to</strong>mizing the number of blankspaces depending upon the number of the row we are in. First, we have <strong>to</strong> decide how manyblank spaces must be written before the first char, and then how many before the second. On87


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming Languagethe leftmost part of the i-th line we have <strong>to</strong> include as many as i − 1 blank spaces. Then, afterthe first char we have <strong>to</strong> 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.23program c04e23;uses math;constN=15;varstr: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 <strong>to</strong> ceil(length(str)/2) dobeginfor j:=1 <strong>to</strong> min(i-1,length(str)-i) dowrite(’ ’);write(str[i]);for j:=1 <strong>to</strong> length(str)-(2*i) dowrite(’ ’);if (abs( (i-1)-(length(str)-i))-1)>=0 thenwriteln(str[length(str)-i+1])elsewritelnendend.⊡Exercise 4.24. Create a program that reads a string and draws it as a bot<strong>to</strong>m-based pyramid.For example, the word computer must look like:computer□We can understand this problem as a derivation of the preceding one. Indeed, we can achievethe solution by tweaking the value of the variable used in the outer for iterative construction,and changing the <strong>to</strong> clause by down<strong>to</strong>.Program 105: Exercise 4.24program c04e24;uses math;constN=15;varstr:STRING[N];i,j:integer;begin(* Reading the string *)88


Data structureswrite(’Please input the string of, at most, ’,N,’ chars: ’);readln(str);(* Writing the matrix *)for i:=ceil(length(str)/2) down<strong>to</strong> 1 dobegin(* Write the leftmost blank spaces + first char *)for j:=1 <strong>to</strong> min(i-1,length(str)-i) dowrite(’ ’);write(str[i]);(* Write the middle *)for j:=1 <strong>to</strong> abs( (i-1)-(length(str)-i))-1 dowrite(’ ’);(* 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 thenwriteln(str[length(str)-i+1])elsewritelnendend.⊡Exercise 4.25. Create a program that reads a string and draws it twice with cross diagonals. Forexample, the word computer must look like:croemtpu□This exercise is tackled here as a combination of the previous two. Note that, in order<strong>to</strong> produce a more compact solution, we write everything inside the same for. Hence, somesmall changes have <strong>to</strong> be performed in the definition of the limits of each of the for iterativeconstructions.Program 106: Exercise 4.25program c04e25;uses math;constN=15;varstr: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 <strong>to</strong> length(str) dobeginfor j:=1 <strong>to</strong> min(i-1,length(str)-i) dowrite(’ ’);pum<strong>to</strong>ecr89


A Practical Introduction <strong>to</strong> <strong>Pascal</strong> Programming Languagewrite(str[i]);for j:=1 <strong>to</strong> abs((i-1)-(length(str)-i))-1 dowrite(’ ’);if (abs((i-1)-(length(str)-i))-1>=1) thenwriteln(str[i])elsewritelnendend.⊡90

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!