Page 0
German University in Cairo June 17, 2023
Media Engineering and Technology Faculty
Prof. Dr. Slim Abdennadher
Assoc. Prof. Milad Ghantous
Dr. Mohamed Hamed
CSEN 202: Introduction to Computer programming
Spring Semester 2023
Final Exam
Bar Code
Instructions: Read carefully before proceeding.
1) Please tick your major
Major
Engineering
BI
2) Duration of the exam: 3 hours (180 minutes).
3)No books or other aids are permitted for this test.
4) This exam booklet contains 18 pages, including this one. Three extra sheets of scratch paper are attached
and have to be kept attached. Note that if one or more pages are missing, you will lose their points. Thus,
you must check that your exam booklet is complete.
5) Write your solutions in the space provided. If you need more space, write on the back of the sheet containing
the problem or on the three extra sheets and make an arrow indicating that. Scratch sheets will not be
graded unless an arrow on the problem page indicates that the solution extends to the scratch sheets.
6) When you are told that time is up, stop working on the test.
Good Luck!
Don’t write anything below ;-)
Σ
Exercise 1 2 3 4 5 6 7
Possible Marks 16 12 10 12 10 32 8 100
Final Marks
CSEN 202: Introduction to Computer programming, Final Exam, June 17, 2023 Page 1
Exercise 1 (10+6=16 Marks)
a) Write an iterative Java method named minMaxResult. The method takes two parameters a and b. Both
parameters are arrays of integers. The method creates and returns an array of integers equal in length to the
longer of the two arrays passed as parameters.
Elements in even numbered indices in the resulting array should be equal the minimum value from the cor-
responding element in the two parameters.
Conversely, elements in odd numbered indices in the resulting array are equal to the maximum value from
the corresponding element in the two parameters.
Examples:
minMaxResult({-1, 10}, {2, 5, 6, -5}) -> returns {-1, 10, 6, -5}
Explanation: The resulting array’s length is 4. -1 is the minimum among
{-1,2}, 10 is the maximum among {10,5} and so on.
minMaxResult({-1, 5, 10}, {2, 4, 6}) -> returns {-1, 5, 6}
minMaxResult({}, {2, 4, 6}) -> returns {2, 4, 6}
minMaxResult({-1, -1, -5, 3}, {-1, -1, -5}) -> returns {-1, -1, -5, 3}
minMaxResult({}, {}) -> returns {}
minMaxResult({},{10}) -> returns {10}
Solution:
// signature 1 mark
//initialization array with correct length 1.5
//for loop 1.5
// checking odd/even 1
// correct update 1.25 each
// adding rest of elements correctly 1.5
// return 1 mark
public static int[] minMaxResult(int[] a1, int[] a2)
{
int[] result = new int[a1.length > a2.length? a1.length: a2.length];
int minLength = a1.length < a2.length? a1.length: a2.length;
for(int i = 0; i < minLength; i++)
{
if(i % 2 == 0)
result[i] = a1[i] < a2[i] ? a1[i]: a2[i];
else
result[i] = a1[i] > a2[i] ? a1[i]: a2[i];
}
int[] rest = a1;
if(a1.length < a2.length)
rest = a2;
for(int i = minLength; i < result.length; i++)
result[i] = rest[i];
return result;
}
CSEN 202: Introduction to Computer programming, Final Exam, June 17, 2023 Page 2
Alternative solution:
public static int[] minMaxResult(int[] a, int[] b)
{
int[] res = new int[b.length > a.length ? b.length : a.length];
for (int i = 0; i < res.length; i++)
if (i < a.length && i < b.length)
{
if (i % 2 == 0)
res[i] = (a[i] < b[i]) ? a[i] : b[i];
else
res[i] = (a[i] > b[i]) ? a[i] : b[i];
}
else
res[i] = (i >= a.length) ? b[i] : a[i];
return res;
}
CSEN 202: Introduction to Computer programming, Final Exam, June 17, 2023 Page 3
b) Write a class called Tester that uses a command-line argument to test the method minMaxResult imple-
mented above.
Example:
> java Tester 2 4 -1 10 3 5 6 -5
-1 10 6 -5
Note: the 2 represents the length of the first array and the 4 represents the length of the second array, such
that the first array is {-1, 10} and the second is {3, 5, 6, -5}.
Solution:
//initialization arrays with correct length with parsing 0.75 each
//for loop 0.5 each
// populating array correctly while parsing 1.5 each
// calling method 0.5 mark
public class Tester
{
public static void main (String[] args)
{
int n = Integer.parseInt(args[0]);
int m = Integer.parseInt(args[1]);
int[] a = new int[n];
int[] b = new int[m];
int i=2;
for(int k =0; k<a.length; k++,i++)
a[k] = Integer.parseInt(args[i]);
for(int k =0; k<b.length; k++,i++)
b[k] = Integer.parseInt(args[i]);
int[] c = minMaxResult(a,b);
for(int j=0; j<c.length; j++)
System.out.print(c[j] + " " );
}
}
Alternative solution:
public static void main(String[] args) {
int[] a = new int[Integer.parseInt(args[0])];
int[] b = new int[Integer.parseInt(args[1])];
for (int i = 0; i < a.length; i++)
a[i] = Integer.parseInt(args[i + 2]);
for (int i = 0; i < b.length; i++)
b[i] = Integer.parseInt(args[i + 2 + a.length]);
display(minMaxResult(a, b));
}
CSEN 202: Introduction to Computer programming, Final Exam, June 17, 2023 Page 4
Exercise 2 (12 Marks)
Given an array of strings, write a Java method findMaxDifferencePair to find the two strings that have the
maximum length difference among all possible pairs of strings in the array. Display these two strings as a pair.
Example:
input: {"apple", "banana", "cherry", "date", "elderberry"}
output: "Max Difference Pair: date elderberry"
Solution:
// signature 1 mark
//initialization strings 0.5
// initiatization max difference 1
//for loop 1.5 each
// difference 1.5
// update strings 1 each
// print 1
public static void findMaxDifferencePair(String[] strings) {
String s1 = “”;
String s2 = “”;
int maxDifference = Integer.MIN_VALUE;
for (int i = 0; i < strings.length - 1; i++) {
for (int j = i + 1; j < strings.length; j++) {
int difference = Math.abs(strings[i].length() -
strings[j].length());
if (difference > maxDifference) {
maxDifference = difference;
s1 = strings[i];
s2 = strings[j];
}}}
System.out.printlm( "Max Difference Pair: “ + s1 + “ “ + s2);
}
Alternative solution:
// signature 1 mark
//initialization strings 1
// initiatization max and min 1
//for loop 2
// conditions 1 each
// update max and min 1 each
// return 1
public static void findMaxDifferencePair(String[] strings) {
String s1 = strings[0];
String s2 = strings[0];
int max = s1.length();
int min = s2.length();
for (int i = 0; i < strings.length ; i++) {
if (strings[i].length() > max ) {
s1 = strings[i];
max = strings[i].length();
}
if (strings[i].length() < min )
{
s2 = strings[i];
min = strings[i].length();
CSEN 202: Introduction to Computer programming, Final Exam, June 17, 2023 Page 5
}
}
System.out.println( "Max Difference Pair: " + s1 + " " + s2);
}
Solution 3
public static void findMaxDifferencePair(String[] s) {
int maxDiff = 0; // or -1
int max_i_1=0, max_i_2=0; // or create 2 strings
for (int i = 0; i < s.length; i++) {
for (int j = i + 1; j < s.length; j++) {
int diff = s[i].length() - s[j].length();
diff = (diff < 0) ? -diff : diff; // or use Math.abs
if (diff > maxDiff) { //>= also is accepted
maxDiff = diff;
max_i_1 = i; // or save the 1st string
max_i_2 = j; // or save the 2nd string
}
}
}
System.out.println("max is between " + s[max_i_1] + " and " + s[max_i_2]);
}
CSEN 202: Introduction to Computer programming, Final Exam, June 17, 2023 Page 6
Exercise 3 (10 Marks)
Write a recursive method called specialParse that takes only one String argument s, and parses the numbers
in the string and returns it as an integer.
You may use helper method(s).
Examples:
specialParse("s1r5") returns integer 15
specialParse("r04ff3") returns integer 43
specialParse("1f0d22T") returns integer 1022
specialParse("123") returns integer 123
Solution:
// signature (0.5 each)
// calling helper 1 mark
// anchor case 1 mark
// checking if digit 1.5 marks
// calling with parameter updated 1.5 mark
// concatenation 1
// calling with parameter updated else part 1.5 mark
// parsing 1.5 marks
public static int specialParse(String s)
{ return Integer.parseInt(helper(s));
}
public static String helper(String s) {
if ( s.length()==0)
return "";
else {
if (s.charAt(0) >= ’0’ && s.charAt(0) <= ’9’) // it’s a number
return s.charAt(0) + helper(s.substring(1));
// append the number and continue
return helper(s.substring(1)); // dont append, but continue
}
}
Alternative solution:
public static int specialParse2(String s)
{
return helper(s, 1); // start from last character, with power =1
}
public static int helper(String s, int p)
{
if(s.length()==0)
return 0;
else {
int end = s.length()-1;
if(s.charAt(end)>=’0’ && s.charAt(end)<=’9’)
// check last character
return Integer.parseInt(s.charAt(end)+"") * p
+ helper(s.substring(0,end),p*10);
// number found, add it and increase power by 10.
return helper(s.substring(0,end), p);
//number not found, continue without increasing power
}
}
CSEN 202: Introduction to Computer programming, Final Exam, June 17, 2023 Page 7
Alternative solution:
public static int specialParse(String s)
{
return helper(s,0);
}
public static int helper(String s, int r)
{
if(s.length()==0)
return r;
if(s.charAt(0)>=’0’ && s.charAt(0)<=’9’)
{
r = r*10 + Integer.parseInt(s.charAt(0)+"");
return helper(s.substring(1),r);
}
else
return helper(s.substring(1),r);
}
CSEN 202: Introduction to Computer programming, Final Exam, June 17, 2023 Page 8
CSEN 202: Introduction to Computer programming, Final Exam, June 17, 2023 Page 9
Exercise 4 (12 Marks)
Write a recursive method moveZeros that takes an array of int, the method moves all 0’s to the end of an
array. Maintain the relative order of the other (non-zero) array elements. and returns the newly constructed array
Examples:
moveZeros({0,0,1,0,3,0,5,0,6}) -> returns {1,3,5,6,0,0,0,0,0}
moveZeros({}) -> returns {}
moveZeros({0,1,2,3}) -> returns {1,2,3,0}
Hint: you may use a helper method.
Solution:
// signature 1 mark
// initializing result array 0.5 marks
// calling helper + return 2 marks
// helper signature 1.5 marks
// anchor case 1 mark
// return 0.5 marks
// checking if zero 1 mark
// populating array correctly 1.5
// calling with parameter updated 1.5 mark each
static int[] moveZeros(int[] a)
{
int[] r = new int[a.length];
return zerosHelper(a,r,0,0,a.length-1);
}
public static int[] zerosHelper(int[]a, int[]r, int k, int i, int j)
{
if(k ==a.length)
return r;
if(a[k] == 0)
{
r[j] = a[k];
return zerosHelper(a,r,++k,i,--j);
}
else
{
r[i] = a[k];
return zerosHelper(a,r,++k, ++i,j);
}
}
CSEN 202: Introduction to Computer programming, Final Exam, June 17, 2023 Page 10
Alternative solution:
public static int[] moveZeros(int[] a) {
int[] res = new int[a.length]; // initially all zeroes
helper(a, res, 0, 0);
return res;
}
public static void helper(int[] a, int[] res, int indexA, int indexRES) {
if (indexA < a.length)
// only process when index is still not at the end of the array A, else stop.
{
if (a[indexA] != 0) {
res[indexRES] = a[indexA]; // only push the element in the array ero.
if no
helper(a, res, indexA + 1, indexRES + 1); // increment both
indices
}
else // the element was zero in the original array
{
helper(a, res, indexA + 1, indexRES); // only inc indexA, keep indexReS same.
}
}
}
CSEN 202: Introduction to Computer programming, Final Exam, June 17, 2023 Page 11
Exercise 5 (10 Marks)
Write a static method isMultiple that takes a n x n 2D array arr as a parameter and returns true if every
element in the array is a multiple of the element above it and false otherwise. Assume the array has no zeros and
has at least two rows.
Examples:
Input: {{3, 1, 2}, {9, 5, 2}, {9, 10, 6}}
3 1 2
9 5 2
9 10 6
Output: true
Input: {{1,6}, {6,7}}
1 6
6 7
Output: false
Solution:
// signature 1 mark
// for loop 2 each
// condition 3 marks
// return 1 each
public static boolean isMultiple(int[][] a)
{
for(int i =1; i<a.length;i++)
for(int j = 0; j<a.length; j++)
if(a[i][j]%a[i-1][j]!=0)
return false;
return true;
}
CSEN 202: Introduction to Computer programming, Final Exam, June 17, 2023 Page 12
Exercise 6 (14+18=32 Marks)
The goal of this exercise is to design and implement a simple Car rental agency class.
The Car rental agency uses The Association of Car Rental Industry System Standards ACRISS vehicle matrix and
uses the SIPP code to identify features that the vehicle may have.
Each Car has an abbreviation consisting of 4 characters.
• 1st character defines the Vehicle Category.
• 2nd character defines the Vehicle Type
• 3rd character defines the Vehicle Transmission
• 4th character defines the Vehicle Fuel Type Air Conditioning
a) Write a class Car that represents a Car in a Car rental agency database.
The class should have the following static variable:
• an int total that holds the total number of cars
The class should also have the following attributes:
• A String called SIPP that consists of 4 characters holding the abbreviation according to the follow-
ing table:
Category Type Transmission Fuel_AC
M - Mini B - 2/3 Door M - Manual Unspecifield Drive R - Unspecified Fuel/Power With Air
N - Mini Elite C - 2/4 Door N - Manual 4-WD N - Unspecified Fuel/Power Without Air
E - Economy D - 4/5 Door C - Manual A-WD D - Diesel with Air
Example: MCND means it is a Mini car that has 2/4 Door with Manual 4-WD transmission and has
Diesel with Air conditioning.
• A boolean variable isRented that holds whether or not the car is rented.
• A double variable pricePerDay that holds the rental price per day.
• An int variable ID that is automatically generated whenever the car is created (starting 0)
Augment your class with the following:
• A constructor that takes takes 5 parameters: (1) category, (2) type, (3) transmission and (4) fuel_AC,
as characters, and (5) priceperday.
• A getTransmission method that returns the description of the transmission of the invoked car.
• A toString() that returns all information about a specific vehicle, separated by commas.
• An isAvailable method that checks whether the invoked car is available for rent or not.
• A withinRange method that takes two parameters, low and high, and checks whether the car
rental price is within the given range, inclusive.
• A calculate method that takes the number of days and returns the total rent price.
CSEN 202: Introduction to Computer programming, Final Exam, June 17, 2023 Page 13
Exercise 6 a Solution:
Solution:
public class Car {
// 1 mark (0.25) each
String SIPP;
boolean isRented;
double pricePerDay;
int ID;
// 0.5 marks
static int total;
// 2 marks
// 0.5 signature, 0.5 concatenation, price and total 0.25 each, 0.5 update
total
public Car(char category, char type, char transmission,
char fuel, double price) {
SIPP = "" + category + type + transmission + fuel;
this.pricePerDay = price;
this.ID = total;
total++;
}
// 4 marks
// 0.5 signature, 1 getting correct char, 0.25 each return, 1.5 switch (or
if/else)
public String getTransmission() {
char tr = SIPP.charAt(2);
switch (tr) {
case ’M’:
return "Mannual Unspecified Drive";
case ’N’:
return "Manual 4WD";
case ’C’:
return "Manual AWD";
default:
return "unkown";
}
// 1 marks
// 0.5 signature, 0.5 return
public boolean isAvailable() {
return !isRented;
}
// 2 marks
// 0.5 signature, 0.5 return, 1 condition
public boolean withinRange(double low, double high) {
return (pricePerDay >= low && pricePerDay <= high);
}
CSEN 202: Introduction to Computer programming, Final Exam, June 17, 2023 Page 14
// 1 marks
// 0.5 signature, 0.5 return
public double calculate(int days) {
return days * pricePerDay;
}
// 2.5 marks
// 0.5 signature, 1.5 conditions, 0.5 concatenation and return
public String toString() {
String category = (SIPP.charAt(0) == ’M’)? "Mini"
: (SIPP.charAt(0)==’N’)? "Mini Elite" : "Economy";
String doors = (SIPP.charAt(1) == ’B’)? "2/3 doors"
: (SIPP.charAt(1)==’C’)? "2/4 doors" : "4/5 doors";
String transmission = (SIPP.charAt(2) == ’M’)? "Manual UD"
: (SIPP.charAt(2)==’N’)? "Mannual 4WD" : "Manual AWD";
String fuel = (SIPP.charAt(0) == ’R’)? "with air"
: (SIPP.charAt(0)==’N’)? "without air" : "Diesel air";
return "ID:" + ID + "," + category +", " + doors + ", "
+ transmission + ", " + fuel + ", " + pricePerDay +" EGP";
}
CSEN 202: Introduction to Computer programming, Final Exam, June 17, 2023 Page 15
CSEN 202: Introduction to Computer programming, Final Exam, June 17, 2023 Page 16
b) Write a class CarRental that represents a Car rental agency. It will use the Car class.
The CarRental class should contain two instance variables:
• A String called name that holds the name of the Agency.
• An array CarList, of Car instances that represents the Car list.
• an int maxCars that holds the maximum number of Car instances that an agency can have.
• An int numCars that holds the number of Car instances that are actually in the array.
The class CarRental should implement the following:
• A constructor that takes an input the maximum capacity of cars and creates a car array with this capac-
ity.
• A constructor that takes an array a of Car objects and initializes the corresponding instance variables.
The carList variable should be of the same length of a. You are required to do a deep cloning of
the all objects.
• A delete method that takes a String representing the category and deletes all cars within the same
category. The variable numCars should be updated accordingly.
• An add method that should take in a Car as a parameter, and add it to the Car array in the first empty
slot. The variable numCars should be updated accordingly.
• An availableToRent method that takes the Type of the Car as a character and checks if there is
an available car to rent or not, if there is any, the first available car rental status should be updated.
• An AvailableWithinRange method that takes 2 parameters, low and high and displays ALL
available-to-rent vehicles within the entered price range.
• A toString method that displays all vehicles in the CarRental
• A main method that should do the following:
1. Create a CarRental instance with a name AVIS with an array of Car objects that has a maxi-
mum capacity of 10.
2. Add 2 cars to AVIS agency.
3. Create carRental called Alamo, that is a copy of Avis. Use the corresponding constructor.
4.Delete all cars in AVIS with category Mini.
5.Display the cars in Alamo
CSEN 202: Introduction to Computer programming, Final Exam, June 17, 2023 Page 17
Solution:
public class CarRental {
// 1 mark (0.25) each
String name;
Car[] carList;
int maxCars;
int numCars;
// 0.75 mark
// 0.25 each initialization
public CarRental(int max, String name) {
maxCars = max;
carList = new Car[max];
this.name = name;
}
// 3.25 marks
// 0.25 each initialization, 0.5 for loop,
// 0.5 creating new car, 1 assigning car content
public CarRental(Car[] a, String name) {
this.name = name;
int len = a.length;
carList = new Car[len];
numCars = len;
maxCars = len;
for (int i = 0; i < len; i++) {
carList[i] = new Car(a[i].SIPP.charAt(0),
a[i].SIPP.charAt(1),
a[i].SIPP.charAt(2),
a[i].SIPP.charAt(3),
a[i].pricePerDay);
}
}
// 3 marks
// 1 comparisons,
// 0.5 loop, 0.5 condition, 0.5 assigning to null, 0.5 update
public void delete(String category) {
char cat;
if (category.equals("Mini"))
cat = ’M’;
else if (category.equals("Mini Elite"))
cat = ’N’;
else
cat = ’E’;
for (int i = 0; i < maxCars; i++) {
if (carList[i].SIPP.charAt(0) == cat) {
carList[i] = null;
numCars--;
}
}
}
CSEN 202: Introduction to Computer programming, Final Exam, June 17, 2023 Page 18
// 2.5 marks
// 0.5 loop, 0.5 condition, 0.5 assigning to c, 0.5 update, 0.5 break
public void add(Car c) {
for (int i = 0; i < maxCars; i++)
if (carList[i] == null) {
carList[i] = c;
// shallow. if deep we need new Car and copy again. both correct.
numCars++;
break;
}
}
2 pts: condition: 1 and setting rented 0.5, break: 0.5
public void availableToRent(char type) {
for (int i = 0; i < maxCars; i++) {
if (carList[i] != null)
if (carList[i].SIPP.charAt(1) == type &&
carList[i].isAvailable()) {
carList[i].isRented = true;
break;
}
2 pts: loop and check null: 1 , condition and print 1
public void availableWithinRange(double low, double high) {
for (int i = 0; i < maxCars; i++)
if (carList[i] != null)
if (carList[i].withinRange(low, high)
&& carList[i].isAvailable())
System.out.println(carList[i].toString());
1.5 pts, 0.5 each: loop, check null, tostring/concat
public String toString() {
String all = "";
for (int i = 0; i < maxCars; i++)
if (carList[i] != null)
all += carList[i].toString() + "\n";
return all;
}
2 pts
public static void main(String[] args) {
Car[] list = new Car[] {
new Car(’M’, ’B’, ’M’, ’R’, 400),
new Car(’N’, ’C’, ’N’, ’N’, 1400),
new Car(’E’, ’D’, ’C’, ’D’, 800),
};
CarRental avis = new CarRental(list, "AVIS");
System.out.println(avis.toString());
CarRental alamo = new CarRental(avis.carList, "ALAMO");
System.out.println(alamo.toString());
alamo.add(new Car(’M’,’B’,’N’,’N’,2000));
CSEN 202: Introduction to Computer programming, Final Exam, June 17, 2023 Page 19
System.out.println(alamo.toString());
alamo.delete("Mini");
System.out.println(alamo.toString());
}
CSEN 202: Introduction to Computer programming, Final Exam, June 17, 2023 Page 20
CSEN 202: Introduction to Computer programming, Final Exam, June 17, 2023 Page 21
Exercise 7 (8 Marks)
What is the output after executing the following program? if the program generates an error, indicate why.
a) public class MysteryTest {
public static void main(String[] args)
{
int x = 4;
int y = 8;
int[] data = {5, 10, 15};
x = mystery1(y, data);
mystery2(x, y);
System.out.println(x + " " + y);
}
public static int mystery1(int n, int[] numbers)
{
n = n + 100;
numbers[2]--;
for (int i = 1; i < numbers.length ; i++);
return numbers[1] * 2;
}
public static void mystery2(int x, int y)
{
x++;
y = y * 3;
}
}
Solution: 1.5 each, total 3 pts
20 8
CSEN 202: Introduction to Computer programming, Final Exam, June 17, 2023 Page 22
b) public class IntObj {
int v = 0;
public IntObj() {
}
public void setInt(int v) {
this.v = v;
}
public int getInt() {
return v;
}
public static void swap(IntObj o1, IntObj o2) {
IntObj o3 = o1;
o1 = o2;
o2 = o3;
}
public static void main(String[] args) {
IntObj p;
p = new IntObj();
IntObj q = new IntObj();
q.setInt(20);
p.setInt(q.getInt());
System.out.println(p.getInt());
p.setInt(15);
swap(p, q);
q = p;
p = null;
System.out.print(q.getInt());
System.out.print(p.getInt());
}
}
20 1.5 pt
15 1.5 pt
Null pointer exception 1pt as p is null 1pt
CSEN 202: Introduction to Computer programming, Final Exam, June 17, 2023 Page 23
Scratch paper
CSEN 202: Introduction to Computer programming, Final Exam, June 17, 2023 Page 24
Scratch paper
CSEN 202: Introduction to Computer programming, Final Exam, June 17, 2023 Page 25
Scratch paper