Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Please answer all the following question in java language. 1. Declare and create

ID: 3694626 • Letter: P

Question

Please answer all the following question in java language.

1. Declare and create an int array with name: myArray and 15 elements.

2. Declare and initialize a two-dimension (4*3) String array with name my2DArray.

3.Given a two-dimension integer array: my2Darray, display all element values. You should complete it twice: one to use regular for statement and the other to use enhanced for statement.

4.Create a function using Variable-length Argument. Parameters’ type is int, and thisfunction will print out the sum of all element values on the screen.

Explanation / Answer

1)

Syntax for declaring an array variable:

The term datatype is the predefined data types such as int,float,char,....

Example:

int[] myArray;

To create an array use the following syntax:

arrayVar = new dataType[size of array];

Example:

myArray = new int[15];

Thus , to declare and create a int array is

int[] myArray = new int[15];

2)

Syntax for declaring an two-dimensional array variable:

The term datatype is the predefined data types such as string,....

Example:

String[][] my2DArray;

To create a two-dimensional array use the following syntax:

arrayVar = new dataType[rowSize][colSize];

Example:

my2DArray = new String[4][3];

Thus , to initialize a 2D array:

{ {"1", "2","3"}, {"1", "2","3"}, {"1","3", "3"}, {"1","3", "3"} };

3)

Two dimensional int array declaration and creation gives:

int[][] my2DArray = new int[3][3];

//Using for loop for setting the array

for (int i = 0; i < my2DArray.length; i++) {
   for (int j = 0; j < my2DArray[i].length; j++) {
       my2DArray[i][j] = i + j;
   }
}

//To print the array

for (int[] a : my2DArray) {
   for (int i : a) {
       System.out.print(i + " ");
   }
   System.out.println(" ");
}

Here for loop is used to store the values and Enhanced for statement that is foreach is used to print the elements.

4)

Here the function has a array input argument and it prints sum of all the elements:

/** the snippet returns thesum of all elements*/
public static void myFunction(int[] A) {
   float sum = 0;
for(int i=0;i<A.length;i++){
       sum = sum + A[i];
}
System.out.println("Sum of all elements: %.1f",sum);
}

Thus ,int array with variable length is passed to function and output is returned.