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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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

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

Saved successfully!

Ooh no, something went wrong!