On the following code that contains a method which returns a

On the following code that contains a method which returns a new matrix (2-d array) with same number of rows and columns as has its parameter (matrix). Each entry in the returned array should equal the result of multiplying the entry at the same row and column in matrix by the value of scalar. code:

package edu.buffalo.cse116;

/** * Class which contains a method which takes in a 2-dimensional array and a scalar value and returns their product. */ public class ScalarMult { /** * Allocates a new 2-d array and then sets each entry to be the product of {@code scalar} and the entry in * {@code matrix} at the same row and column. This was inspired by the only \"joke\" told by my calculus teacher:
* Why can\'t you cross a mountain climber and a grape? Because you cannot cross a scalar.
*
* Yeah, I did not find it funny either. * * @param matrix 2-d array which we would like to have multiplied by the given value. * @param scalar The new matrix will be equal to having each entry in {@code matrix} multipled by this value. * @return The product of this matrix and constant value. */

public int[][] scalarMult(int[][] matrix, int scalar) { } }

Solution

public class ScalarMult {

   public ScalarMult() {
       // TODO Auto-generated constructor stub
   }

   public int[][] scalarMult(int[][] matrix, int scalar){
      
       for(int i=0;i<matrix.length;i++){
           for(int j=0;j<matrix[i].length;j++){
               matrix[i][j] = scalar*matrix[i][j];
           }
       }
       return matrix;
   }
  
   public static void main(String[] args) {
      
       ScalarMult sm = new ScalarMult();
       int[][] matrix = {{2,3,4},{5,6,7}};
       System.out.println(\"Original Matrix:\");
       for(int i=0;i<matrix.length;i++){
           for(int j=0;j<matrix[i].length;j++){
               System.out.print(matrix[i][j]+\" \");
           }
           System.out.println();
       }
       sm.scalarMult(matrix, 2);
       System.out.println(\"After Multiplication: \");
       for(int i=0;i<matrix.length;i++){
           for(int j=0;j<matrix[i].length;j++){
               System.out.print(matrix[i][j]+\" \");
           }
           System.out.println();
       }
   }

}

On the following code that contains a method which returns a new matrix (2-d array) with same number of rows and columns as has its parameter (matrix). Each ent

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site