Synopsis
This class discusses array operations and using if /else for decision making in the programs.
|
Discussion about what to include in the class notes, powerful ideas and learning journal sections of this site. It will not be reproduced here since it does not pertain directly to the learning of programming with Java I feel, however it is important for a more ``complete'' cs1 site.
Array Stuff
Associated w /each array is a
public variable
called
length
which the stores the number of memory cells in the array.
array a [] [] [] - a.length is 3
Tasks
Assume
-- > a is an array of int number
-- > s is an array of strings.
-- > both have been instantiated.
1) Display all of the values in array a - one per line.
for (int x = 0; x < a.length; x + +)
{
IO.println (a [x]);
}
|
or
for (int x = 1; x < = a.length; x + +)
{
IO.println (a [x-1];
}
|
Task 2
Add 10 to each element of array a.
for (int x = 0; x < a.length; x + +)
{
a [x] = a [x] + 10;
}
|
Task 3
Assign the largest value in array a to the variable
max
- which must be declared. Assume a has at least 1 element.
for (int x = 1; x < a.length; x + +)
{
if (a [x] > max)
{
max = a [x];
}
}
|
Task 4
Make a copy of array a called the copy...c.
c = a; / /this isn't a copy. this is an alias to array a
The solution
int c [];
c = new int [a.length];
for (int x = 0; x < = a.length; x + +)
{
c [x] = a [x];
}
|
Task 5
Swap the first two values in array a.
The Standard way
int temp = a [0];
a [0] = a [1];
a [1] = temp;
|
Problem
Read several (at least one) positive integers and display all of the integers which are greater than their average value.
Ex.
Input:10 4 15 7 - 1 (avg. 9)
Output:10 15
A solution which features the Global Procedural app architecture.
- The main method
static public void main (String args [])
{
readAndStoreTheNumbers ();
computeTheAverage ();
displayTheNumbersAboveAverage ();
}
|
- data dictionary - constants are all caps
static private int a []; / /array var
static private final int LIMIT = 1000; / /max # of values
static private double average;
static private int nrElements;
static private int number;
|
- the methods - refine the methods
static private void readAndStoreTheNumbers ()
{
a = new int [LIMIT];
number = IO.read_int ();
nrElements = 0;
while (number > 0)
{
a [nrElements] = number;
nrElements + +;
number = IO.read_int ();
}
}
static private void computeTheAverage ()
{
int sum = 0;
for (int x = 0; x < nrElements; x + +)
{
sum = sum + a [x];
}
average = (double) sum / (double) nrElements;
}
static private void displayTheNumbersAboveAverage ()
{
for (int x = 0; x < nrElements; x = x + 1
{
if (a [x] > average)
{
IO.println (a [x]);
}
}
/ /end}
|