“Write a method” questions

Write a method getMin() that takes an int array n as its argument and returns the smallest value in the array [8 marks].

Answer:

int getMin(int[] n){
  int min = n[0];
   for (int i = 0; i < n.length; i++) {
    if (n[i] < min) {
      min = n[i];
    }
  }
  return min;
}
  • 1 mark for correct return type (int)
  • 1 mark for correct argument type (int[])
  • 1 mark for correct initialization of min
  • 1 mark for using a loop
  • 1 mark for setting up for loop correctly (termination condition and increment)
  • 1 mark for correct if condition
  • 1 mark for correct assignment of min
  • 1 mark for correct return value

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s