Printing all elements of a 2D array in Java

The issue arises when attempting to provide a function with a single array of strings, while the input is a double array of strings. Moreover, computing the average outside the loop and then proceeding with the checking can be a feasible solution.

Solution 1:

To avoid losing the calculated value from the previous iteration, it is recommended to declare the


variable before the start of your second loop instead of declaring it inside the loop. Moreover, you can calculate the average value outside the loop and then proceed with your checking, as shown in the example below:

int n=2;
int m=3;   
int[][] mark = { { 67,80,56 }, { 32,26,31} };    
// grade function
for (int i = 0; i < n; i++) {
    int sum=0;
    for (int j = 0; j < m ; j++) {
        sum=sum+ mark[i][j];
    int avg = sum / m;
//your code to check pass/fail

To print values for each row, avoid using return and opt for print instead.


Solution 2:

To print the grade of each student individually, it is necessary to invoke the grade method for every student’s marks. This can be accomplished by placing the method call within a for loop.

for(int i = 0; i < n; i++) {

As a result, your method’s definition undergoes a modification.

public static String grade(int mark[]) {

Finally, your


validation will inevitably fail since


is unreachable within the for loop due to


calculation of the sum of array elements.

public static String grade(int mark[][])
    int m = 5, avg = 0;
    int sum = 0;
    for(int j = 0;j < m; j++) {
        sum = sum + mark[i][j];
    avg = sum / m;
    if(avg >= 90)
        return "A+";
    else if(avg < 40)
        return "F";

Frequently Asked Questions