Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Jul 2012
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    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();
        }
    }
    Attached Thumbnails Attached Thumbnails Print grid of numbers using nested loops-screen-shot-2012-07-20-10.59.41-pm.png  

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    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 iRowsint iCols)
        {
            
    StringBuilder sb = new StringBuilder();
            for (
    int r 1<= iRows; ++r)
            {
                for (
    int c 1<= iCols; ++c)
                {
                    if (
    1)
                    {
                        
    sb.append(", ");
                    }
                    
    sb.append((iRows * (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
    •