java

How to fill a 2D array with numbers in Java

In this tutorial, we are going to see how to fill and display a 2D array with numbers in Java. For that, we are going to use the Scanner class of Java.
 

Java Program to fill a 2D array with numbers:
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		
		System.out.print("Enter the number of rows: ");
		Scanner sc = new Scanner(System.in);
		int m = sc.nextInt();
		
		System.out.print("Enter the number of columns: ");
		int n = sc.nextInt();

		//declare the 2d array
		int[][] a = new int[m][n];

		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				System.out.print(String.format("Enter a[%d][%d] : ", i, j));
				a[i][j] = sc.nextInt();
			}
		}

		for (int i = 0; i < a.length; i++) {
			for (int j = 0; j < a[0].length; j++) {
				System.out.print(a[i][j] + "\t");
			}
			System.out.println();
		}
		
		// close the scanner object
		sc.close();
	}
}

Output:

Enter the number of rows: 2
Enter the number of columns: 2
Enter a[0][0] : 1
Enter a[0][1] : 2
Enter a[1][0] : 3
Enter a[1][1] : 4
1       2
3       4
[st_adsense] mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *