Search code examples
javaloopsrownested-loops

Array 2-D in java


I want to write a java program that prints the average of each row of a two-dimensional array but it works only on the first row. I didn't know what is the problem.

This is the code:

    int [][] A = new int[r][c];

    for (int i=0;i<A.length;i++)
    {
        System.out.println("Enter the elements of the row number: "+(i+1));
        for (int j=0; j<A[i].length;j++)
            A[i][j]=kbd.nextInt();
    }

    int sum = 0, avg =0;
    for (int i=0; i<A.length;i++)
    {
        for (int j=0; j<A[i].length;j++) {
            sum += A[i][j];
            avg = sum/A[i].length;
        }
        
        System.out.println("The average of the row number: "+(i+1)+" is: "+avg);
    }

}

Solution

  • You need to reset sum to zero every time you loop. This can be fixed by declaring the sum variable inside the for-loop instead of outside. Also avg and sum should be a double instead of a int:

    for (int i=0; i<A.length;i++)
    {
        double sum = 0;
        double avg =0;
        for (int j=0; j<A[i].length;j++) {
            sum += A[i][j];
            avg = sum/A[i].length;
        }
        
        System.out.println("The average of the row number: "+(i+1)+" is: "+avg);
    }