Chapter 8 - Fill In the Code Flashcards
1
Q
- This code assigns the value 10 to all the elements of an array a.
int [ ] a = new int[25]; for ( int i = 0; i < a.length; i++ ) { // your code goes here }
A
a[i]=10;
2
Q
- This code prints all the elements of array a that have a value greater than 20.
double [ ] a = { 45.2, 13.1, 12.8, 87.4, 99.0, 100.1, 43.8, 2.4 };
for ( int i = 0; i < a.length; i++ ) { // your code goes here }
A
if(a[i]>20)
3
Q
- This code prints the average of the elements of array a.
int [ ] a = { 45, 13, 12, 87, 99, 100, 43, 2 };
double average = 0.0; for ( int i = 0; i < a.length; i++ ) { // your code goes here } // ... and your code continues here
A
{
average+=a[i];
}
System.out.println(average/a.length);
4
Q
- This code calculates and prints the dot product of two arrays (Σ a[i] * b[i]).
int [ ] a = { 3, 7, 9 };
int [ ] b = { 2, 9, 4 };
int dotProduct = 0;
for ( int i = 0; i < a.length; i++ ) { // your code goes here }
A
{
dotProduct+=a[i]*b[i];
}
System.out.println(dotProduct);
5
Q
- This code prints the following three lines:
a[0] = 3 a[1] = 6 a[2] = 10
int [ ] a = { 3, 6, 10 }; for ( int i = 0; i < a.length; i++ ) { // your code goes here }
A
System.out.println(“a[“+i+”] = “+a[i]);
6
Q
- This method returns true if an element in an array of Strings passed as a parameter contains the substring IBM; otherwise, it returns false.
public boolean foo( String [ ] a ) { // your code goes here }
A
for ( int i = 0; i < a.length; i++ ) { if ( a[i].indexOf( "IBM" ) != -1 ) return true; } return false;
7
Q
- This method returns the number of elements in an array passed as a parameter that are multiples of 7.
public int foo( int [ ] a ) { // your code goes here }
A
int count = 0; for ( int i = 0; i < a.length; i++ ) { if ( a[i] % 7 == 0 ) count++; } return count;
8
Q
- This method returns true if the first two elements of the array passed as a parameter have the same value; otherwise, it returns false.
public boolean foo( String [ ] a ) { // your code goes here }
A
if ( a.length < 2 ) return false; else if ( a[0].equals( a[1] ) ) return true; else return false;
9
Q
- This method takes an array of ints as a parameter and returns an array of booleans. For each element in the parameter array whose value is 0, the corresponding element of the array returned will be assigned false; otherwise, the element will be assigned true.
public boolean [ ] foo(int [ ] a) { // your code goes here }
A
boolean [] temp = new boolean[a.length]; for ( int i = 0; i < a.length; i++ ) { if ( a[i] != 0 ) temp[i] = true; } return temp;