Level 4 - Arrays Flashcards
Declare an array of integers called ‘values’ with room to store 10 integers
int[] values = new int[10];
What value displays?
int[] nums = {10, 3, 4, 5, 6, 7, 5};
System.out.println( nums[2]);
4
What is output?
int[] list = new int[3];
list[1] = 2;
System.out.println(list.length);
3
//list[0] and list[2] both have a value of 0
What value displays?
int[] nums = {5, 1, 34, 12, 11, 71, 5};
System.out.println( nums[7]);
Array out of bounds runtime exception - the last element is nums[6]
Describe what the following code segment does:
for(int i=0; i < nums.length; i++)
nums[i] = Math.abs(nums[i]);
makes everything in the array nums positive
Write a loop that locates the first occurrence of a negative integer in an array called ‘list’. When the loop is finished, the variable should contain the index of the negative number. The variable should be -1 if there was no negatives
int pos = -1;
for(int i =0; i < list.length; i++)
{
if(list[i] < 0)
pos = i;
}
return pos;
Write a loop that displays the length of all the Strings in a string array called ‘someText’
for (int i =0; i < someText.length(); i++)
System.out.println( someText[i].length() );
What value displays?
String[] pets = {“dog”, “cat”, “fish”, “pig”, “hamster”}; System.out.println( pets[1]);
cat
What value displays?
String[] pets = {“dog”, “cat”, “fish”, “pig”, “hamster”}; System.out.println( pets[2].length());
4
//the pet at position 2 was ‘fish’ and it had 4 characters
What value displays?
String[] pets = {“dog”, “cat”, “fish”, “pig”, “hamster”};
System.out.println( pets.length);
5
// .length asks how many spots in the array
What value displays?
String[] pets = {“dog”, “cat”, “fish”, “pig”, “hamster”};
System.out.println( pets[3]+pets[0]);
pigdog
Use a for loop to fill an array called ‘randoms’ with a random number from 1-100. (assume the array has been created)
for (int i=0; i < randoms.length; i++)
{
randoms[i] = (int)(Math.random()*100)+1;
}
What is the issue with this array?
int [] numbers = new int [4];
numbers[1] = 3;
numbers[2] = 56;
numbers[3] = 34;
numbers[4] = 2;
“numbers[4]” is out of bounds of the array.
Write a line of code that displays the length of the array: dogfight
System.out.print(dogfight.length);
How does this change each element of the array?
for (int i = 0; i < b.length; i++)
{
b[i] += 3;
}
The loop adds 3 to each element of the array “b.”