Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Print grid of numbers using nested loops

1. ## Print grid of numbers using nested loops

Hello. I've been trying to write the code for the following program, and I have a majority of it completed. The one thing I'm having trouble with is determining the equation to actually print the numbers. Any help? Thanks!

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.
Code:
```public*static*void*printGrid(int*rows,*int*cols){
for(int*row=1;row<rows;row++){
for(int*col=1;col<cols;col++){
int*result=rows*cols;
System.out.print(result+",*");
}
System.out.println();
}
}```

• Changing for column major ordering in two nested loops simply changes how you calculate the corresponding entry. Effectively, you need to take the row, and add to it the value of the number of total rows * the column in question. Depending on your loop initial position depends if you add one to the row after calculation, or if you subtract one from the column during calculation. I'll do the column.
PHP Code:
```     public static void printGrid(int iRows, int iCols)    {        StringBuilder sb = new StringBuilder();        for (int r = 1; r <= iRows; ++r)        {            for (int c = 1; c <= iCols; ++c)            {                if (c > 1)                {                    sb.append(", ");                }                sb.append((iRows * (c - 1)) + r);            }            sb.append("\n");        }                System.out.println(sb.toString());    }  ```
And simple as that.

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•