# [Snippet] Students

## Recommended Posts

Só porque sim, aqui vai a resolução de um exercício muito simples: ler 20 notas de alunos, registar num ficheiro, e depois calcular as positivas, negativas e média.

E só porque sim, na altura deu-me na cabeça fazer um código mais "ofuscado"

O que acham?

```{\$mode objfpc}
program students;
uses sysutils, strutils;

const DIM = 20;
FNAME = 'teste';
TAB = '    ';

type TArrayInt = array of smallint;
TFileInt = file of smallint;

n : smallint;

procedure FillArray(var arr : TArrayInt; dimension : longint; const prompt : string);
begin
setlength(arr, dimension-1);
for dimension := low(arr) to high(arr) do begin
write(AnsiReplaceText(prompt, '@{COUNT}', IntToStr(dimension)));
end;
end;

procedure CopyArrayToFile(const arr : TArrayInt; out f : TFileInt);
var elem : smallint;
begin
for elem in arr do
write(f, elem);
end;

procedure GetArrayFromFile(var f : TFileInt; out arr : TArrayInt);
var i : smallint = 0;
begin
seek(f,0);
SetLength(arr, FileSize(f));
while not eof(f) do begin
inc(i);
end;
end;

function CountPositive(arr : TArrayInt; const minimum : smallint = 0) : smallint;
var elem : smallint;
begin
CountPositive := 0;
for elem in arr do
if elem >= minimum then
inc(CountPositive);
end;

function CountPositive(var f : TFileInt; const minimum : smallint = 0) : smallint; overload;
var arr : TArrayInt;
begin
GetArrayFromFile(f, arr);
CountPositive := CountPositive(arr, minimum);
end;

procedure GetNegative(arr : TArrayInt; out neg : TArrayInt; const minimum : smallint = 0);
var elem : smallint;
begin
for elem in arr do
if elem < minimum then begin
SetLength(neg, length(neg)+1);
neg[length(neg)-1] := elem;
end;
end;

procedure GetNegative(var f : TFileInt; out neg : TArrayInt; const minimum : smallint = 0); overload;
var arr : TArrayInt;
begin
GetArrayFromFile(f, arr);
GetNegative(arr, neg, minimum);
end;

function Average(arr : TArrayInt) : real;
var elem : smallint;
begin
Average := 0.0;
for elem in arr do
Average := Average + elem;
Average := Average / length(arr);
end;

function Average(var f : TFileInt) : real; overload;
var arr : TArrayInt;
begin
GetArrayFromFile(f, arr);
Average := Average(arr);
end;

begin
writeln(TAB, n);
end.
```

• 2

Knowledge is free!

## Create an account

Register a new account

×

• #### Revista PROGRAMAR

• Wiki
• IRC
×
• Create New...