2d Array Input in Java. How to take 2d array input in Java. In this article, we will explore how to efficiently take input for a 2d array in Java, a fundamental skill for programmers.
Table of Contents
Taking Input for 2d array in Java
The process for taking 2d array input in Java involves iterating through the array row and column and assigning value to each element. We can acheive this by using nested loop and Scanner
object for input.
2d Array Input Java Example
import java.util.Scanner;
public class TwoDArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of row in 2d array");
int n = sc.nextInt();
System.out.println("Enter the number of column in 2d array");
int m = sc.nextInt();
int[][] matrix = new int[n][m];
System.out.println("Enter the elements of 2d array");
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
matrix[i][j] = sc.nextInt();
}
}
// printing the 2d matrix
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
System.out.print(matrix[i][j]+" ");
}
System.out.println();
}
}
}
Output
The above Java program first asks users to enter several rows and columns. After that Java program asks users to enter elements of the 2d array(as a size specified by the user – no of rows and columns) . At the end Java program prints the 2d array entered by user. After taking 2d array input we can perform all required operations on 2d array.
Happy Coding & Learning
3 thoughts on “2d Array Input in Java”