c. (10 points) Write a static method named printGrid that accepts two integer pa
ID: 3720727 • Letter: C
Question
c. (10 points) Write a static method named printGrid that accepts two integer parameters rows and cols. The output is a comma-separated grid of numbers where the first parameter (rows) represents the number of rows of the grid and the second parameter (cols) represents the number of columns. The numbers count up from 1 to (rows x cols) The output are displayed in column-major order, meaning that the numbers shown increase sequentially down each column and wrap to the top of the next column to the right once the bottom of the current column is reached. You may assume that both parameters passed to your method are greater than 0 Here are some example calls to your method and their expected results Call Output1, 4, 7, 10, 13, 16 rintGrid(1,3); 1, 2,3 rintGrid(5,3); 1, 6, 11 2,7, 12 3, 8. 13 4, 9, 14 5, 10, 15 rintGrid(3,6); rintGrid(4,1 2, 5, 8, 11, 14, 17 3, 6,9,12, 15, 18 4Explanation / Answer
//Code to copy
//Test java program for printGrid method
//PrintGridTester.java
public class PrintGridTester
{
public static void main(String[] args)
{
System.out.println("printGrid(3, 6)");
//calling printGrid method
printGrid(3, 6);
System.out.println("printGrid(5, 3)");
//calling printGrid method
printGrid(5,3);
System.out.println("printGrid(4, 1)");
//calling printGrid method
printGrid(4,1);
System.out.println("printGrid(1,3)");
//calling printGrid method
printGrid(1,3);
}
/**The static method printGrid takes number of rows
* and number of columns and then print the grid
* on console.*/
public static void printGrid(int rows, int columns)
{
//run for number of rows
for(int i = 1; i <= rows; i++)
{
//find the end of the row value
int end = i + rows * (columns - 1);
//continue the inner for loop
//that runs until the row j becomes end
for(int j = i; j <= end; j += rows)
{
System.out.print(j);
if(j != end)
{
System.out.print(", ");
}
}
System.out.println();
}
System.out.println();
}
}
Sample Output:
printGrid(3, 6)
1, 4, 7, 10, 13, 16
2, 5, 8, 11, 14, 17
3, 6, 9, 12, 15, 18
printGrid(5, 3)
1, 6, 11
2, 7, 12
3, 8, 13
4, 9, 14
5, 10, 15
printGrid(4, 1)
1
2
3
4
printGrid(1,3)
1, 2, 3
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.