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.

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

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

Saved successfully!

Ooh no, something went wrong!