The following exercise is designed to check your understanding of Java arrays and loop statements. Read the exercise, then write or paste your answer into the text area below it. Create an application called Loopy that consists of a
main()
method and an additional static method named zero(). Here is the method definitions for
zero()
.
static void zero(int[][] a, int n);
The method
zero()
should search the two-dimensional array a and change the first occurrence of n to 0.
One approach is to use nested for loops to search the array and then to use a break statement to stop searching once an occurrence of n has been found and set to 0. You are free to search the array however you like. Depending on your approach, the first occurrence of n that you find may not be the same as that found using a different approach. That is fine. All that is required is that you change the first occurrence that you find.
Your
main()
method should create and initialize a two-dimensional array of int and then demonstrate the use of the method
zero()
. You might consider displaying the contents of your array before and after calling
zero()
.
Note that in Java, two-dimensional arrays are actually arrays of arrays, and therefore need not be rectangular.
Your solution should also work with non-rectangular two-dimensional arrays. Here's an example of declaring and initializing a non-rectangular array:
int[][] a = {{1, 3, 2}, {2, 1}};
In the text box below, cut and paste the source code for the Loopy application. Click the
Submit button to submit the code.