Return to Jeff's Main Page

CS1 at Oswego

Hypertexknowlogy

Frequently Asked Questions

 
My Intro to Object-Oriented Programming  
 
 
 
Class Notes

Wednesday November 1 , 2000
 
More array stuff tonight.
Associated with each array is a public variable called length which stores the number of memory cells in the array. 

Some more array tasks:

Assume ' a' is an array of real numbers and is 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]);
}
2)    add 10 to each element of array a.
for (int    x    =    0;    x    <    a.length;    x + +)
{
a [x]    =    a [x]    +    10;
}
3)    assign the largest value in array a to the variable ' max'    -    which must be declared.    Assume a has at least one element.
int max    =    a [0];
for (int    x    =    1;    x    <    a.length;    x + +)
{
if (a [x]    >    max)
{
max    =    a [x];
}
}
 

4)    make a copy of array a.   call the copy c.

int c []    =    new int [a.length];
for (int    x    =    0;    x    <    a.length;    x + +)
{
c [x]    =    a [x];
}
5)    swap the first two values in array a.
int temp    =    a [0];
a [0]    =    a [1];
a [1]    =    temp;
 

CG then demonstrated the use of an integer array with the following problem:

Read several (at least one) positive integers and display all of the integers which are greater than their average value. 

For example,  the input:    10    4    15    7    - 1
Yields the output:    10    15 

Our solution will feature the global procedural architecture. 

/ /    The main method.
static public void main (~ ~ ~ ~)
{

readAndStoreTheNumbers ();
computeTheAverage ();
displayTheNumbersAboveAverage ();
 

/ /    Data Dictionary
static private int a [];
static private final int LIMIT = 1000;
static private double average;
static private int nrElements;
static private int number; 

/ /    Refine the methods.
static private void readAndStoreTheNumbers ()
{

a    =    new int [LIMIT];
nrElements    =    0;
number    =    IO.read_int ();
while (number    >    0)
{
a [nrElements]    =    number;
nrElements    =    nrElements    +    1;
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]);
}
}