Assume that mat is a N by N 2D array that stores N2 integers

Assume that mat is a N by N 2-D array that stores N^2 integers write Java code to sum only the integers in the last column of mat write Java code to sum only the integers in first row of mat. write Java code to sum the integers in the major diagonal of mat. Given the following java program, write down the output in the correct order.

Solution

Ans a) : Program : for sum of last column for 2-D array NxN

public class Twoarray{
   public static void main(String [] args){
   int [][] myarray = new int [N][N]
   int randomGenerator = new Random();
  
   for(int i=0 ; i<N ; i++){
       for(int j=0 ; j<N ; j++){
           random = randomGenerator.nextInt(100);
           myarray[i][j] = random;
       }  
   }
   int sum=0;
   for(int i=0 ; i<N ; i++){
       for(int j=N-1 ; j<N ; j++){
           sum += myarray[i][j];
       }
   }
   system.out.println(sum);
   }
}

Ans b) : Program : for sum of first row for 2-D array NxN

public class Twoarray{
   public static void main(String [] args){
   int [][] myarray = new int [N][N]
   int randomGenerator = new Random();
  
   for(int i=0 ; i<N ; i++){
       for(int j=0 ; j<N ; j++){
           random = randomGenerator.nextInt(100);
           myarray[i][j] = random;
       }  
   }
   int sum=0;
   int i=0,j=0;
   do{
       sum += myarray[i][j];
       j++;
   }while(j<N)
   }
   system.out.println(sum);
   }
}

Ans c) : Program : for sum of major diagonal for 2-D array NxN

public class Twoarray{
   public static void main(String [] args){
   int [][] myarray = new int [N][N]
   int randomGenerator = new Random();
  
   for(int i=0 ; i<N ; i++){
       for(int j=0 ; j<N ; j++){
           random = randomGenerator.nextInt(100);
           myarray[i][j] = random;
       }  
   }
   int sum=0;
   for(i=0 ; i<N ; i++){
       for(j=0; j<N ; j++){
           if(i==j)
               sum += myarray[i][j];
           else
               break;
       }
   }
  
   system.out.println(sum);
   }
}

 Assume that mat is a N by N 2-D array that stores N^2 integers write Java code to sum only the integers in the last column of mat write Java code to sum only t
 Assume that mat is a N by N 2-D array that stores N^2 integers write Java code to sum only the integers in the last column of mat write Java code to sum only t

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site