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 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

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

Saved successfully!

Ooh no, something went wrong!