Rohan G CollegeBoard Unit 6 Arrays
Week 9 Arrays
// Hack 1
int[] arrayOne = {1, 3, 5, 7, 9};
for (int i = 0, arrayOne.length, i==) {
}
Hack 2 Which of the following is FALSE about arrays
A. A java array is an object B. Length of array can be changed after creation of array C. Numerical data types of arrays are initialized to 0 to start
B.
// Hack 3
int[] myNumbers = new int[] {5, 3, 4, 1, 2};
Arrays.sort(myNumbers);
for (int num: myNumbers) {
System.out.println(num);
}
// Hack 4
for ( int k = 0; k < a.length; k++ )
{
while ( a[ k ] < temp )
{
a[ k ] *= 2;
}
}
// Hack 5
public class ForEachDemo
{
public static void main(String[] args)
{
int[] highScores = { 10, 9, 8, 8};
String[] names = {"Jamal", "Emily", "Destiny", "Mateo"};
// for each loop with an int array
for (int value : highScores)
{
System.out.println( value );
}
// for each loop with a String array
for (String value : names)
{
System.out.println(value); // this time it's a name!
}
}
}
// Hack 7
for ( int k = 0; k < a.length; k++ )
{
while ( a[ k ] < temp )
{
a[ k ] *= 2;
}
}
// Computing Sums
int[] array = {5, 1, 78}; // intialize
int sum = 0; // variable to keep track of sum
for (int number: array) { // iterates over each loop in the array
sum += number; // the number is added to the sum
}
System.out.println(sum); //expected sum is 84, so 84 should be printed
// from college board
private double findMax(double[] values) {
double max = values[0]; // initialize max with first element of array
for(int i=1; i<values.length; i++) { // starting with the second element, iterate over the rest of the array
if (values[i] > max) { // if the current element is greater than the max
max = values[i]; // set the max equal to the greatest value until that point
}
}
return max;
}
private int findEvenNumbers(int[] values) {
int evenCount = 0; // initalize count of even numbers to zero
for(int value: values) { // iterate over every element of array
if(value % 2 == 0) { // use modulus operator to check if value is even
evenCount += 1; // increment evenCount if the value is even
}
}
return evenCount;
}
Given the following code segment, which of the following will cause an infinite loop? Assume that temp is an int variable initialized to be greater than zero and that a is an array of integers.
- A. The values don't matter this will always cause an infinite loop.
- B. Whenever a includes a value that is less than or equal to zero.
- C. Whenever a has values larger then temp.
- D. When all values in a are larger than temp.
- E. Whenever a includes a value equal to temp.
// FRQ
public void addMembers(String[] names, int gradYear) {
for (String name : names) {
memberList.add(new MemberInfo(name, gradYear, true));
}
}