Topic: Name: _____________________________________________________ Period: _______ Date: _______________________ Arrays – day2: Introduction

advertisement
Topic:
Arrays – day2: Introduction
Name: _____________________________________________________
Period: _______ Date: _______________________

Objectives

I will be able to describe how to count elements within an array given a comparison
criteria.
I will be able to describe how to traverse an array and compare elements
Declare an array of 10 integers
and set the first and last
elements.
int [ ] data = new int [10];
How do you populate an array
with random values with a
range of 0 to 99 inclusive.
int [ ] data = new int [10];
for (int k=0; k < data.length; k++ )
data [k] = (int)(Math.random()* 100);
Write a method which will
create an array of a specified
length with random values
given a specified range.
public int [ ] createArray (int length, int range)
{
int [ ] data = new int [length];
for (int k=0; k < data.length; k++ )
data [k] = (int)(Math.random()* range);
data[0] = 15;
data[data.length-1] = 22;
return data;
}
Write a method which will
return the minimum value
given an array of integers
public boolean has23(int[] nums) {
for (int k=0; k<nums.length; k++)
if (nums[k] == 2 || nums[k] == 3)
return true;
return false;
}
From www.codingbat.com
fix23
Given an integer array length 3, if there is a 2 in the array
immediately followed by a 3, set the 3 element to 0. Return the
changed array.
fix23({1, 2, 3}) → {1, 2, 0}
fix23({2, 3, 5}) → {2, 0, 5}
fix23({1, 2, 1}) → {1, 2, 1}
public int[] fix23(int[] nums) {
for (int k=1; k<nums.length; k++)
if (nums[k-1] == 2 && nums[k] == 3)
nums[k]=0;
return nums;
}
TestArrays








Summary:
Find maximum value
Calculate Average
Get the number of odd elements
Get the number of elements greater than 50
Get the number of odd elements greater than 50
Create an array of a specified length with sequential values starting at a
specified value
Merge 2 arrays (with the same length)
Merge 2 arrays (with different lengths)
Download