CS1 Course Site

CS1 at Oswego

Hypertexknowlogy

Frequently Asked Questions

 
CS1 Course Site  
 
 
 
Wait , WAIT !!What's that word ? ( Class Notes ( without definitions ) )

Monday October 30 , 2000
 
The for statement
Specifications
Form
for (< intit >;  < test >;  < incriment >)
{
    < statement-sequence >
}
meaning
< init >;
while (< test >)
{
    < statement-sequence >;
    < incr >;
}
Ex
/ /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
int sum = 0;
int c = 1;
while (c < = 5)
{
    sum = sum + c;
    c = c + 1;
}
Ex
What does this do?
for (int i = 25;  i > 0;  i = i - 1)
{
    for (int x = 1;  x < i;  x = x + +)
    {
        IO.print ( ``*'' );
    }
    IO.println ();
}
Translate (to the ``while'' equivalent)
Take away outer for
int i = 25;
while (i > 0)
{
    for (int x = 1;  x < = i;  x = x + 1)
    {
        IO.print ( ``*'' );
    }
    IO.println ();
    i = i - 1;
}
Take away the inner for statement
int i = 25;
while (i > 0)
{
    int x = 1;
    while (x < = i)
    {
        IO.print ( ``*'' );
        x = x + 1;
    }
    IO.println ();
    i = i - 1;
}
Array declaration and instantiation
int a [];
a = new int [4];
a [0] = 2;
a [1] = 3;
a [2] = 5;
a [3] = 7;
String primary [] = new String [3];
primary [0] = Red;
primary [1] = Blue;
primary [3] = Yellow;
Cicle c [] = new Circle [5];  c [0] = new Circle (2);
c [1] = new Circle (1);
.
.
.
Tasks
Suppose a is an integer array,  b is a String array.   Moreover,  both have been completely instantiated....
Thusly
int a [] = new int [5];
a [0] = 10;
a [1] = 15;
a [2] = 20;
a [3] = 25;
a [4] = 30;
  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...using only one IO.   statement
    for (int x = 0;  x < = 4;  x + 1)
    {
        IO.println (a [x]);
    }