Java Exercises: Print an array after changing the rows and columns of a specified two-dimensional array
Java Basic: Exercise-155 with Solution
Write a Java program to print an array after changing the rows and columns of a given two-dimensional array.
Original Array:
10 20 30
40 50 60
After changing the rows and columns of the said array:10 40
20 50
30 60
Pictorial Presentation:
Sample Solution:
Java Code:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
int[][] twodm = {
{10, 20, 30},
{40, 50, 60}
};
System.out.print("Original Array:\n");
print_array(twodm);
System.out.print("After changing the rows and columns of the said array:");
transpose(twodm);
}
private static void transpose(int[][] twodm) {
int[][] newtwodm = new int[twodm[0].length][twodm.length];
for (int i = 0; i < twodm.length; i++) {
for (int j = 0; j < twodm[0].length; j++) {
newtwodm[j][i] = twodm[i][j];
}
}
print_array(newtwodm);
}
private static void print_array(int[][] twodm) {
for (int i = 0; i < twodm.length; i++) {
for (int j = 0; j < twodm[0].length; j++) {
System.out.print(twodm[i][j] + " ");
}
System.out.println();
}
}
}
Sample Output:
Original Array: 10 20 30 40 50 60 After changing the rows and columns of the said array:10 40 20 50 30 60
Flowchart:
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to print the contents of a two-dimensional Boolean array where t will represent true and f will represent false.
Next: Write a Java program that returns the largest integer but not larger than the base-2 logarithm of a given integer.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework