Return to Jeff's Main Page

CS1 at Oswego

Hypertexknowlogy

Frequently Asked Questions

 
My Intro to Object-Oriented Programming  
 
 
 
Class Notes

Monday October 30 , 2000
 
Tonight we were introduced to a very cool mechanism of iteration:    the ' for' statement.   Here's what it's about: 


The for statement: 

specification:
form:

for (< init >;    < test >;    < incr >)
{
< statement sequence >
}
meaning:
< init >
while (< test >)
{
< statement sequence >
< incr >;
}
Here's an example:
/ /    Code to sum the integers from 1 to 5..
int sum =    0;
for (int    c =    1;    c    < =    5;    c    =    c +    1)
{
sum =    sum +    c;

The equivalent ' while' statement of this example looks like this: 

int sum =    0;
int    c    =    1;
while (c    < =    5)
{

sum    =    sum    +    c;
c    =    c +    1;

 

CG then showed us an example of how to convert a ' for' statement within a ' for' statement into the equivalent ' while' statements.    See the class notes for details. 

The remainder of tonight's lecture concentrated on arrays

Basically,  an array is an object which contains a number of objects of the same type,  and each one can be referenced. 


Here is an example of an array declaration and instantiation for the array of the following string values:
``red''
``blue''
``white'' 

The code: 

String primary []    =    new String [3];
primary [0]    =    ``red'';
primary [1]    =    ``blue'';
primary [2]    =    ``white''; 

As you can see,  primary [0] is bound to ``red'' and so on.   It is important to note that in the instantiation,  String [3] denotes the length of the string array.   The first ``whatever'' in an array is always denoted [0].    Here is some more array code: 

Suppose ' a' is an integer array,  then:
1)    read a new value into the first element of array a.

a [0]    =    IO.read_int ();
2)    add 10 to the first element of array a.
a [0]    =    a [0]    +    10;
3)    display the values of array a,  one per line and using only one IO statment.
for (int    x    =    0;    x    < =    4;    x    =    x    +    1)
{
IO.println (a [x]);
}