COE 212 Final, Spring 2011
Lebanese American University · Engineering Programming · 15 pages · Dr. Wissam Fawaz
Showing the first 10 of 15 pages. Download the PDF to see all of it.
More COE 212 files
- Final · Fall 2016Final examView
- Exam Final Exam · Fall 2015Final examView
- Final Exam · Spring 2013Final examView
- Final · Spring 2013Final examView
- Final · Spring 2013Final examView
- Problems Final · Spring 2013Final examView
- Final + Solutions · Spring 2012Final exam · with solutionView
- Final · Fall 2012Final examView
Show the text of this final exam
COE 211/COE 212 – Computer
Programming/Engineering Programming
Welcome to
The Comprehensive Final Exam
Monday May 30 2011
Instructor: Wissam F. Fawaz
Maurice J. Khabbaz
Name: __Solution Key___________
Student ID: ________________
Instructions:
1. This exam is Closed Book. Please do not forget to write your
name and ID on the first page.
2. You have exactly 150 minutes to complete the 7 required
problems and the one bonus problem.
3. Read each problem carefully. If something appears
ambiguous, please write your assumptions.
4. Do not get bogged-down on any one problem, you will have
to work fast to complete this exam.
5. Put your answers in the space provided only. No other spaces
will be graded or even looked at.
Good Luck!!
1
Problem 1: Arrays (40 minutes) [30 points]
For each question choose the single right answer.
1)
Which of the following statements will assign to the third command line argument a value of
“NJ”?
a.
args[1] = “NJ”;
b. args[2] = “NJ”;
c.
args[3] = “NJ”
d.
None of the above
In what follows, assume that states is a two dimensional array of Strings that is filled up to
capacity with the following values:
2)
What is returned by states[3][2]?
a.
“TX”
b.
“MI”
c.
“OH”
d.
None of the above
3)
What is the value of states.length?
a.
3
b.
12
c.
4
d.
None of the above
4)
The statement System.out.println(states[4][2]); will
a.
output AUB
b.
output BAL
c.
cause an ArrayOutOfBoundsException to be thrown
d.
None of the above
5)
What is returned by
states[states.length-2][states.length-2].length()?
a.
2
b.
4
c.
12
d.
None of the above
6)
Which of the following statements can be used to declare states?
a.
String[][] states = new String[3][2];
b.
String[][] states = new String[4][3];
c.
String[][] states = new String[2][3];
d.
String[][] states = new String[3][4];
7)
What is returned by
states[1][1].charAt(1)?
a.
‘A’
b.
‘L’
c.
‘M’
d.
None of the above
2
states
AL
CA
HI
FL
MA
MI
MN
TX
NY
NC
ND
OH
int[] zip = new int[4];
zip[0] = 7;
zip[1] = 1;
zip[2] = 4;
int j = zip[1];
System.out.println(zip[j+1]+zip[3]);
int[] data = {0, 3, 7, 9, 12, 14};
System.out.println(data[data[1]]);
int[] arr = new int[5];
int j = 2;
arr[0] = 4;
arr[1] = 5;
arr[2] = 6;
arr[3] = 7;
int j = arr[j];
System.out.println(arr[(int)Math.floor((j+1)/2.0)]);
8)
What is the output of the following code fragment
a.
5
b.
7
c.
4
d.
None of the above
9)
What output does the following code fragment produce?
a.
7
b.
9
c.
12
d.
14
10) What is output of the following code fragment
a.
5
b.
7
c.
4
d.
None of the above
Fill in the values for the array called world after the corresponding Java
code has run. You must enter your final answers into the boxes provided.
Example: int [] world = new int[4]; Answer:
for (int j=0; j<4; j++)
world[j] = j;
3
world
0 1 2 3
11) final int SIZE = 6;
int[] world = new int[SIZE];
for (int i=0; i < world.length; i++) {
world[i] = (i+1)*(i+2)/2;
}
12) final int XMAX = 3, YMAX = 3;
int[][] world = new int [XMAX][YMAX];
int goali = 1, goalj = 1;
for (int i=0; i < XMAX; i++) {
for (int j=0; j < YMAX; j++) {
int idist = Math.abs(i – goali);
int jdist = Math.abs(j – goalj);
world[i][j] = idist + jdist;
}
}
13) int[][] A = {{1, 2, 3},{4, 5, 6}};
int[][] world = new int[A[0].length][A.length];
for (int i=0; i<A.length; i++)
for (int j=0; j<A[0].length; j++)
world[j][i] = A[i][j];
14) int[][] GPA = {{4, 4, 4}, {2, 4, 3}, {1, 2, 3}};
int student = 3;
int courses = 3;
int[] studentGPA = new int[student];
for(int j=0; j < student; j++)
for(int i=0; i < courses; i++)
studentGPA [j] += GPA[j][i];
double[] world =new double[student];
for (int k=0; k < student; k++)
world [k] = studentGPA [k]/courses;
4
world
Answer:
world
Answer:
2 1 2
1 0 1
2 1 2
1 3 6
10 15 21
Answer: world
4
5
6
1
2
3
Answer: world
4.0 3.0 2.0
Problem 2: Inheritance (10 minutes) [10 points]
For each question choose the single right answer.
1)
Inheritance establishes a(n):
a.
uses relationship
b.
has-a relationship
c.
is-a relationship
d.
this relationship
2)
Which of the following represents a generic concept in a class hierarchy?
a.
An interface
b.
A class declared as abstract
c.
A class declared as final
d.
None of the above
3)
Which of the following statements is false about constructors?
a.
Constructors are not inherited
b.
Constructors have no return type
c.
Constructors can be invoked by the child class using super.ConstructorName( )
d.
A child class invokes the parent’s constructor to initialize all inherited variables
4)
Method overriding
a.
Occurs when a class defines 2 methods with same name but with different signatures
b.
Occurs when a parent class is not sure about a method definition so it leaves the
definition for the child class
c.
Occurs when a child class defines a method with the same name and signature as a
method in the parent class
d.
None of the above
5)
Which of the following statements declares Salaried as a subclass of PayType?
a.
public class Salaried implements PayType
b.
public class Salaried derivedFrom(PayType)
c.
public class PayType extends Salaried
d.
None of the above
6)
If class A is derived from Class B, then
a.
Public and private members of B can be used in A
b.
Public members in B can be used in A, but protected members cannot be accessed in A
c.
Neither public nor private members in B can be directly referenced in A
d.
None of the above
7)
All Java classes are subclasses of which of the following classes
a.
String
b.
Class
c.
Wrapper
d.
None of the aboves
8)
Which of the following methods is included in every class created in Java?
a.
compareTo
b.
equals
c.
charAt
d.
None of the above
9)
Consider the following statement: super(); This statement
a.
calls the method super defined in the current class
b.
calls the method super as defined in java.lang
c.
calls the constructor as defined in the current class
d.
calls the constructor as defined in the parent of the current class
10)
When designing a class hierarchy, it is important that common features be kept
a.
higher in the class hierarchy
b.
lower in the class hierarchy
c.
near the middle of the class hierarchy
d.
in the Object class
5
Problem 3: True or false (10 minutes) [10 points]
1. A method can return only primitive values (int, double, boolean, etc…).
Answer: True False
2. In Java, an array can store only one type of data. For instance, you cannot create
an array that stores both double and String values
Answer: True False
3. The compareTo() method returns a negative value if the string through which
it is invoked follows the string passed in as a parameter.
Answer: True False
4. If a program attempts to access an element outside of the range of the array
indexes, a compile time error occurs.
Answer: True False
5. The following do-while loop is an infinite loop
int x=10;
do{ x*=20 } while(x > 5);
Answer: True False
6. Given the following method definition:
int triArea(int width, int height) {
int area = width * height;
return area/2;}
After the following statement executes: double x=triArea(5,7); x will
hold a value of 17.5
Answer: True False
7. After the following code has been executed:
int x=10;
for(int y=5; y<20; y+=5)
x+=y;’
x will end up storing a value of 40
Answer: True False
8. The string Hello gets printed 40 times after the following code is executed:
for(int i = 0; i < 8; i+=2)
for (int j=1; j<=10; j++)
System.out.println(“Hello”);
Answer: True False
9. A child class is allowed to define a method with the same name and parameter list
as a method in the parent class
Answer: True False
10. Once a method is overridden in a child class, the original version can never be
referenced from the subclass
Answer: True False
6
Problem 4: Method definition (15 minutes) [8 points]
You are given below the headers of 4 methods called cube, countA,
beginsWithVowel, and reverse. Your job is to complete the definition
of each one of these methods as per the provided guidelines.
1. cube is a method that accepts one integer parameter called val and
that returns the value of val raised to the third power.
public int cube(int val) {
return Math.pow(val,3);
}
2. countA is a method that accepts a String parameter and returns the
number of times the letter ‘A’ appears in the String.
public int countA(String word) {
int counter;
for (int i = 0; I < word.length()-1; i++)
if (word.charAt(i) == ‘A’ ||
word.charAt(i) == ‘a’)
counter ++;
return counter;
}
3. beginsWithVowel is a 1-parameter method that indicates whether the
word passed as a parameter begins with a vowel.
public boolean beginsWithVowel(String word) {
char c = word.charAt(0);
if (c == ‘a’ || c == ‘i’ || c == ‘o’
|| c == ‘u’ || c == ‘e’)
return true;
else
return false;
}
4. reverse is a method that accepts as a parameter a String called
str and returns a new String that contains the characters of str
in reverse order.
public String reverse(String str) {
string str1 = “”;
for (int i = str.length()-1; i>=0; i--)
str1 += str.charAt(i);
return str1;
}
7
Problem 5: Completing code fragments (25 minutes) [10 points]
(1)Assume that values is a 102-element array containing a list of
integer values, as declared on the third line of the Java code presented
below.
Add Java statements that would complete the program below to
compute the average of the non-zero even values as well as the
average of the odd values found in the values array. Then complete
the code to print out the two computed averages out.
public class ComputeAvgs {
public static void main(String[] args) {
double[] values = new double [101];
// Assume that we loaded the array with the
// appropriate values.
// Write below a one-line statement to declare
// and initialize the variables called
// avgOdd, avgEven, numOdd, and numEven.
double avgOdd=0, avgEven=0, numOdd=0, numEven=0;
// Complete the code below to count the number of
// even/odd numbers and compute their respective
sums.
for(int i=0; i<values; i++) {
if (values[i]%2 == 0) {
avgEven += values[i];
numEven++;
}
else
if (values[i] != 0) {
avgOdd += values[i];
numOdd++;
}
} // end for loop
// Compute the averages below.
avgEven /= numEven;
avgOdd /= numOdd;
// Print the averages out.
System.out.println(“Avg of odd vals:”+ avgOdd);
System.out.println(“Avg of even vals:”+ avgEven);
}// end main
}// end ComputeAvgs
8
Problem 5 continued:
(2) Below is given a class named LibraryItem. A library item has a title.
public class LibraryItem {
private String title;
public LibraryItem(String t) {title = t;}
public String getTitle() {return title;}
public String toString() {
return “Title: ” + title;
}}
Complete the partial definition given below for a subclass called Book derived
from the LibraryItem class. Note that a book object also has an author and a
checkout period (a number of days). Complete the constructor, equals, and
toString methods as noted by comments highlighted in bold.
public class Book extends LibraryItem{
// instance variable representing author and check out
// period goes below
public String author;
private int checkout;
// constructor must invoke the constructor of parent
// class using the super reference.
public Book(String theTitle, String theAuthor, int
checkOutPeriod) {
super(theTitle);
author = theAuthor;
checkout = checkOutPeriod;
}
// A method that returns the name of author
public String getAuthor () {
return author;
}
public boolean equals(Object other) {
// two books are equal if they have the same
// title and the same author.
return (((Book)
other.getTitle())).equals(other.getTitle()) &&
author.equals(other.getAuthor());
}
public String toString ( ) {
//Invoke the LibraryItem’s version of toString
// and then concatenate the author to returned String.
return super.toString() + “, Author: “ + author;
}}
9
Problem 6: Writing code segments (10 minutes) [7 points]
Write each of the Java code segments requested below.
Example: write a one-line statement declaring a string storing your name.
Answer: String name = “wissam”;
a) Write a one-line statement declaring and creating a one-dimensional
array called grades to store the grades obtained on 5 courses.
int[] grades = new int[5];
b) Write a one-line statement to define the header of a method called
average that accepts a variable length parameter list of integers.
double average (double… list)
c) Write a one-line statement declaring, creating, and initializing an
array of temperatures called temps containing the numbers 67.5,
73.4, and 81.0
double temps = {67.5, 73.4, 81.0};
d) Write one or more Java statements to print each character found in
the string stored in a variable called word on a separate line.
for (int i=0; i<word.length(); i++)
System.out.println(word.charAt(i));
e) Write a code segment to define a method called perim that receives
the lengths of 3 sides of a triangle and returns its perimeter.
public int perim (int a, int b, int c) {
return a+b+c;
}
f) Write one or more Java statements to print all the grades stored in
the array temps (from part (c)) in reverse order.
for (int i=temp.length()-1; i>=0; i--)
System.out.print(temps[i] + “ “);
g) Write one or more Java statements to print the smallest number in
the int[][] nums = new int[99][100] 2-dimensional array.
int min = nums[0][0];
for (int i = 0; i<nums.length; i++)
for (int j = 0; j < nums[i].length; j++)
min = (nums[i][j] < min) ?
nums[i][j]:min;
10
Problem 7: Coding (40 minutes) [25 points]
1. The harmonic mean of two numbers is given by
Write a program that reads two numbers (as integers) from the keyboard and prints
out both the usual average (i.e., arithmetic mean) and the harmonic mean.
2. Design and implement an application that determines and prints the number of
odd, even, and zero digits in an integer value read from the end user.
Sample output:
Enter an int value: 1024
Number of zeros in entered value: 1
Number of odd digits in entered value: 1
Number of even digits in entered value: 2
11
3. Design and write a Java application that takes as input an integer larger than 1 and
prints the sum of the squares from 1 to that integer. For example, if the integer
equals 4, then the value that should be printed out is 30, which is the sum of
squares between 1 and 4 (i.e., 1+4+9+16).
4. Design and write a Java application that takes as input an integer x that is larger
than 2 and prints the even numbers between 2 and x. For example, if x equals 9,
then the following values should be printed out: 2 4 6 8.
12
5. Design and implement an application that reads a string from the user, then
determines and prints how many of each lowercase vowel (a, e, i, o, and u) appear
in the entire string.
6. Design and implement an application that determines and prints the first 20
numbers of a Fibonacci sequence. Each number is formed by adding previous 2
numbers. Assume that the first two numbers are 0 and 1.
13
14
Problem 8: Bonus [10 points]
Design and implement a complete JAVA application that will read a sequence of 1-digit
(0 – 9) numbers from a file called inNums.txt and store these numbers in a String
called str. Once done, your program must scan through str and count how many times
each number has occurred. Your program must print a histogram in such a way to allow
the user to visually inspect the frequency distribution of the numbers. To do so, each
number is going to be printed followed by its corresponding frequency count and finally
this count printed out in stars. An example output follows:
Sequence of numbers: 1 3 5 0 0 1 5 5
Histogram:
Number 0: 2 | **
Number 1: 2 | **
Number 2: 0 |
Number 3: 1 | *
Number 4: 0 |
Number 5: 3 | ***
15