0% found this document useful (0 votes)
7 views2 pages

2D Arrays Solutions

This document contains 3 solutions for working with 2D arrays in Java. The first solution counts the number of 7s in a 2D array. The second solution sums the elements of the second row of a 2D array. The third solution transposes a 2D integer matrix by creating a new matrix with the rows and columns swapped.

Uploaded by

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

2D Arrays Solutions

This document contains 3 solutions for working with 2D arrays in Java. The first solution counts the number of 7s in a 2D array. The second solution sums the elements of the second row of a 2D array. The third solution transposes a 2D integer matrix by creating a new matrix with the rows and columns swapped.

Uploaded by

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

2D ARRAYS SOLUTIONS

[email protected]
Solution 1:
public class Solution {
public static void main(String[] args) {
int[][] array = { {4, 7, 8}, {8, 8, 7} };

int countOf7 = 0;
for(int i=0; i<array.length; i++) {
for(int j=0; j<array[0].length; j++) {
if(array[i][j] == 7) {
countOf7++;
}
}
}

System.out.println("count of 7 is : " + countOf7);


}
}

Solution 2:
public class Solution {
public static void main(String[] args) {
int[][] nums = { {1,4,9},{11,4,3},{2,2,3} };
int sum = 0;

//sum of 2nd row elements


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

System.out.println("sum is : " + sum);


}
}
Solution 3 :

[email protected]
public class Solution {
public static void main(String[] args) {
int row = 2, column = 3;
int[][] matrix = { {2, 3, 7}, {5, 6, 7} };

// Display original matrix


printMatrix(matrix);

// Transpose the matrix


int[][] transpose = new int[column][row];
for(int i = 0; i<row; i++) {
for (int j = 0; j<column; j++) {
transpose[j][i] = matrix[i][j];
}
}

// print the transposed matrix


printMatrix(transpose);
}

public static void printMatrix(int[][] matrix) {


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

You might also like