Homework 02: Control Flow

Submit this homework using Gradescope. You can type up your answers, or write legibly and scan them. Do not attempt to submit a paper copy in class, as it will not be accepted.


Consider the following method, which is trying to count the number of elements in an array a that are divisible by a specific divisor:

int countDivisibleElements(int[] a, int divisor) {
  int count = 0;
  boolean divisibleFound = false;
  
  int i = 0;
  while (i < a.length)
    if (a[i] % divisor == 0) 
      divisibleFound = true;
      count++;
    i++;
    
  if (divisibleFound)
    return count;
  else
    return 0;
}
  1. (1 point) Why does the method not return the correct value? (You can try the method out if you want to see what it actually does; or just trace its operation on paper.)

  2. (1 point) What specific stylistic choice is the cause of the problem?

  3. (1 point) Rewrite the method to return the correct result. Remove unnecessary variables and convert the while loop to a for loop.