Reputation: 21
/* finding largest element in an 2d array */ hi im trying to find the largest element in a two dimensional array can anybody help.the output i get is 8 but it should be 45
class LargestSmallestOfTwoDimensionalArray
{
public static void main(String[] args)
{
int[][] data ={ {8,1,25,3,4},{45,12,13,2,3} }; // array of data
int large = data[0][0];
for(int i =0 ; i < data.length ; i++)
{
for(int j =i + 1 ; j < data.length ; j++)
{
if(large < data[i][j])
{
large= data[i][j];//checking and storing the largest element
}
}
}
System.out.println("Largest Element :" + large);
}
}
Upvotes: 1
Views: 293
Reputation: 16721
The problem lies in second loop, start at zero and check your condition:
for (int j = 0; j < data[i].length ; j++)
Remember, you need to check for the length of the inner list, not outer.
Upvotes: 3
Reputation: 7083
The problem is that you are not checking every position in the array.
Change your code to this:
int[][] data ={ {8,1,25,3,4},{45,12,13,2,3} }; // array of data
int large = data[0][0];
for(int i =0 ; i < data.length ; i++)
{
for(int j =0 ; j < data[i].length ; j++)
{
if(large < data[i][j])
{
large= data[i][j];//checking and storing the largest element
}
}
}
System.out.println("Largest Element :" + large);
Hope it helps..
Upvotes: 2