Write a method named printGrid that accepts two integer parameters rows and cols
ID: 3630167 • Letter: W
Question
Write a 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. Assume that rows and cols are greater than 0.example:
printGrid(3,6);
the output should be
1, 4, 7, 10, 13, 16
2, 5, 8, 11, 14, 17
3, 6, 9, 12, 14, 17
printGrid(1,3);
output:
1, 2, 3
Explanation / Answer
public static void printGrid(int rows, int cols)
{
// iterate over rows
for(int r = 0; r < rows; r++)
{
// first value in row is r+1
int curr = r+1;
String temp = "";
// iterate through columns
for(int c = 0; c < cols; c++)
{
temp += curr + ", ";
// curr gets incremented by number of rows
curr += rows;
}
// remove the extra comma
temp = temp.substring(0, temp.length()-2);
System.out.println(temp);
}
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.