Java 2D Array

Photo by Shahadat Rahman on Unsplash

Lately I have been learning Java so I have been looking for problems I can practice the basics on. I came across a problem that I thought was very interesting and fun to work on. The problem was to find the maximum number in a 2D array and also show the index of that number. I thought it would be good to show my process.

There is two steps to this problem. First we have to find the maximum number and then return the element’s index in the 2D array. I am going to create a method for each of the steps. I will call the first method maxNum. I will be creating variable that will represent the maximum number. I will use two for loops. This is what my first method looks like.

The maxNum method will take a 2D array as an argument. Every time the value of the max variable is lower than one of the element’s the value will be replaced with that element. This is how we find the maximum value. Now we need to find the index of the maximum number. This is actually very similar to the maxNum method. The only difference is that we can iterate through the array and check if the element is equal to the maximum number. If so, we store the index values into an array and return it. This is what that method will look like.

This is actually all we need! I am going to add a main method and output the value to the console. This is what the completed class looks like.

This problem is another great way to get used to iterating through arrays. I found it fun to solve and I learned from it. Happy coding! 😎