0% found this document useful (0 votes)
11 views19 pages

Session 15 - Arrays - 2D Array

The document provides an overview of 2D arrays in Java, explaining their structure, syntax, and various operations such as initialization, accessing elements, and traversing. It includes examples of declaring and manipulating 2D arrays, as well as practice programs and quizzes to reinforce learning. Additionally, it introduces jagged arrays, highlighting their flexibility in handling non-uniform data storage.

Uploaded by

pavankumarvoore3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views19 pages

Session 15 - Arrays - 2D Array

The document provides an overview of 2D arrays in Java, explaining their structure, syntax, and various operations such as initialization, accessing elements, and traversing. It includes examples of declaring and manipulating 2D arrays, as well as practice programs and quizzes to reinforce learning. Additionally, it introduces jagged arrays, highlighting their flexibility in handling non-uniform data storage.

Uploaded by

pavankumarvoore3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

OBJECT-ORIENTED

PROGRAMMING THROUGH JAVA

UNIT - III

Session 15 - Arrays - 2D array

1. 2D Arrays

2D Arrays
2D arrays, also known as arrays of arrays, are a fundamental concept in Java for handling
tabular data.

1. Introduction to 2D Arrays
A 2D array in Java is essentially an array of arrays. It can be visualized as a table with rows and
columns. Each element of a 2D array is accessed by specifying two indices: one for the row and
one for the column.

Syntax:

type[][] arrayName = new type[rows][columns];



● type: The data type of the array elements.
● arrayName: The name of the array.
● rows: The number of rows in the 2D array.
● columns: The number of columns in the 2D array.
2. Examples
a. Declaring and Initializing a 2D Array

public class Array2DExample {


public static void main(String[] args) {
int[][] matrix = new int[3][4]; // 3 rows and 4 columns

// Initializing the array


for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = i + j; // Assigning values
}
}

// Printing the array


for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}

Output:

0 1 2 3
1 2 3 4
2 3 4 5

Explanation: This program declares a 2D array with 3 rows and 4 columns. It initializes the
array such that each element is the sum of its row and column indices. The nested loops are
used to assign values and print the array.

b. Creating a 2D Array with Initial Values

public class Array2DInitialization {


public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Printing the array


for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}

Output:

1 2 3
4 5 6
7 8 9

Explanation: This program initializes a 2D array with predefined values and prints the matrix.
The values are set directly in the array declaration.

c. Accessing Elements of a 2D Array

public class Array2DAccess {


public static void main(String[] args) {
int[][] matrix = {
{10, 20, 30},
{40, 50, 60},
{70, 80, 90}
};

// Accessing a specific element


int element = matrix[1][2]; // Accesses element in 2nd row and 3rd column
System.out.println("Element at [1][2]: " + element);
}
}

Output:

Element at [1][2]: 60

Explanation: This program demonstrates how to access a specific element in a 2D array using
its row and column indices.
d. Traversing a 2D Array

public class Array2DTraversal {


public static void main(String[] args) {
int[][] matrix = {
{1, 2},
{3, 4},
{5, 6}
};

// Traversing the array


for (int[] row : matrix) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
}
}

Output:

1 2
3 4
5 6

Explanation: This program uses enhanced for loops to traverse and print each element of the
2D array. It simplifies accessing each element by iterating through rows and columns.

Practice Programs
Program 1: Sum of All Elements in a 2D Array

public class Sum2DArray {


public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

int sum = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
sum += matrix[i][j];
}
}

System.out.println("Sum of all elements: " + sum);


}
}

Output:

Sum of all elements: 45



Program 2: Transpose of a 2D Array

public class Transpose2DArray {


public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

int[][] transpose = new int[3][3]; // Transpose of a 3x3 matrix

// Calculating transpose
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
transpose[j][i] = matrix[i][j];
}
}

// Printing transpose
for (int i = 0; i < transpose.length; i++) {
for (int j = 0; j < transpose[i].length; j++) {
System.out.print(transpose[i][j] + " ");
}
System.out.println();
}
}
}

Output:
1 4 7
2 5 8
3 6 9

Program 3: Find the Maximum Element in Each Row

public class MaxElementInRows {


public static void main(String[] args) {
int[][] matrix = {
{10, 20, 30},
{40, 50, 60},
{70, 80, 90}
};

for (int i = 0; i < matrix.length; i++) {


int max = matrix[i][0];
for (int j = 1; j < matrix[i].length; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
}
}
System.out.println("Max in row " + i + ": " + max);
}
}
}

Output:

Max in row 0: 30
Max in row 1: 60
Max in row 2: 90

Program 4: Fill a 2D Array with Multiples of 5

public class Fill2DArray {


public static void main(String[] args) {
int[][] matrix = new int[3][4]; // 3 rows and 4 columns
int value = 5;

for (int i = 0; i < matrix.length; i++) {


for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = value;
value += 5;
}
}

// Printing the array


for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}

Output:

5 10 15 20
25 30 35 40
45 50 55 60

Program 5: Matrix Multiplication

public class MatrixMultiplication {


public static void main(String[] args) {
int[][] matrix1 = {
{1, 2},
{3, 4}
};

int[][] matrix2 = {
{5, 6},
{7, 8}
};

int[][] result = new int[2][2];

// Multiplying matrices
for (int i = 0; i < matrix1.length; i++) {
for (int j = 0; j < matrix2[0].length; j++) {
result[i][j] = 0;
for (int k = 0; k < matrix2.length; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}

// Printing result matrix


for (int

i = 0; i < result.length; i++) {


for (int j = 0; j < result[i].length; j++) {
System.out.print(result[i][j] + " ");
}
System.out.println();
}
}
}

Output:

19 22
43 50

Do It Yourself
1. Write a Java program to declare a 2D array of size 4x3 and initialize it with values from 1
to 12. Print the array.

2. Create a program that calculates and prints the sum of each column in a 2D array.

3. Implement a program to find and print the transpose of a given 2D array.

4. Write a Java program to find and print the maximum element in a given 2D array.

5. Create a program that prints the diagonal elements of a square matrix.

Quiz

1. How do you declare a 2D array in Java?


A) int[] array = new int[3][4];
B) int[][] array = new int[3][4];
C) int[] array = new int[3][4][5];
D) int[][] array = new int[4];
Answer: B) int[][] array = new int[3][4];

2. Which method can be used to access the element in the 2nd row and 3rd column of a
2D array matrix?
A) matrix[2][3]
B) matrix[1][2]
C) matrix[3][2]
D) matrix[2][1]

Answer: B) matrix[1][2]

3. How do you print all elements of a 2D array in Java?


A) Use a single loop
B) Use nested loops
C) Use Arrays.toString()
D) Use System.out.println()

Answer: B) Use nested loops

4. What is the output of matrix[1][2] if matrix is a 2D array initialized as {{10, 20,


30}, {40, 50, 60}, {70, 80, 90}}?
A) 20
B) 30
C) 50
D) 60

Answer: D) 60

5. Which of the following is true about matrix multiplication in Java?


A) The number of columns in the first matrix must be equal to the number of rows in the
second matrix.
B) The number of rows in the first matrix must be equal to the number of columns in the
second matrix.
C) The matrices must be of the same size.
D) Matrix multiplication is not possible in Java.

Answer: A) The number of columns in the first matrix must be equal to the number of
rows in the second matrix.
2. Arrays of Varying Lengths (Jagged
Arrays)

Arrays of Varying Lengths


Arrays of varying lengths, often referred to as "jagged arrays" or "ragged arrays," are a type of
2D array in Java where each row can have a different number of columns. This flexibility allows
for more dynamic and non-uniform data storage compared to traditional 2D arrays where every
row has the same number of columns.

1. Introduction to Jagged Arrays


A jagged array is an array of arrays where each sub-array can have a different length. This is
useful for scenarios where the data structure is not rectangular and each row might represent a
different quantity of elements.

Syntax:

type[][] arrayName = new type[numberOfRows][];



Initialization:

arrayName[0] = new type[lengthOfFirstRow];


arrayName[1] = new type[lengthOfSecondRow];
// and so on

Example:

int[][] jaggedArray = new int[3][]; // Array with 3 rows


jaggedArray[0] = new int[2]; // First row with 2 columns
jaggedArray[1] = new int[4]; // Second row with 4 columns
jaggedArray[2] = new int[3]; // Third row with 3 columns

2. Examples
a. Declaring and Initializing a Jagged Array
public class JaggedArrayExample {
public static void main(String[] args) {
// Creating a jagged array
int[][] jaggedArray = new int[3][];

// Initializing the sub-arrays


jaggedArray[0] = new int[2]; // First row
jaggedArray[1] = new int[4]; // Second row
jaggedArray[2] = new int[3]; // Third row

// Assigning values to the jagged array


jaggedArray[0][0] = 1;
jaggedArray[0][1] = 2;
jaggedArray[1][0] = 3;
jaggedArray[1][1] = 4;
jaggedArray[1][2] = 5;
jaggedArray[1][3] = 6;
jaggedArray[2][0] = 7;
jaggedArray[2][1] = 8;
jaggedArray[2][2] = 9;

// Printing the jagged array


for (int i = 0; i < jaggedArray.length; i++) {
for (int j = 0; j < jaggedArray[i].length; j++) {
System.out.print(jaggedArray[i][j] + " ");
}
System.out.println();
}
}
}

Output:

1 2
3 4 5 6
7 8 9

Explanation: This program initializes a jagged array with varying lengths for each row. The
values are assigned to each sub-array, and the nested loops are used to print the entire jagged
array.

b. Accessing Elements in a Jagged Array

public class JaggedArrayAccess {


public static void main(String[] args) {
int[][] jaggedArray = {
{1, 2},
{3, 4, 5},
{6, 7, 8, 9}
};

// Accessing a specific element


int element = jaggedArray[1][2]; // Accesses element in 2nd row and 3rd column
System.out.println("Element at [1][2]: " + element);
}
}

Output:

Element at [1][2]: 5

Explanation: This program demonstrates accessing a specific element in a jagged array using
its row and column indices.

c. Iterating Over a Jagged Array

public class JaggedArrayIteration {


public static void main(String[] args) {
int[][] jaggedArray = {
{10, 20},
{30, 40, 50},
{60, 70, 80, 90}
};

// Iterating through the jagged array


for (int i = 0; i < jaggedArray.length; i++) {
for (int j = 0; j < jaggedArray[i].length; j++) {
System.out.print(jaggedArray[i][j] + " ");
}
System.out.println();
}
}
}

Output:

10 20
30 40 50
60 70 80 90

Explanation: This program uses nested loops to iterate through and print each element of the
jagged array.

d. Modifying a Jagged Array

public class ModifyJaggedArray {


public static void main(String[] args) {
int[][] jaggedArray = {
{1, 2},
{3, 4, 5},
{6, 7, 8}
};

// Modifying the array


jaggedArray[0][1] = 10; // Changing value in the first row
jaggedArray[2][2] = 20; // Changing value in the third row

// Printing the modified jagged array


for (int i = 0; i < jaggedArray.length; i++) {
for (int j = 0; j < jaggedArray[i].length; j++) {
System.out.print(jaggedArray[i][j] + " ");
}
System.out.println();
}
}
}

Output:

1 10
3 4 5
6 7 20

Explanation: This program modifies specific elements in the jagged array and prints the
updated array.

Practice Programs
Program 1: Jagged Array with User Input

import java.util.Scanner;

public class JaggedArrayUserInput {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.print("Enter number of rows: ");


int rows = sc.nextInt();

int[][] jaggedArray = new int[rows][];

for (int i = 0; i < rows; i++) {


System.out.print("Enter number of columns for row " + i + ": ");
int cols = sc.nextInt();
jaggedArray[i] = new int[cols];

System.out.println("Enter " + cols + " values for row " + i + ":");


for (int j = 0; j < cols; j++) {
jaggedArray[i][j] = sc.nextInt();
}
}

// Printing the jagged array


for (int i = 0; i < jaggedArray.length; i++) {
for (int j = 0; j < jaggedArray[i].length; j++) {
System.out.print(jaggedArray[i][j] + " ");
}
System.out.println();
}
}
}

Output: (Depends on user input)

Explanation: This program creates a jagged array based on user input for the number of rows
and columns in each row. It then populates and prints the array.

Program 2: Sum of Each Row in a Jagged Array

public class SumJaggedArrayRows {


public static void main(String[] args) {
int[][] jaggedArray = {
{1, 2},
{3, 4, 5},
{6, 7, 8, 9}
};

// Calculating and printing the sum of each row


for (int i = 0; i < jaggedArray.length; i++) {
int sum = 0;
for (int j = 0; j < jaggedArray[i].length; j++) {
sum += jaggedArray[i][j];
}
System.out.println("Sum of row " + i + ": " + sum);
}
}
}

Output:

Sum of row 0: 3
Sum of row 1: 12
Sum of row 2: 30

Explanation: This program calculates and prints the sum of elements in each row of a jagged
array.

Program 3: Maximum Value in Each Row

public class MaxInJaggedArrayRows {


public static void main(String[] args) {
int[][] jaggedArray = {
{1, 2},
{3, 4, 5},
{6, 7, 8, 9}
};

// Finding and printing the maximum value in each row


for (int i = 0; i < jaggedArray.length; i++) {
int max = jaggedArray[i][0];
for (int j = 1; j < jaggedArray[i].length; j++) {
if (jaggedArray[i][j] > max) {
max = jaggedArray[i][j];
}
}
System.out.println("Max in row " + i + ": " + max);
}
}
}

Output:
Max in row 0: 2
Max in row 1: 5
Max in row 2: 9

Explanation: This program finds and prints the maximum value in each row of a jagged array.

Program 4: Jagged Array to Matrix

public class JaggedArrayToMatrix {


public static void main(String[] args) {
int[][] jaggedArray = {
{1, 2},
{3, 4, 5},
{6, 7, 8, 9}
};

// Converting jagged array to matrix representation


int maxCols = 0;
for (int i = 0; i < jaggedArray.length; i++) {
if (jaggedArray[i].length > maxCols) {
maxCols = jaggedArray[i].length;
}
}

int[][] matrix = new int[jaggedArray.length][maxCols];


for (int i = 0; i < jaggedArray.length; i++) {
for (int j = 0; j < jaggedArray[i].length; j++) {
matrix[i][j] = jaggedArray[i][j];
}
}

// Printing the matrix


for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}

Output:

1 2 0 0
3 4 5 0
6 7 8 9

Explanation: This program converts a jagged array into a matrix with uniform row lengths and
prints the resulting matrix.

Do It Yourself
1. Write a Java program to create a jagged array with 3 rows where the first row has 2
columns, the second row has 3 columns, and the third row has 4 columns. Initialize and
print the array.

2. Implement a Java program that calculates and prints the sum of all elements in a jagged
array.

3. Write a program that finds and prints the minimum value in each row of a jagged array.

4. Create a program that converts a jagged array into a matrix form and prints it. Ensure
that missing values are represented by zeros.

5. Write a Java program that allows the user to input the number of rows and columns for
each row of a jagged array. Populate the array with user input and print it.

Quiz

1. How do you declare a jagged array in Java?


A) int[][] array = new int[3][3];
B) int[][] array = new int[3][];
C) int[] array = new int[3][3];
D) int[][] array = new int[3][4];

Answer: B) int[][] array = new int[3][];

2. Which of the following is true about accessing elements in a jagged array?


A) The number of columns must be the same for every row.
B) Each row can have a different number of columns.
C) Elements can only be accessed in a rectangular fashion.
D) Jagged arrays do not support accessing elements.

Answer: B) Each row can have a different number of columns.

3. How can you initialize a jagged array with different lengths for each row?
A) array = new int[rows][columns];
B) array = new int[rows][]; array[row] = new int[columns];
C) array = new int[][];
D) array = new int[columns][rows];

Answer: B) array = new int[rows][]; array[row] = new int[columns];

4. What will be the output of the following code snippet?

int[][] jaggedArray = {
{1, 2},
{3, 4, 5},
{6, 7}
};
System.out.println(jaggedArray[1][1]);
A) 3
B) 4
C) 5
D) 7

Answer: B) 4

5. Which of the following methods is used to iterate over a jagged array?


A) Single loop
B) Nested loops
C) Arrays.toString()
D) System.out.println()

Answer: B) Nested loops

References
End of Session - 15

You might also like