Row/Column Maxima, Transpose & Formatting
Find row/column maxima safely (jagged-aware) and build matrix transposes (rectangular and jagged). Practice aligned printing.
Row Maxima
Row maxima: compute the max of each row by scanning its elements once.
public class Main {
public static void main(String[] args) {
// Example jagged array
int[][] m = {
{1, 7, 3},
{4, 9, 2, 11},
{6}
};
int r = 1; // choose which row to check (row index 1 → {4, 9, 2, 11})
// Max of a single row r
int max = Integer.MIN_VALUE; // start with very small number
for (int c = 0; c < m[r].length; c = c + 1) {
if (m[r][c] > max) {
max = m[r][c]; // update if current value is larger
}
}
System.out.println("Max value in row " + r + " = " + max);
}
}
Column Maxima
Column maxima in jagged arrays: check each row's length before reading column c.
public class Main {
public static void main(String[] args) {
// Example jagged array (rows with different lengths)
int[][] m = {
{1, 7, 3},
{4, 9}, // shorter row (only 2 columns)
{6, 2, 11, 5} // longer row (4 columns)
};
int c = 2; // column index to check (3rd column)
// Max of column c across all rows
int colMax = Integer.MIN_VALUE;
for (int r = 0; r < m.length; r = r + 1) {
// Guard: only access if this row has column c
if (c < m[r].length) {
if (m[r][c] > colMax) {
colMax = m[r][c]; // update maximum
}
}
}
System.out.println("Max value in column " + c + " = " + colMax);
}
}
All lessons in this course
- 2D Array Basics & Nested Iteration
- Jagged Arrays & Table Formatting
- Row/Column Maxima, Transpose & Formatting
- 2D Mini-Project: Gradebook
- 2D Utilities as a Helper Class (Refactor)
- 2D Data Cleaning & Validation