140 likes | 229 Views
Quest Review 1: Loops. While Loop. Mr. Tan gives you an array, randIntsForTan , with random integers in it. You need to tell him the sum of all the even integers in the array. You decide to write a while loop to accomplish this.
E N D
While Loop • Mr. Tan gives you an array, randIntsForTan, with random integers in it. You need to tell him the sum of all the even integers in the array. You decide to write a while loop to accomplish this. • Write the while loop that will find the sum of all the even integers in the array.
While Loop int sum = 0;int index = 0; while(index<randIntsForTan.length) { if (randIntsForTan[index]%2==0) { sum += randIntsForTan[index]; } index++; }
For Loop • Mr. Tan is happy that you wrote such a well-written while loop, but was expecting that you would write a for loop instead since they are faster to write than while loops. • Change the while loop that you just wrote into a for loop.
For Loop int sum = 0; for(inti= 0; i<randIntsForTan.length, i++) { if (randIntsForTan[i]%2==0) { sum += randIntsForTan[i]; } }
For-Each Loop • Mr. Tan is pleased that you know how to convert while loops into for loops so easily, but would like to also make sure that you can use the for-each loops. • Convert your for loops into for-each loops to prove to him that you know your stuff.
For-Each Loop int sum = 0; for(intnum : randIntsForTan) { if (num%2==0) { sum += num; } }
Array Loops • The following program segment is intended to find the index of the first negative integer in arr[0]…arr[N-1], where arr is an array of N integers. Will it work? When will it work? inti = 0; while(arr[i] >= 0) { i++; } location = i;
Array Loops • Needs at least one negative integer • Change to: inti = 0; while(i<arr.length) { if (arr[i] < 0) { break; } i++; } location = i;
Array Loops • Consider the following code segment: int sum = arr[0]; inti = 0; while(i < arr.length) { i++; sum += arr[i]; } What is the result of executing the segment?
Array Loops • How would you rewrite the while loop? int sum = arr[0]; inti = 0; while(i < arr.length) { i++; sum += arr[i]; } • How about as a for loop? For each loop?
Array Loops • The following code fragment is intended to find the smallest value in arr[0]…arr[n-1] int min = arr[0]; inti = 1; while(i<n) { i++; if (arr[i] < min) { min = arr[i]; } } What changes need to be made?
Array Loops Array arr1 contains elements arr1[0]…arr1[N-1], where N is arr1.length int count = 0; for (inti = 0; i<N; i++) { if (arr1[i] != 0) { arr1[count] = arr1[i]; count++; }} int[] arr2 = new int[count]; for(inti = 0; i<count; i++) { arr2[i] = arr1[i]; } If array arr1 initially contains the elements 0, 6, 0, 4, 0, 0, 2 in this order, what will arr2 contain after execution of the code segment?
0, 6, 0, 4, 0, 0, 2 • 6, 6, 0, 4, 0, 0, 2 • 6, 4, 0, 4, 0, 0, 2 • 6, 4, 2, 4, 0, 0, 2 • arr2 6, 4, 2