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

advertisement
Topic:
Arrays – day1: Introduction
Objectives
Why are arrays important?
Name: _____________________________________________________
Period: _______ Date: _______________________



I will be able to describe why arrays are important in CS.
I will be able to describe how arrays are declared and initialized
I will be able to describe how to compare elements within an array.
Data variables that we have used so far can only hold 1 value. Arrays allow us to hold
multiple values of the same data type.
What is an array?
Data Structures that holds multiple values of the same type in continuous memory.
How do you declare an array
of integers?
int [ ] myArray;
How do you declare and
create an array of 6 integers?
How do I set the elements to:
2, 3, 6, 1, 8, 5
Another way of declaring,
creating, and initializing an
array
int [ ] myArray = new int [ 6 ];
myArray[0] = 2;
myArray[1] = 3;
myArray[2] = 6;
myArray[3] = 1;
myArray[4] = 8;
myArray[5] = 5;
int [ ] myArray = { 2, 3, 6, 1, 8, 5 };
How do you test if the first
and the last elements are the
same?
if (myArray[0] == myArray[5])
System.out.println(“they have the same values”);
How do you specify the
number of elements an array
can hold?
myArray.length
How do you test if the first
and the last elements are the
same?
if (myArray[0] == myArray[myArray.length - 1])
System.out.println(“they have the same values”);
codingBat: Arrays-1
firstLast6
Given an array of integers, return true if 6 appears as either the first or last element in the
array. The array will have a length of 1 or more.
firstLast6({1, 2, 6}) → true
firstLast6({6, 1, 2, 3}) → true
firstLast6({13, 6, 1, 2, 3}) → false
public boolean firstLast6( int[ ] nums )
{
If (nums[0] == 6)
return true;
If (nums[nums.length-1] == 6)
return true;
return false;
}
Given an array of integers, return the sum of all of the elements. The array will have a length
of 1 or more.
sum({1, 2, 6}) → 9
sum({6, 1, 2, 3}) → 12
sum({13, 6, 1, 2, 3}) → 25
public int sum( int[ ] nums )
{
int sum = 0;
for (int k=0; k < nums.length; k++)
sum = sum + nums[k];
return sum;
}
codingBat: makePi
Return an integer array, length 3, containing the first 3 digits of pi, {3, 1, 4}.
makePi() → {3, 1, 4}
public int[ ] makePi()
{
int [ ] pie = new int [3];
pie[0] = 3;
pie[1] = 1;
pie[2] = 4;
return pie;
}
codingBat: commonEnd
Given 2 arrays of integers, a and b, return true if they have the same first element or they
have the same last element. Both arrays will have a length of 1 or more.
commonEnd({1, 2, 3}, {7, 3}) → true
commonEnd({1, 2, 3}, {7, 3, 2}) → false
commonEnd({1, 2, 3}, {1, 3}) → true
public boolean commonEnd(int[ ] a, int[ ] b)
{
If ( a[0] == b[0] )
return true;
if (a[a.length-1] == b[b.length-1])
return true;
return false;
}
Summary:
Download