Search code examples
javaarraysoutput-formatting

Output formatting in array and how to take values outside of for loop


I want the output to appear after the dotted line.Sum of each column must appear beneath its column,i tried inserting the result in an array but i am not able to take it outside of for loop.

public class SumOfColumn 
{
public static void main(String[] args) 
 {
    int i,j;
    int a[][]={{22,33,44,11},{33,55,77,11},{44,11,88,55},{33,55,22,77}};
    for(i=0;i<4;i++)
     {
         int sum=0;
         for(j=0;j<4;j++)
         {
             System.out.print(a[i][j]+ "\t" );
             sum = sum + a[j][i];
         }
    System.out.println(sum);    
    System.out.println();
    }
        System.out.println("-------------------");
    }
}

This is the output where result is appearing in front of rows i want the result below each column and below the dotted line

22  33  44  11  132

33  55  77  11  154

44  11  88  55  231

33  55  22  77  154

----------------

Solution

  • Declare a result value outside the scope of of the for() loop. Something like this oughta do it (not tested, though)

    public class SumOfColumn 
    {
    public static void main(String[] args) 
     {
        int i,j;
        int a[][]={{22,33,44,11},{33,55,77,11},{44,11,88,55},{33,55,22,77}};
        int res[]={0,0,0,0};
        for(i=0;i<4;i++)
         {
             int sum=0;
             for(j=0;j<4;j++)
             {
                 System.out.print(a[i][j]+ "\t" );
                 sum = sum + a[j][i];
             }
            res[i]=sum;
            System.out.println(sum);    
            System.out.println();
        }
        System.out.println("-------------------");
        for(i=0;i<4;i++)
        {
            System.out.print(res[i]+ "\t" );
        }
        System.out.println();
       }
    }