How to iterate through columns [rows] of a multi dimensional array

后端 未结 4 1532
庸人自扰
庸人自扰 2020-12-05 21:07

I am using a multi-dimensional array to store the total amount of product sold (products range 1 to 5) by a particular salesperson (1 to 4 salespersons).

T arranged

相关标签:
4条回答
  • 2020-12-05 21:52

    To iterate over a single row k in a two-dimensional array:

    for (int j = 0; j < multiarray[k].length; j++)
        multiarray[k][j]; // do something
    

    And to iterate over a single column k in a two-dimensional array:

    for (int i = 0; i < multiarray.length; i++)
        multiarray[i][k]; // do something
    
    0 讨论(0)
  • 2020-12-05 21:58

    Lets say you have a two dimensional array as

    int[][] salesData={{13, 23, 45, 67, 56},
                                    {43, 65, 76, 89, 90},
                                    {43, 45, 76, 98, 90},
                                    {34, 56, 76, 43, 87}};
    

    so it is a 4*5 matrix

    int[0] represents the the 1st row i.e the {13, 23, 45, 67, 56} if you need the value in individual cell you need to iterate 2 for each loop like

        for (int[] rowData: salesData){
                    for(int cellData: rowData)
                    {
    System.out.printn("the indiviual data is" +cellData);
                    }
                }
    
    0 讨论(0)
  • 2020-12-05 22:01

    First off, don't use all your code if it's not needed. You only need the declaration and maybe one for-loop.

    Loop through columns:

    for(int i=0; i<monthlySales[salesPerson].length; i++) {
        monthlySales[i][salesPerson]; //do something with it!
    }
    
    0 讨论(0)
  • 2020-12-05 22:07

    Got it:) Bit of a headwreck trying to visualise the array but got there eventually, cheers for the help

    //loop thorugh each column to get total products sold
        for (int product = 0; product < salesTotals[0].length; product++) {
            int totalProduct = 0;
            for (int salePerson = 0; salePerson < salesTotals.length; salePerson++) {
    
                totalProduct += salesTotals[salePerson][product];
    
            }//end inner for
            System.out.printf("%10d", totalProduct);
    
        }//end outer for
    
    0 讨论(0)
提交回复
热议问题