5.14 Lab 5c Patterned Matrix Objectives Create a program that initializes and pr
ID: 3699819 • Letter: 5
Question
5.14 Lab 5c Patterned Matrix
Objectives
Create a program that initializes and prints a 2-dimensional array.
Experience the exception message generated by a negative index value.
Use printf() instead of print() or println() methods.
Background Reading
ZyBook: 6. Arrays, 8.3 printf()
General Instructions
Write a Java class PatternedArray.java that will create an 2-dimensional array and print it in a table format.
The program should:
Create a two-dimensional array and that is filled with whole numbers such that the elements have the following pattern:
Row 1: 10+numRows*1+ 0, 10+numRows*1+1,10+numRows*1+2, …
Row 2: 10+numRows*2+ 0, 10+numRows*2+1, 10+numRows*2+2, …
Row 3: 10+numRows*3+ 0, 10+numRows*2+1, 10+numRows*3+2, …
Print the array by row where each element printed has a minimum width of 4 spaces and is left-justified. Use System.out.printf(). [Note: printf() is identical to format() End each row with a newline and complete the output with a blank line. See ZyBooks Chapter 8.3 for printf() explanation.
Sample output where input is 3 5
Sample output where input is 1 4
Sample output where input is 5 3
Hint:
System.out.printf("%3d", array[0][0]); would print the value at array[0][0] with a minimum width of three spaces right-justified.
If row is 3 and col is 0, System.out.printf("%-8d", array[row][col]); would print the value at array[3][0] with a minimum width of eight spaces left-justified.
public class PatternedMatrix {
public static void main(String[] args) {
//Grab the umber of rows and columns from the user, in that order
//create a 2-D array (matrix) that is rox x col
//use a nested for loops that fill the array with the pattern shown
//in the problem statement
//again using nested for loops, print the contents of the matrix
//with each row on it's own line and each number followed by a space
}
}
Explanation / Answer
PatternedMatrix.java
import java.util.Scanner;
public class PatternedMatrix {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of rows:");
int r = scan.nextInt();
System.out.println("Enter the number of columns:");
int c = scan.nextInt();
int a[][]= new int[r][c];
for(int i=0;i<r;i++){
for(int j=0;j<c;j++) {
a[i][j]=10+r*(i+1)+j;
}
}
for(int i=0;i<r;i++){
for(int j=0;j<c;j++) {
System.out.printf("%3d", a[i][j]);
}
System.out.println();
}
}
}
Output:
Enter the number of rows:
5
Enter the number of columns:
3
15 16 17
20 21 22
25 26 27
30 31 32
35 36 37
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.