BASHA TECH

Linear Data Structures : 1.1 Arrays 본문

Computer/Java

Linear Data Structures : 1.1 Arrays

Basha 2023. 4. 7. 16:52
728x90

1. Considering the following code snippet.

int[] data = new int[]{1, 3, 5, 7, 9};

=> the value of data[3] is 7.

In Java and many other programming languages, array elements are accessed using an index starting from 0. So, data[3] refers to the element at the 4th index of the array, which is 7 in this case.

 

* cf. the value of data[9] => In the given Java code, data[9] will result in a runtime error because the "data" array contains only 5 elements with indices ranging from 0 to 4. Therefore, trying to access data[9] would be an attempt to access an element beyond the boundary of the array and will result in an "ArrayIndexOutOfBoundsException".

 

Explanation : The first position in an array is [0]. So data[0] stores an integer of value 1, data[1] stores an integer of value 3, and so on. Trying to execute data[9] in this array results in an IndexOutOfBoundsException, as the array only has five elements.

 

2. An integer array named data is initialized with the following values: {1,2,3,4,5}. This array is passed as argument in the following method. what are the values for the array after returning from this method?

publicvoidmethod(int[] data) {
    for (int i = 0; i < data.length; i += 2) {
        data[i] = 0
    }
}

=> 0,2,0,4,0

After the execution of the "method" with the given code, the integer array "data" will have every other element set to 0.

For example, if the initial values of the "data" array are {1, 2, 3, 4, 5, 6}, the values of the "data" array after returning from the "method" will be {0, 2, 0, 4, 0, 6}.

The elements at even indices (i.e., 0, 2, 4, ...) will be set to 0 by the method, while the elements at odd indices (i.e., 1, 3, 5, ...) will remain unchanged.

 

Explanation : The method modifies the values in positions 0, 2 and 4 of the array, assigning value 0 to all of them. Changes in the array persist once the method ends. In Java, changes in objects and arrays passed as arguments in a method persist after the method ends, while changes in primitive types passed as arguments in a method do not persist after the method ends.

 

3. Choose the correct answer for the following code snippet

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

=> It's not correct bc data has not been created yet.

 

Explanation : Arrays need to be initialized before they can store information. In this code snippet the array data has been declared, but not initialized. When creating the array its length is defined and the corresponding space in memory is allocated. If we write this code in a Java program we will get a compilation error indicating that the local variable data may have not been initialized

 

cf. why this answer is wrong? => it's incorrect bc data doesnt have an attrivut called length

The given code is attempting to access the "length" attribute of the integer array "data" using the dot operator, but the array has not been initialized with any values.

In Java, arrays must be initialized before they can be used. If an array is not initialized, it will have a default value of "null". Therefore, attempting to access the "length" attribute of a null array will result in a runtime error called "NullPointerException".

To fix this error, the "data" array needs to be initialized with a size and assigned to a new integer array object using the "new" keyword. For example:

int[] data = new int[5]; // creates a new integer array object with a size of 5
for (int i = 0; i < data.length; i++) {
    data[i] = 0;
}

In this case, the for loop will iterate over each element of the "data" array and set its value to 0, as intended.

 

4. For an array called data of size N, the time to retrieve the information stored in the last element of the array (data[N-1])...

=> ...is approximately the same time it takes to retrieve the information stored in the first element of the array (data[0]).

 

Explanation : In Java, arrays use contiguous blocks of memory, which are allocated at the time of creating the array. We know where the position of each data of the array in memory is, therefore the access time to each data is approximately the same.

 

5. Which of the following algorithms on arrays is typically less computationally expensive?

=> Retrieving the information contained in the last position of the array.

 

Retrieving the information contained in the last position of the array is typically less computationally expensive than performing other operations on arrays.

This is because accessing the last element of an array can be done in constant time (i.e., O(1)) with a single array index operation, regardless of the size of the array.

In contrast, some array operations, such as searching for a specific element or sorting the array, may require a linear search through the array, which has a time complexity of O(n), where "n" is the number of elements in the array.

Therefore, accessing the last element of an array is generally considered to be a fast and efficient operation in terms of computational complexity.

 

Explanation : Dividing an array into two halves, and concatenating two arrays imply the need for creating new arrays, as the size of the array is defined at creation time. Inserting new information in the first empty position requires checking the information stored position by position until an empty position is found. Retrieving the information contained in the last position of the array requires only one instruction (array[array.length-1];)

 

cf. Inserting new information in the first empty position of the array. =>

Inserting new information in the first empty position of the array may have varying computational complexity depending on the size of the array and the number of empty positions before the first one.

If the first empty position is known and available, inserting new information can be done in constant time (i.e., O(1)) with a single array index operation, similar to accessing the last element of an array.

However, if the first empty position is not known and the array needs to be searched for an empty position, then the computational complexity can become linear (i.e., O(n)), where "n" is the number of elements in the array. This is because the algorithm needs to search through the array to find the first empty position and then insert the new information, which can take longer as the size of the array increases.

Therefore, the computational complexity of inserting new information in the first empty position of an array can vary depending on the circumstances, but it can generally be faster than some other array operations like sorting or searching if the empty position is known and available.

 

6.  Have a look at the following code snippet. what is it doing?

privateintmethod(int[] array) {
    int var = array[0];
    for (int i = 0; i < array.length; i++) {
        if (array[i] > var) {
            var = array[i];
        }
    }
    return var;
}

=>Returning the maximum value of the array.

 

Explanation : This code returns the maximum value of the array. It starts storing array[0] in var and then compares element by element of the array to check if these are higher than array[0]. If that is the case then var is updated with the higher value. At the end var is storing the maximum of the array.

 

7. Have a look at the following code snippet. what would be returnd by this method?

privateintmethod(int[] array) {
    int var = 0;
    for(int i = 0; i < array.length; i++){
        var+=array[i];
    }
    return var;
}

=> The sum of the integer elements in array.

 

Explanation : The code traverses the array storing in var the sum of the integer elements that have been traversed until that moment. Every new integer element is added to var with the statement var+=array[i];

 

8. Have a look at the following code snippet. What is it doing?

privateintmethod(int[] array) {
    int value = array[0];
    int var = 0;
    for(int i = 1; i < array.length; i++){
        if (array[i]>value){
            var++;
        }
    }
    return var;
}

=> Returning the number of values of the array that are higher than array[0].

 

Explanation : This code returns the number of values of array that is higher than array[0]. The code traverses array with a for loop, checks if the following value in array is higher than args[0] with the statement if (array[i]>value), and if so, increments var by one.

 

9. Have a look at the following code snippet. if int[][]array = {{16,3,2,13}, {5,10,11,8}, {9,6,7,12}, {4,15,14,1}}. what is var[] storing after running this code?

privatevoidmethod(int[][] array) {
    int[] var =new int[array[0].length];
    for (int i = 0; i < array.length; i++){   
        for (int j = 0; j < array[i].length; j++){                
            var[j] += array[i][j];
        }
    }  
}

=> Four integers of value 34, which correspond to the sums of the columns of the bidimendional array

 

Explanation : This code calculates the sum of the columns of the bidimensional array, traversing the bidimensional array row by row. i indicates the row and j the column, so first the row i is traversing column by column (j changes its value) and when all the columns are traversing, i increments (the next row is traversing) and repeat the same process.

 

The given code is a Java method that takes a 2D integer array "array" as input and does not return any value (i.e., the return type is "void").

The method initializes a new 1D integer array "var" with a length equal to the length of the first row of the input array. Then, it iterates over each element of the input array using two nested for loops.

In each iteration of the outer loop, the method iterates over the elements of the current row (i.e., the inner array) and adds their values to the corresponding elements in the "var" array. Specifically, the "jth" element of the "var" array is updated by adding the value of the "jth" element in the current row of the input array.

At the end of the method, the "var" array is not returned or printed, so its contents are not displayed by the method.

Therefore, we cannot determine the exact values stored in the "var" array after running this code without further inspection.

 

The answer is correct because the given code is designed to compute the sum of each column in a 2D array and store the result in a 1D array named "var".

The input array array = {{16,3,2,13},{5,10,11,8},{9,6,7,12},{4,15,14,1}} has four columns, and the sum of each column is 34. Therefore, after running the code with this input, the "var" array will contain four integers of value 34, where each integer represents the sum of a column in the input array.

So the correct answer to "What is var[] storing after running this code?" is "Four integers of value 34, which correspond to the sums of the columns of the bidimensional array."

 

cf. The answer "Four integers of value 34, which correspond to the sums of the rows of the bidimensional array" is not correct, because the given code is designed to compute the sum of each column in a 2D array, not the sum of each row.

The "var" array is declared as an integer array with a length equal to the number of columns in the input 2D array "array". In the nested for loop, the code iterates over each element in the 2D array "array", adding the value of each element to the corresponding index in the "var" array based on the inner loop index. This results in the "var" array containing the sum of each column in the input array, not the sum of each row.

Therefore, the correct answer is "Four integers of value 34, which correspond to the sums of the columns of the bidimensional array."

 

 

728x90
반응형

'Computer > Java' 카테고리의 다른 글

Week 1. Summary  (0) 2023.04.07
Java#CH08. 입출력 스트림과 파일 입출력  (0) 2022.07.30
Java#CH07. 자바 스레드 기초  (0) 2022.07.30
Java#CH06. 컬렉션과 제네릭  (0) 2022.07.30
Java#CH05. 상속  (0) 2022.07.30
Comments