CPSC 124, Fall 2021: Sample Answers to Quiz #4

These are sample answers only.

Question 1. Show the exact output from the following code segment:

   int i, sumSoFar;
   sumSoFar = 0;
   for ( i = 1; i < 6; i++ ) {
       sumSoFar = sumSoFar + i;
       System.out.println( i + ": " + sumSoFar );
   }

Answer.

          1: 1
          2: 3
          3: 6
          4: 10
          5: 15

(In each iteration of the loop, the new value assigned to sumSoFar is the sum of the current value of sumSoFar and the current value of i. The first time through the loop i is 1, and sumSoFar becomes 0+1; the second time, it becomes 1+2; the third time, it becomes 3+3; the fourth time, it becomes 6+4; and the fifth time it becomes 10+5. Then i becomes eaual to 6, and the loop ends.)

Question 2. Explain carefully what is accomplished by each of the two lines in the following Java code segment:

     int[] values;
     values = new int[ 100 ];

Answer. The first line creates a variable of type int[]. This only creates a variable. It has not yet created an array, but the variable is capable of refering to an array. The second line creates an array that can hold 100 values of type int. Initially, all of the values in the array are zero. The variable values is set to refer to that new array. So, after that statement, values.length is 100, and the 100 array elements are values[0], values[1], ..., values[99].

Question 3. Suppose that names is a variable of type String[], and that the array names has already been created and filled with data. The values in the array are strings. Write a code segment that will print out every string in the array that begins with the letter 'A'. Use a for loop. (For full credit, take into account that some of the strings might have length zero.)

Answer.

    int index;
    String oneName;  // one of the names from the list.
    for (index = 0; index < names.length; index++) {
        oneName = names[index];
        if (nameName.length() > 0 && oneName.charAt(0) == 'A') {
            System.out.println(oneName);
        }
    }