Given this JAVA programming snippet, complete the modDoubleArrayBy method and st
ID: 3697921 • Letter: G
Question
Given this JAVA programming snippet, complete the modDoubleArrayBy method and state what the code will print out.
public static void main(String[] args){
int [] array = {1,2,3,4,5};
int [] [] dub = new int[array.length] [array.length];
for (int i=0; i<dub.length;i++)
{
for (int j=0;j<dub[i].length;j++)
{
dub[i][j] = array[j]*i;
}
}
/*modDoubleArrayBy is method that takes in two parameters: a 2D
* array of ints and an int value. It returns a 2D array of the same size
* as the parameter array with all the values mod'ed (%) by the value parameter.
* YOU HAVE TO WRITE THIS METHOD
*/
dub = modDoubleArrayBy(dub,2);
for(int i=0;i<dub.length;i++)
{
for(int j=0;j<dub[i].length;j++)
{
System.out.print(dub[i][j]+ " ");
}
System.out.println();
}
Explanation / Answer
ArrayOperation.Java
package com.chegg.questions;
public class ArrayOperation {
public static void main(String[] args) {
int[] array = { 1, 2, 3, 4, 5 };
int[][] dub = new int[array.length][array.length];
for (int i = 0; i < dub.length; i++) {
for (int j = 0; j < dub[i].length; j++) {
dub[i][j] = array[j] * i;
}
}
System.out.println("Elements in the array before modDoubleArrayBy call");
for (int i = 0; i < dub.length; i++) {
for (int j = 0; j < dub[i].length; j++) {
System.out.print(dub[i][j] + " ");
}
System.out.println();
}
dub = modDoubleArrayBy(dub, 2);
System.out.println("Elements in the array After modDoubleArrayBy call");
for (int i = 0; i < dub.length; i++) {
for (int j = 0; j < dub[i].length; j++) {
System.out.print(dub[i][j] + " ");
}
System.out.println();
}
}
private static int[][] modDoubleArrayBy(int[][] dub, int num) {
int[][] newDub = new int[dub.length][dub.length];
for (int i = 0; i < dub.length; i++) {
for (int j = 0; j < dub[i].length; j++) {
int val = dub[i][j] % num;
newDub[i][j] = val;
}
System.out.println();
}
return newDub;
}
}
Output:
Elements in the array before modDoubleArrayBy call
0 0 0 0 0
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
Elements in the array After modDoubleArrayBy call
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.