CS102 1819 Spring Midterm Sol
CS102 1819 Spring Midterm Sol
(b) Write the contents of nums2 array after this program segment is executed. idx remain j
0 0 0
int[] nums = {71, 20, 8, 16, 7, 10}; 1
int[] nums2 = new int [nums.length]; 1 2
int idx = 0; 2 3
for (int remain = 0; remain < 2; remain++) 3 4
{ 5
for (int j = 0; j < nums.length; j++)
{
4 6
if (nums[j] % 2 == remain) 1 0
{ 5 1
nums2[idx] = nums[j]; 2
idx++; 3
} 4
} 6 5
} 6
2
Contents of nums2:
20 8 16 10 71 7
(Bonus + 5 points) Explain in english the task performed in (b) by the statements starting from the
statement: int idx = 0;
This program segments fills the array nums2 first by taking the even
values in nums, and then by taking the odd values in nums.
C102 - Midterm 1 01 April 2019
KEY
(c) Output:
int k = 20; 024681012141618
do
{ 02468101214
for (int j = 0; j < k; j += 2) 0246810
System.out.print (j);
0246
System.out.println ();
k -= 4; 02
} while (k > 0);
public class Q4
{
public static void main (String[] args) throws IOException
{
// Open file:
Scanner fileScan = new Scanner (new File("grades.txt"));
int numInt = 0;
double sum = 0, max = 0, min = 100;
// While there is something in the file, read it.
while (fileScan.hasNext())
{
double n = fileScan.nextDouble(); // Read next double.
numInt++; // Increment counter.
sum += n; // Add to sum
if (n > max) // Check for max
max = n;
if (n < min) // Check for min
min = n;
}
fileScan.close(); // Close file stream.
double ave = sum / numInt; // Compute average
System.out.println ("Number of grades: " + numInt);
// System.out.printf ("Number of grades: %d\n", numInt);
// System.out.println ("Sum = " + sum + " Average = " + ave);
System.out.printf ("Sum = %.2f Average = %.2f\n", sum, ave);
System.out.println ("Max = " + max + " Min = " + min);
// System.out.printf ("Max = %.2f Min = %.2f\n", max, min);
}
}