Print a 2D Array or 2 Dimensional Array in Java
In this tutorial, first we will learn how to print 2d array in java but before writing the code in java let's first understand what is 2d array in java, after that we will write the code of 2 dimensional array in java.
A two dimensional or 2d array is a collection of data cells which are arranged in row and column or matrix format. All the data in a 2D array is of the same type.
If you are not able to understand the above
definition, then look at the example given
below.
For example:-
Below, in this post, I have have written a short and easy to understand java program below which prints the elements input by the user in 2d array form.
Basically, the logic I have implemented in this program is pretty easy to understand.
First, I will ask the user to enter the number of rows and columns, then the user will enter the elements of the array, after that I will use for loop and print all the elements in matrix format. square of that number after that I will extract the digits (starting from the last digit) of the square.
Print a 2 Dimensional Array in Java
import java.util.*;
public class Print_Two_Matrix
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of Rows");
int r=sc.nextInt();
System.out.println("Enter the number of Columns");
int c=sc.nextInt();
int arr[][]=new int[r][c];
int brr[][]=new int[r][c];
System.out.println("Enter the elements of First Matrix");
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
arr[i][j]=sc.nextInt();
}
}
System.out.println("First Matrix is :");
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println("");
}
System.out.println("Enter the elements of Second Matrix");
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
brr[i][j]=sc.nextInt();
}
}
System.out.println("Second Matrix is :");
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
System.out.print(brr[i][j]+" ");
}
System.out.println("");
}
}
}
------------
OUTPUT:-
------------
Enter the number of Rows
3
Enter the number of Columns
3
Enter the elements of First Matrix
1
2
3
4
5
6
9
8
7
First Matrix is :
1 2 3
4 5 6
9 8 7
Enter the elements of Second Matrix
1
2
3
6
5
4
7
8
9
Second Matrix is :
1 2 3
6 5 4
7 8 9
-----------------
0 Comments
Just write down your question to get the answer...