Results 1 to 3 of 3
  1. #1
    cliffh is offline Member
    Join Date
    Sep 2010
    Posts
    9
    Rep Power
    0

    Default two dimensional arrays

    I have created a two dimensional array that gets the number of rows, columns, number to start with, and how much to count by :
    int [][] matrix = new int[r][c];
    for (int i = 0; i<r; i++) {
    for (int j = 0; j<c; j++){
    matrix [i][j] = starting;
    starting= starting + count;
    System.out.print(matrix[i][j] + " ");


    }
    System.out.println();


    }

    Which prints out:
    Original matrix:
    2 6 10 14 18
    22 26 30 34 38
    42 46 50 54 58


    How do I change this so the rows are printed as columns and the columns are printed as rows? So it prints:

    Transposition matrix:
    2 22 42
    6 26 46
    10 30 50
    14 34 54
    18 38 58

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Don't print out the results in the same nested for loops where you fill your array. Instead fill the array first, then use a new set of nested for loops to print out your array values, but in this second set of for loops, you'll reverse the order of the loops -- the outer loop will loop on the columns and the inner loop on the rows.

  3. #3
    cliffh is offline Member
    Join Date
    Sep 2010
    Posts
    9
    Rep Power
    0

    Default

    Perfect! Thanks a bunch!

    int [][] matrix = new int[r][c];
    for (int i = 0; i<r; i++) {
    for (int j = 0; j<c; j++){
    matrix [i][j] = starting;
    starting= starting + count;
    }

    }

    for (int i = 0; i<r; i++) {
    for (int j = 0; j<c; j++){
    System.out.print(matrix[i][j] + " ");
    }
    System.out.println();


    }
    System.out.println("");
    System.out.println("Transposition matrix:");
    for (int j = 0; j<c; j++){
    for (int i = 0; i<r; i++){
    System.out.print(matrix[i][j] + " ");
    }
    System.out.println();
    }

Similar Threads

  1. Printing Two Dimensional Arrays with for loops
    By mcnam4119 in forum JCreator
    Replies: 3
    Last Post: 10-06-2010, 05:27 AM
  2. Replies: 4
    Last Post: 08-01-2010, 09:25 AM
  3. dynamic two dimensional arrays?
    By dinosoep in forum New To Java
    Replies: 4
    Last Post: 12-05-2009, 06:12 PM
  4. Multi-dimensional arrays
    By Implode in forum New To Java
    Replies: 1
    Last Post: 09-15-2009, 08:50 AM
  5. [SOLVED] Multi-dimensional arrays
    By thelinuxguy in forum Advanced Java
    Replies: 3
    Last Post: 05-07-2009, 02:52 PM

Posting Permissions

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