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.

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

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

Saved successfully!

Ooh no, something went wrong!