147k views
4 votes
Write a program, TwoDimentionalGrid. Ask the user to enter the size of the 2 dimensional array. Here we are not doing any input validation. We are assuming, user is going to enter a number greater than 1. Create a 2D array with the same row and column number. Now print the array as a number grid starting at 1. Example: At place row number 3 and column number 2, number would be 6 (3*2). Any number would be the product of it's row number and column number. Hint: Use setw 5. Expected Output: Here I am attaching 2 expected output. Make sure your code is running for both input.

User Reddersky
by
4.4k points

1 Answer

6 votes

Answer:

The program in Java is as follows:

import java.util.*;

public class Main{

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Array size: ");

int n = input.nextInt();

int[][] myarray = new int[n][n];

for(int i =0;i<n;i++){

for(int j =0;j<n;j++){

myarray[i][j] = i * j; } }

for(int i =0;i<n;i++){

for(int j =0;j<n;j++){

System.out.print(myarray[i][j]+" "); }

System.out.println(); }

}}

Step-by-step explanation:

This prompts the user for the array size

System.out.print("Array size: ");

This gets input for the array size

int n = input.nextInt();

This declares the array

int[][] myarray = new int[n][n];

This iterates through the rows

for(int i =0;i<n;i++){

This iterates through the columns

for(int j =0;j<n;j++){

This populates the array by multiplying the row and column

myarray[i][j] = i * j; } }

This iterates through the rows

for(int i =0;i<n;i++){

This iterates through the columns

for(int j =0;j<n;j++){

This prints each array element

System.out.print(myarray[i][j]+" "); }

This prints a new line at the end of each row

System.out.println(); }

}

User Dismissile
by
4.5k points