AP® Computer Science A Selection and Iteration Practice Questions
Work through AP Computer Science A practice questions on Selection and Iteration, then check each answer against a worked solution.
Free · no sign-up Open questions need no account. Sign up or log in to open the rest.
Subtopic: Iteration Clear filter
Question 232
int n = 81;
int count = 0;
while (n > 1)
{
if (n % 3 == 0)
n = n / 3;
else
n = n - 1;
count++;
}
What value is stored in count after the loop terminates?Main Solution
Answer
Answer: A. Because each value remains divisible by 3, the path is 81 → 27 → 9 → 3 → 1. That is 4 iterations.
Answer: Correct: A
A
4
B
5
C
3
D
6
Answer images
Question 233
Question 234
public static int process(int n)
{
int result = 0;
while (n > 0)
{
result = result + n % 10;
n = n / 100;
}
return result;
}
What value is returned by process(58364) ?Main Solution
Answer
Answer: C. The method adds the last digit, then removes the last two digits. Starting with 58364, it adds 4, then 3 from 583, then 5 from 5. The total is 12.
Answer: Correct: C
A
26
B
17
C
12
D
10
Answer images
Question 235
A technical workshop offers several sessions throughout the day. The workshop stores information about each session in three parallel arrays.
capacity[i]is the maximum number of students allowed in sessioni.enrolled[i]is the number of students currently enrolled in sessioni.canceled[i]istrueif sessionihas been canceled andfalseotherwise.
You will write two methods of the WorkshopSchedule class. A partial class declaration is shown below.
public class WorkshopSchedule
{
private int[] capacity;
private int[] enrolled;
private boolean[] canceled;
// constructor not shown
public int openSeats(int session)
{ /* to be written in part (a) */ }
public int firstAvailableSession(int needed)
{ /* to be written in part (b) */ }
}
Part (a). Write the method openSeats, which returns the number of open seats in session session. If the session is canceled, the method returns 0.
For example, if capacity[2] = 24, enrolled[2] = 19, and canceled[2] = false, then openSeats(2) returns 5. If canceled[2] = true, then openSeats(2) returns 0.
Part (b). Write the method firstAvailableSession, which returns the index of the first session that has at least needed open seats. The method must ignore canceled sessions. If no session has at least needed open seats, the method returns -1.
Assume part (a) works as intended. Your solution to part (b) must call openSeats.
Answer images
Question 236
Question 237
Question 238
Question 239
AP® and Advanced Placement® are registered trademarks of the College Board, which is not affiliated with, and does not endorse, Verityprep. Names are used for identification purposes only.

