Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
AnswerKey
CSC 1051 Algorithms and Data Structures I
Final Examination
May 2, 2015
Name:______________________________
Question Value
Score
1
10
2
10
3
10
4
10
5
10
6
10
7
10
8
10
9
20
TOTAL
100
Please answer questions in the spaces provided. If you make a mistake or for some
other reason need more space, please use the back of and clearly indicate where the
answer can be found.
Good luck and best wishes for a wonderful summer!
CSC1051 Data Structures and Algorithms I
Spring 2015
Dr. Papalaskari
AnswerKey
1.(________/10)Whatgetsprinted?
Pleaseshowoutputasitwillappear,orindicate“NOOUTPUT”,orshowsome
oftheoutputfollowedby“INFINITELOOP.”
Output:
4
int a = 5;
do
{
Done: 4
a--;
System.out.println(a);
}while (a >= 6)
System.out.println("Done: " + a);
for (int a = 4; a > 0; a++)
System.out.println(a * 2);
System.out.println("Done: " + a);
String[] notes = {"do", "re", "mi"};
for (String st: notes)
System.out.println(st + st);
System.out.println("Done: ");
for(int a = 1; a <= 3; a++)
for (int b = 5; b <= 6; b++)
System.out.println(a + "\t" + b);
System.out.println("Done");
CSC1051 Data Structures and Algorithms I
Spring 2015
Output:
8
10
12
14
… INFINITE LOOP
Output:
dodo
rere
mimi
Done
Output:
1
5
1
6
2
5
2
6
3
5
Dr.
3
6 Papalaskari
Done
AnswerKey
2.(________/10)
a) Show what gets printed and rewrite using if/else:
char ch = 'n';
System.out.print ("The answer is ");
switch(ch)
{
case 'y':
System.out.println ("positive.");
break;
case 'N':
System.out.println ("negative.");
break;
default:
System.out.println ("unclear.");
}
Output:
The answer is unclear.
Usingif/else:
char ch = 's';
System.out.print ("The answer is ");
if (ch == 'y')
System.out.println ("positive.");
else if (ch == 'N')
System.out.println ("negative.");
else
System.out.println ("unclear.");
2. Show what gets printed and rewrite using while and if/else (i.e., eliminate the
for and conditional operator):
for (int a = 0; a < 4; a++)
System.out.println(a + (a % 2 == 0? " yes ": " no "));
Output:
Usingwhileandif/else:
int a = 0;
while (a < 4)
{
System.out.print(a);
if (a % 2 == 0)
System.out.println(" yes");
else
System.out.println(" no");
a++;
}
CSC1051 Data Structures and Algorithms I
Spring 2015
0
1
2
3
yes
no
yes
no
Dr. Papalaskari
AnswerKey
3.(________/10)Considerthefollowingprogram:
import java.util.Scanner;
import java.io.*;
public class FinalS15FileIO
{
public static void main(String[] args) throws IOException
{
Scanner inFile;
PrintWriter outFile;
inFile = new Scanner (new File("data-in.txt"));
outFile = new PrintWriter("data-out.txt");
while (inFile.hasNext())
{
String line = inFile.nextLine();
Scanner scan = new Scanner(line);
int count = 0;
while (scan.hasNext())
{
String token = scan.next();
count ++;
}
outFile.println(count);
}
outFile.close();
}
}
a) Suppose the file data-in.txt is used as the input file. Show the contents of the
file data-out.txt after execution of the program.
b) List two examples of situations that could cause IOExceptions in the above code.
file not found for the Scanner – cannot do input
bad file name for the PrintWriter – cannot create the file
c) Suppose you want to catch and handle the IOExceptions using the following
catch clause:
catch (IOException e)
{
System.out.println("Warning: problem with IO. Run interactively.");
inFile = new Scanner(System.in);
outFile = new PrintWriter(System.out);
}
•
(i.e., keep running, but issue a warning and do interactive I/O instead)
Show how to incorporate this in the above program: 1) Draw a box around
the statements of the above program that you would include in the try block,
and 2) mark the position where you would insert the catch code.
CSC1051 Data Structures and Algorithms I
Spring 2015
Dr. Papalaskari
AnswerKey
4.(________/10) (a) WriteaJavamethodfindMax() withoneparameterthatisa
2Darrayofdouble,thatfindsandreturnsthelargestofallthevaluesinthe2D
array.Assumethatallthevalueswillbepositive.Theremayberepetitions,butit
shouldnotmatter,themethodshouldstillreturnavaluethatisnolessthananyof
theothervalues.Themethodshouldhaveoneparameter(the2Darrayofdouble)
anditshouldreturnadouble,andnotprintanything.
public static double findMax(double[][] array)
{
double max = 0;
for (int i = 0; i < array.length; i++)
for (int j = 0; j < array[i].length; j++)
if (array[i][j] > max)
max = array[i][j];
return max;
}
(b) Assume findMax() is defined as a static method in the class below. Complete the
code of main() below to use findMax so as to print the largest of the numbers stored
in either of the arrays a and b (i.e., the largest number overall).
public class ThisIsATest
{
public static void main(String[] args)
{
double[][] a = ...
(arraysareinitializedwithsomevalues)
double[][] b = ...
//**** print the largest value stored in either a or b
double amax = findMax(a);
double bmax = findMax(b);
if (amax > bmax)
System.out.println(amax);
else
System.out.println(bmax);
}
}
CSC1051 Data Structures and Algorithms I
Spring 2015
Dr. Papalaskari
AnswerKey
5. (________/10).(a) Show the output produced by the following code fragment:
String mess = "";
char[] grades = {'A', 'B', 'C', 'D', ’F'};
for (char ch: grades)
mess = ch + mess;
System.out.println (mess);
_____FDCBA__________________
(b) Show the output produced by the following code fragment:
char[] grades = {'A', 'B', 'C', 'D', ’F'};
for (char ch: grades)
System.out.print ((char) (ch + 1));
_____BCDEG__________________
(c) Suppose an int array ratings contains values in the range 0-3. Write a code
fragment that creates an array count that contains the frequency of occurrences of 0’s,
1’s, 2’s and 3’s in the ratings array, and then prints this information.
Example: if the array ratings has these contents:
ratings
0
1
2
3
4
5
6
2
3
2
1
0
2
2
Your code should create the array count with the following contents:
count
0
1
and the output would be:
Count
Count
Count
Count
for
for
for
for
0:
1:
2:
3:
1
1
2
3
4
1
1
1
4
1
Write your code fragment below. Assume the array ratings is already initialized to
some values. Your code should work for any size array.
int[] count = new int[4];
for (int x: ratings)
count[x]++;
CSC1051 Data Structures and Algorithms I
Spring 2015
Dr. Papalaskari
AnswerKey
6.(________/10) SupposeyouhaveaDieclassdefinedasfollows:
import java.awt.*;
public class Die
{
private int faceValue;
// current value showing on the die
// Constructor: Sets the initial face value.
public Die()
{
faceValue = 1;
}
// Rolls the die and returns the result.
public int roll()
{
faceValue = (int)(Math.random() * 6) + 1;
return faceValue;
}
// Face value mutator.
public void setFaceValue (int value)
{
faceValue = value;
}
ç
Writeyour
answeron
facingpage
(backof
previous
page).
ç
Answerkey
onnext
pageèè
// Face value accessor.
public int getFaceValue()
{
return faceValue;
}
// Returns a string representation of this die.
public String toString()
{
String result = Integer.toString(faceValue);
return result;
}
// Draws the die on page at position x, y.
public void draw (Graphics page, int x, int y)
{
page.setColor (Color.white);
page.fillRect (x, y, 30, 30);
page.setColor (Color.black);
page.drawString(Integer.toString(faceValue), x+10, y+20);
}
}
Onthefacingpage,writetheJavacodeforadriverclassthatusestheDieclasstodetermine
howlikelyitistoroll“snakeeyes”,i.e.,twoones.Usethefollowingapproach:
Ø DeclareandinstantiatetwoDieobjects,die1anddie2
Ø Rollthem10,000times(orsomesufficientlylargenumber,specifiedbyaconstantin
yourprogram)whilekeepingtrackofhowmanytimesyourolledonesonbothdice
Ø Intheend,printhowmanytimesthedicewererolled,thenumberofsnakeeyes,and
proportionofsnakeeyes(i.e.,probability).Careful:useacastwhendividingintegers!
CSC1051 Data Structures and Algorithms I
Spring 2015
Dr. Papalaskari
AnswerKey
public class SnakeEyes
{
public static void main(String[] args)
{
final int NUM_TIMES = 10000;
Die die1 = new Die();
Die die2 = new Die();
int snakes = 0; // counter for snake eyes
for (int i = 0; i < NUM_TIMES; i++)
{
die1.roll();
die2.roll();
if (die1.getFaceValue() == 1 &&
die2.getFaceValue() == 1)
snakes ++;
}
System.out.println("The dice were rolled " +
NUM_TIMES);
System.out.println("There were " + snakes +
" snake eyes.");
System.out.println("Approximate probability of " +
"getting snake eyes: " +
((double) snakes/ NUM_TIMES));
}
}
CSC1051 Data Structures and Algorithms I
Spring 2015
Dr. Papalaskari
AnswerKey
7.(________/10) Supposeyouhavea Passenger classdefinedasfollowsto
representpassengersintheTitanic:
public class Passenger
{
// instance data
private int status;
private boolean child;
private char sex;
private boolean survivor;
// constructor
public Passenger(int status, boolean child, char sex, boolean survivor)
{
this.status = status;
this.child = child;
this.sex = sex;
this.survivor = survivor;
}
// toString() – returns String description of Passenger
public String toString()
{
String pass = "";
switch (status)
{
case 1: pass += "1st class\t"; break;
case 2: pass += "2nd class\t"; break;
case 3: pass += "3rd class\t"; break;
case 4: pass += "crew\t"; break;
}
pass += (child? "child": "adult") + "\t";
pass += ((sex == 'm') ? "male" : "female") + "\t";
pass += (survivor? "survived": "perished");
return pass;
}
}
Onthenextpage,writethecodeforaPassengerCollectionclasstorepresentthe
listofpassengersoftheTitanicandtokeeptrackoftotalnumberofpassengersand
survivors,usinganarrayofPassengerobjects.Somebitsofthecodeandcomments
arealreadywritten.Usethesecommentsasguidelinesforyourcode,inthespaces
providedonthenextpage.Notethatyouonlyneedtoimplementtheconstructorand
addPassenger()methods,whichshouldinitializeandupdate,respectively,thearray
andthetwocounts(i.e.,countandnumSurvivors).
CSC1051 Data Structures and Algorithms I
Spring 2015
Dr. Papalaskari
AnswerKey
(Question 7, continued)
public class PassengerCollection
{
private Passenger[] collection;
private int count;
private int numSurvivors; // additional count: survivors
//-----------------------------------------------------// Constructor: Creates an initially empty collection
//
with space for up to 5000 passengers.
//
Initializes count and numSurvivors appropriately.
//------------------------------------------------------
public PassengerCollection ()
{
collection = new Passenger[5000];
count = 0;
numSurvivors = 0;
}
//-----------------------------------------------------// Method addPassenger(): Adds a Passenger to the
//
collection. Update
//
count and numSurvivors.
//-----------------------------------------------------public void addPassenger (int status, boolean child,
char sex, boolean survivor)
{
collection[count] =
new Passenger(status, child, sex, survivor);
count++;
if (survivor)
numSurvivors++;
}
CSC1051 Data Structures and Algorithms I
Spring 2015
Dr. Papalaskari
AnswerKey
8.(________/10)
Constructanalgorithmthatinputsanintegernumand10,000otherintegersandprintsamessage
indicatingwhethernumwasfoundamongthe10,000otherintegers,followedbyagoodbyemessage.
Hint:Youneedtouseabooleanvariablefoundtokeeptrackofwhetheryoufoundamatch.
Example:Ifnum(i.e.,thefirstnumberinput)is1318,and10,000othernumbersareinputafterthat,
noneofwhichisequalto1318,thealgorithmshouldprint:
Searching for 1318
Not found
Goodbye
Alternatively,ifthenumber1318occurredoneormoretimesamongtheothernumbers,itshouldprint:
Searching for 1318
Found it!
Goodbye
Directions:
Writeyouralgorithmbyrearrangingandstructuringelementschosenfromthelistbelow,using
indentationtoshowstructure.Donotuseanythingelseandnotethatnotalloftheseareneeded,but
youmayuseoneofthemmorethanonce,ifnecessar
found=true
else
found=false
while(count<=10000)
inputnum
while(num<=10000)
inputx
while(count<=num)
count=1
print“Searchingfor”num
count=count+1
printx
x=x+1
printnum
if(x==num)
print“Foundit!”
if(found)
print“Notfound”
if(found==true)
print“Goodbye”
if(found==false)
if(x!=num)
inputnum
found=false
count=1
while(count<=10000)
inputx
if(x==num)
found=true
count=count+1
if(found==true)
print“Foundit!”
else
print“Notfound”
print“Goodbye”
CSC1051 Data Structures and Algorithms I
Spring 2015
Dr. Papalaskari
AnswerKey
9.(________/20) WriteacompleteJavaprogramconsistingofadatatypeCat
andaclientCrazyCatLadyanddrawaUMLclassdiagramforyourclasses.
Ø Name: Henri
Example:
Ø Age: 7
Ø Lives: 5
a)TheCatclassshouldhavethefollowingmethods:
• Constructor:Oneparameter(forthename).SetsCat’sageto0andlivesto9.
• birthday():increasesageofCatby1.
• death():decreasestheCat’snumberoflivesby1.
• toString():returnsaStringcorrespondingtothisCat.
• getAge():returnsthisCat’sage
• draw(Graphics page, int x, int y):drawsthisCatinthecurrent
Graphicscontextatpositionx, y. Pleasedonotdoanythingfancyhere:
justdrawasimpleshapetorepresentthecatandadditsnamenearby.Add
anotherfeaturesuchascolorordifferentshapetodepicttheageornumberof
lives(youonlyneedtodooneofthem).
b)TheclientCrazyCatLadyshouldimplementthefollowingalgorithm:
o InstantiatethreevariablesoftheCatclassnamedcat1,cat2,cat3
(Kindlymakeupfunnynamesforthem–I’mspendingmyholidaysgradingthisexam!J)
o Printtheinfoof cat1,cat2,cat3
• Let’spretendthattwoyearshavegoneby…SotheCats’agesneedtoincrease.
Also, cat3hasdonesomethingstupidandlosesalife.Writesomecodethat
usesthebirthday() and death() methodstomodelthissituation.
o Printtheinfoof cat1,cat2,cat3(again).
o Calculateandprinttheaverageageofthecats.
o NOTE:thisisnotagraphicalclass,soitdoesNOTusethedraw()methodatall.
c)DrawaUMLclassdiagramdepictingtheclassesCatandCrazyCatLady.
WritethecompletecodeforthetwoclassesandUMLdiagraminthenext3pages.
ItisNOTnecessarytoincludecommentswithyourcode,butbesuretousegood
indentation.
èèè CSC1051 Data Structures and Algorithms I
Spring 2015
Dr. Papalaskari
AnswerKey
public class Cat
{
private int age;
private int lives;
private String name;
// Constructor: One parameter (for the name).
//
Sets Cat's age to 0 and lives to 9.
public Cat(String name)
{
this.name = name;
age = 0;
lives = 9;
}
// birthday(): increases age of Cat by 1.
public void birthday()
{
age++;
}
// death(): decreases the Cat's number of lives by 1.
public void death()
{
lives--;
}
// toString(): returns a String corresponding to this Cat.
public String toString()
{
return (name + ", Age: " + age + ", Lives: " + lives);
}
// getAge(): returns this Cat's age
public int getAge()
{
return age;
}
// draw(): draws this Cat on page at position x, y
public void draw(Graphics page, int x, int y)
{
page.setColor(age < 5? Color.black: Color.gray);
page.fillOval(x, y);
page.setColor(Color.red);
page.drawString(name, x, y);
}
}
CSC1051 Data Structures and Algorithms I
Spring 2015
Dr. Papalaskari
AnswerKey
public class CrazyCatLady
{
public static void main(String[] args)
{
//Instantiate 3 variables of the Cat class named cat1, cat2, cat3
Cat cat1 = new Cat("Macavity");
Cat cat2 = new Cat("Mungojerrie");
Cat cat3 = new Cat("Rumpelteazer");
// print info on cats
System.out.println(cat1);
System.out.println(cat2);
System.out.println(cat3);
// Let's pretend that two years have gone by…
// So the Cats' ages need to increase.
cat1.birthday();
cat2.birthday();
cat3.birthday();
cat1.birthday();
cat2.birthday();
cat3.birthday();
// Also, cat3 has done something stupid and loses a life.
cat3.death();
// print info on cats
System.out.println(cat1);
System.out.println(cat2);
System.out.println(cat3);
// Calculate and print the average age of the cats.
System.out.println( "Average feline age: " +
(double) (cat1.getAge() + cat2.getAge() + cat3.getAge()) / 3 );
}
}
CSC1051 Data Structures and Algorithms I
Spring 2015
Dr. Papalaskari
AnswerKey
Cat
CrazyCatLady
name: String
age: int
lives: int
main(args: String[]): void
birthday(): void
death(): void
toString: String
getAge(): int
draw(p: Graphics, x:int, y:int): void
CSC1051 Data Structures and Algorithms I
Spring 2015
Dr. Papalaskari
AnswerKey
CSC1051 Data Structures and Algorithms I
Spring 2015
Dr. Papalaskari
AnswerKey
CSC1051 Data Structures and Algorithms I
Spring 2015
Dr. Papalaskari
AnswerKey
CSC1051 Data Structures and Algorithms I
Spring 2015
Dr. Papalaskari