Practice D.3 Program development with authentic IB Computer Science (CS) exam questions for both SL and HL students. This question bank mirrors Paper 1, 2, 3 structure, covering key topics like programming concepts, algorithms, and data structures. Get instant solutions, detailed explanations, and build exam confidence with questions in the style of IB examiners.
In a text processing program, we need to count the occurrences of a specific character.
Construct code that uses a for loop to iterate through a string text and counts how many times the character 'e' appears.
Explain how the loop and selection statements work together in your code.
Define the term 'parameter variable' in the context of a method that performs this counting task.
A company provides car parking services in large cities and needs a computer system to keep track of the number of vehicles using its parking areas.
When a vehicle arrives, its registration plate is recorded on the system and it is allocated a number that identifies where it should park. When the vehicle leaves, that space is made available for other vehicles to use.
Vehicles are identified by their unique registration plate, which is an alphanumeric code of eight characters (e.g. X1234567). This is clearly displayed on the vehicle.
A programmer created the classes ParkingAreaandVehicleto model the above situation.
public class ParkingArea {
private Vehicle vehicles$$;
private String name;
ParkingArea(String name, int capacity) {
this.name = name;
if (capacity > 300) capacity = 300;
this.vehicles = new Vehicle$capacity$;
}
String getName() {
return name;
}
public int getCapacity() {
return vehicles.length;
}
public int findVehicle(String reg) {
//find where the vehicle is located in the array and
//return the index not yet written
}
}
public class Vehicle {
private String registration;
private byte colour;
private boolean broken;
public final static byte BLACK=1;
public final static byte WHITE=2;
public final static byte BLUE=3;
public final static byte RED=4;
public final static byte GREEN=5;
private final static double ADMIN\_FEE = 3;
public Vehicle() {}
public Vehicle(String registration) {
this.registration = registration;
}
public Vehicle(String registration, byte colour) {
this.registration = registration;
this.colour=colour;
}
public void setBroken(boolean broken) {
this.broken=broken;
}
public void setColour(byte colour) {
this.colour=colour;
}
public boolean getBroken() {
return broken;
}
public String getRegistration() {
return registration;
}
public double pay(int hours) {
// code to return admin fee - only if applicable
}
}
Construct code to create an instance of the Vehicleclass that has a registration of X1234567.
Outline why it is necessary to use the keyword thisin the setBrokenmethod of the Vehicleclass.
Construct code that sets the colour of the object created in part (i) as black.
Describe the relationship between the classes Vehicleand ParkingArea.
Outline one effect of using the modifier staticwhen declaring a variable.
A hotel chain has a loyalty scheme in which customers are awarded 1000 points for each day they stay in one of their hotels. With these points, customers can achieve one of three status levels: Gold, Silver or Bronze. The level will determine the extra services to which they are entitled.
The total number of points collected during the current year will determine which of the three status levels they are assigned for the following year: For example only the points collected in 2018 will determine the status level for 2019.
Occasionally, new customers receive additional bonus points as part of a promotion.
The Pointsclass keeps details of the points and status levels of each customer.
public class Points
{
private String memberId; // id of the hotel customer
private int totalPoints; // this year's points
private int bonusPoints; // any bonus points given to this year's new member
private String statusNow; // current(this year's)status
private String statusNextYear; // following year's status
private Visits$$ allVisits = new Visits;//details of each visit
// during this year
int y; // number of visits this year
public Points(String id) // constructor for new member
{
memberId = id;
bonusPoints = 0;
y = 0;
statusNow = 'Bronze';
}
//constructor for new member given bonus points (valid for current year only)
public Points(String id, int bp)
{
memberId = id;
bonusPoints = bp; // multiples of 1000 - maximum number is 5000
y = 0;
statusNow = 'Bronze';
}
// all the accessor and mutator methods are present but not shown
public Visits getAllVisits(int v)
{
return allVisits;
}
public void addVisit(Visits v) // adds a new Visit object to the array
{
allVisits = v;
y = y + 1;
}
isGold() {code missing}
calculateTotalPoints(){code missing}
daysMissing(){code missing}
}
The instance variables in the Pointsclass are preceded by the modifier private. The choice of modifier affects the way in which these variables are accessed or used.
The customers will be assigned one of three levels for the following year (Gold, Silver or Bronze) depending upon the current year’s total points as follows.
In 2018, Tim became a member for the first time and was awarded a bonus of 1000 points. So far, in 2018, Tim has stayed three times at one of these hotels. The first visit lasted 2 days, the second visit lasted 1 day and the third visit lasted 6 days.
The different Pointsobjects are stored in an array which is declared globally in the main (driver) class as follows:Points[] allPoints = new Points[10000];
With the use of two examples other than private, outline how the choice of this modifier affects the way in which these variables are accessed or used.
With reference to the two methods with the same name in the Pointsclass, explain the OOP feature that makes it possible to successfully implement either of these methods.
State the status level that Tim has been assigned, for 2019, following these visits.
State how an individual object can be identified using this array.
The attribute statusNowis assigned its correct value at the beginning of every year for existing members. It cannot be changed during the year.
Construct the method isGold()in the Pointsclass, which will return whether the current status is “Gold”.
A restaurant uses an object-oriented program to manage the cost of the food and drink consumed by customers. Everytime a table is occupied a Paymentobject is instantiated which will contain details of the items ordered. As each item is ordered, a FoodItemor a DrinkItemobject is added to the Paymentobject as appropriate.
public class Payment
{
private FoodItem[] fi = new FoodItem[100];
private int fiCount;
private static double foodTax = 0.2; // 20 % sales tax added to
// all food prices
private DrinkItem[] di = new DrinkItem[100];
private int diCount;
private static double drinkTax = 0.1; // 10 % sales tax added to
// all drink prices
public Payment()
{
fiCount = 0;
diCount = 0;
}
public DrinkItem getDi(int x)
{
return di[x];
}
// all other accessor and mutator methods are included
// addFoodItem() – this method adds a new FoodItem object
// addDrinkItem() – this method adds a new DrinkItem object
public static double findPrice(Item[] pl, String c)
{ //code missing }
// calculateBill() – This method returns the bill (the total value of
// the items consumed for a particular table)
}
public class FoodItem
{
private String itemCode;
private int quantity;
public FoodItem(String x, int y)
{
itemCode = x;
quantity = y;
}
// all accessor and mutator methods are included
}
The DrinkItemclass is defined in a similar way.
Whenever a Payment object is instantiated, the variables fiCount and diCount are initialized to 0 through the code in the constructor.
Outline an alternative method of initializing these variables that would not require the use of the code in the constructor.
State the implication of the use of the term staticin the Paymentclass.
With reference to two examples from the classes in the resource, explain the benefits gained by the use of different data types.
Describe the purpose of the following statement:
**private** FoodItem[] fi = **new** FoodItem[100]
The Paymentclass method addFoodItem()is passed a FoodItemobject as a parameter.
Construct the method addFoodItem().
When the number of customers in the supermarket is low, some check-out counters will close. When there are many customers waiting, a new check-out counter will open.
When a new check-out counter opens, some customers from the nearest line will choose to move their carts to this check-out counter.
For this simulation, the assumption is made that every second cart in the old line will move to the new line and the other carts will remain in the original line.
Outline why the variable activein the UML of the class POSlinewas defined as a boolean data type.
Construct the code for a method split(part of the class POSsystem), that takes an existing, non-empty POSlineas a parameter. It should copy every second cart from the original line into a new line. Afterwards it should delete every second cart from the original line.
An example call in POSsystemwould be: POSline number2 = split(number1), where number1is an existing POSline.
You may use any method declared or developed.
As a result of the simulation, the company has decided to create a new POS system for their supermarkets.
There have been discussions about adapting existing open source code when developing modules of the new POS system.
Describe two ethical issues that may arise if modules of the new POS system are developed from open source code.
A sorting algorithm needs to be implemented using selection statements.
Construct code that finds the minimum value in an array numbers of integers.
Explain how the if statement is used in your code to compare values.
Define the term 'local variable' and explain its scope in the context of your code.
In a banking application, there's a static method to calculate interest rates.
Define the term static in the context of object-oriented programming.
Explain one advantage of using static methods in a class.
Construct a static method called calculateInterest in a class Bank that takes a principal amount (double) and returns the interest (double). Assume a static interest rate of 5%.
A method needs to perform different actions based on user input.
Explain one advantage of using a switch statement over multiple if-else statements.
Construct code using a switch statement that performs different actions when a variable choice has values 1, 2, or 3.
Define the term 'signature' of a method and describe what it includes.
A company is developing a simple calculator application in Java. The application will perform basic arithmetic operations like addition, subtraction, multiplication, and division.
Define the term 'primitive data type' in programming.
Describe the uses of the primitive data types int and double in this calculator application.
Construct code that declares two variables of type double, assigns them values, and calculates their sum.
The following code implements the Parcel class used in the delivery company's program.
public class Parcel
{
private int trackingID;
private double weight;
public String destinationAddress;
public String originAddress;
public Parcel(int ID) {
trackingID = ID; weight = 0;
}
public void setWeight(double newWeight) {
weight = newWeight;
}
public double getWeight() {
return weight;
}
}
The origin and destination addresses are stored in a Parcel object as simple strings. However, addresses are complex and there are a lot of different pieces of information that may or may not be present such as a first name or a business name, in addition to house number, street name, city and country. It has been decided to create a new Address class to handle this information.
Outline one advantage of using standard library collections.
Describe two ways in which programming by a team differs from programming by an individual working alone.
State the appropriate data type to be used in the Address class to store the street name.
State the appropriate data type to be used in the Address class to store the building number.
State the appropriate data type to be used in the Address class to store an indication of whether or not this is a business address.
Identify the changes to the Parcel class that will be needed to make use of the new Address class.
Outline how these two new classes can be created with minimal duplication of code.