id/email
password
forgot password | create account
about | help | code help+videos | done | prefs
CodingBat code practice

 

srp4379@lausd.net > getSmallest4
prev  |  next  |  chance

public int getSmallest4(int[] nums)

Given an int[] array with 4 elements
return the smallest value.

Create an int return variable called smallest.
Assign it a default value, e.g. the first element.

Use an if statement to check if the 2nd value is smaller -
and if it is smaller, change the value of smallest to that value.

Use ANOTHER if statement to check if the 3rd value is smaller -
If it is, change the value of smallest to the 3rd element.

Use a 3rd if statement to check if the 4th value is smaller -
If it is, change the value of smallest to the 4th element.

public int getSmallest4(int[] nums) {
  int smallest = nums[0];
  if (nums[1] < smallest) {
    smallest = nums[1];
  }
  if (nums[2] < smallest) {
    smallest = nums[2];
  }
  if (nums[3] < smallest) {
    smallest = nums[3];
  }
  return smallest;
}
Below is how you would do the same thing using Math.min().
public int getSmallest4(int[] nums) {
  int smallest = Math.min( nums[0], nums[1] );
  smallest = Math.min( smallest, nums[2] );
  smallest = Math.min( smallest, nums[3] );
  return smallest;
}

getSmallest4([5, 10, 15, 20]) → 5
getSmallest4([20, 15, 10, 5]) → 5
getSmallest4([3, 6, 9, 12]) → 3

...Save, Compile, Run (ctrl-enter)

public int getSmallest4(int[] nums) { }

Editor font size %:
Shorter output


Forget It! -- delete my code for this problem

Progress graphs:
 Your progress graph for this problem
 Random user progress graph for this problem
 Random Epic Progress Graph

Java Help

Misc Code Practice

Difficulty: 1

Copyright Nick Parlante 2017 - privacy