CS 0007 Exam 2 Name: __________________________


11/22/1999


Part 1: Program Segment Questions


1. (25 points)


Write a procedure called sort that sorts an array of 20 integers in ascending order using the selection sort algorithm. You’ll also need to write a swap procedure, defined within the sort procedure. Make sure you pass parameters correctly.

procedure sort(var list:array[1..20] of integer);

var

i,j,lowvalue,lowindex:integer;

procedure swap (var a,b:integer);

var

c:integer;

begin

c:=a;a:=b;b:=c;

end;

begin

for i:=1 to 20 do

begin

lowvalue:=maxint;

for j:=i to 20 do

if list[j]<lowvalue then

begin

lowvalue:=list[j];

lowindex:=j;

end;

swap (list[i],list[lowindex]);

end;

end;


2. (25 points)


Write a complete program that does nothing but continuously reads lines of characters (strings) from the user and writes each line to a text file called myfile after the user presses enter. The program must terminate when the user hits enter on a blank line.

program myprogram (input,output,myfile);

var

myfile:text;

str:array[1..80] of char;

begin

rewrite (myfile);

repeat

readln (str);

writeln (myfile,str);

until str=’’;

end.


3. (25 points)


Write a function called readintegers that reads all the integers from a text file called myfile (use readln()) and returns the sum of the integers as an integer. Note: (1) this function takes no parameters, (2) is responsible for opening the file for reading, and (3) assume myfile is in the program header line and declared globally as text.

function readintegers:integer;

var

tally,num:integer;

begin

reset (myfile);

tally:=0;

while not eof(myfile) do

begin

readln (myfile,num);

tally:=tally+num;

end;

readintegers:=tally;

end;

 

 

 

 

 

 

 

 

 

 

 

 

 

 


4. (25 points)



Write a function called findinteger that takes an array of 1000 unique integers by variable and a single integer by value and searches the array for the integer. If the integer is found, the function returns the index where it was found. If the integer is not found in the array, the function returns –1.

function findinteger (var thearray:array[1..1000] of integer;find:integer):integer;

var

i:integer;

begin

findinteger:=-1;

for i:=1 to 1000 do

if thearray[i]=find then findinteger:=i;

end;