



|
|
CS1 Course Site
|
Wait , WAIT !!What's that word ? ( Class Notes ( without definitions ) )
Wednesday November 1 , 2000
|
|
More Array Stuff
Associated with each array is a public variable called
length
which stores the number of memory cells in the array.
Tasks
Assume
a is an array of integers.
s is an array of strings.
Both have been instantiated.
- Display all of the valiues 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]);
}
- Add 10 to each element of array a []
for (int x = 1; x < a.length; x + +)
{
a [x] = a [x] + 10;
}
- Assign the largest value in array a [] to the variable max which must be declared. Assuming a [] has atleast one element.
int max = a [0];
for (int x + 1; x < a.length; x + +)
}
if (a [x] > max0)
{
max = a [x];
}
}
- Make n of array a [] called the copy...c
int ----------
c = a; this just makes an alias
The solution
int c [] = new int [a.length];
for (int x = 0; x < a.length; x + +)
{
c [x] = a [x];
}
- Swap the first two values in array a.
What do you think of this?
a [0] = a [1];
a [1] = a [0];
WRONG!!
The standard solution
int temp = a [0];
a [0] = a [1];
a [1] = temp;
Problem
Read several (atleast one) positive integers and display all of the integers which are greater than their average value.
Ex
a solution which features the Global Procedural application architecture.
- The main method
static public void main (---)
{
readAndStoreTheNrs ();
computeTheAverage ();
displayTheNrsAboveAverage ();
- / /The ``variables''
static private int a [];
static private final int LIMIT = 1000;
static private double average;
static private int nrElements;
static private int number;
- Refine the method
static private void readAndStoreNrs ()
{
n = new int [LIMIT];
nrElements = 0;
number = IO.read_int ();
while (number > 0)
{
a [nrElements] = number;
nrElements + 1;
number = IO.read_int ();
}
}
|
|