Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Reid G.C.Thinking in PostScript.1990.pdf
Скачиваний:
17
Добавлен:
23.08.2013
Размер:
846.44 Кб
Скачать

Example 8.10: Exiting a Loop

/fd (/user/glenn/Book/current/pictures/test.eps) (r) file def /buff 128 string def

/Helvetica 10 selectfont 20 130 moveto

{ %loop

fd buff readline { %else gsave show grestore 0 -12 rmoveto

}{ fd closefile exit } ifelse

}bind loop

CONCLUDING THOUGHTS

In this chapter you have seen many different situations for loops, some of which use data, some of which use instructions, and some of which are simply executed until it is determined that they are done. It is up to you to decide which of the looping operators is best suited for your needs, and to use it appropriately. In the next chapter you will see how to construct and use procedures in your programs.

EXERCISES

1. Rewrite the following C program segment in PostScript.

main ()

{

long factorial; int index; factorial = 1;

for ( index = 10; index > 0; index-- )

{

factorial = factorial * index;

}

printf ( “10 factorial is %d\n”, factorial );

}

2.Rewrite the following PostScript code fragment using a repeat loop. Don’t worry about manufacturing the data inside the loop, just use the data directly from the operand stack.

Chapter 8: USING LOOPING CONSTRUCTS

103

0 0 moveto

100 200 lineto

200 200 lineto

300 400 lineto

400 400 lineto

500 600 lineto

600 600 lineto closepath fill

3.Write a loop that takes a single string on the operand stack, counts the number of spaces in the string, and returns the string and an integer count of spaces back on the operand stack when finished. For this exercise, use the search, loop, and exit operators.

4.Rewrite the above exercise using the forall operator instead of search and loop.

5.Find the bugs in the following program (there are at least two or three of them). The program should print a grid of 20 lines by 10 lines.

% draw a grid of 20 x 10 lines save

0.1 setlinewidth

20 20 translate

0 10 200 { %for

dup 0 moveto 0 100 rlineto

}for stroke

0 10 100 { %for

0 1 index moveto 200 0 rlineto

}for

stroke restore

104

Chapter 8: USING LOOPING CONSTRUCTS