CS1 Course Site

CS1 at Oswego

Hypertexknowlogy

Frequently Asked Questions

 
CS1 Course Site  
 
 
 
Class Notes

Monday October 30 , 2000
 
The for statement  

SPECIFICATION  

Form  

  for (< init >;  < test >;  < incr >)
  {
      < statement-sequence >
 
}
 

init -- initialization  

incr -- incrementation  

Meaning  

  < init >;
  while (< test >)   {
      < statement-sequence >
      < incr >;
 

 

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...
    int sum = 0;
    int c = 1;
    while (c < = 5)
    {
        sum = sum + c;
        c = c + 1;
 
  }
 

Example  

What does this do?  

  int i = 25;  i > 0;  i = i - 1)
  {
      for (int x = 1;  x < = i;  x = x + 1)
      {
        IO.print (``*'');
     
}         IO.println ();
 
}
 

This forms a triangle out of *.  

Translation to the ``while'' equivalent.  

  / /Taking away the ``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.
  int i = 25;
  while (i > 0)
  {
      int x = 1;
      while (x < = i)
      {
        IO.print (``*'');
        x = x + 1;
     
}         IO.println ();
        i = i - 1;
 
}  

Definition   An ARRAY is an object which contains some number of objects of the ``same'' type,  each of which may be referenced.

Array declaration and instantiation for an array of int values of length 4..  

  int a [];
  a = new int [4];
  a [0] = 2;
  a [1] = 3;
  a [2] = 5;
  a [3] = 7;
 

Establish and instantiate an array of String values of length 3..  

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

Establish and instantiate an array of Circle values of length 5..  

  Circle c [] = new Circle [5];
  c [0] = new Circle (2.0);
  c [1] = new Circle (1.0);
 

TASK  

Suppose a is an integer array,  b is a String array.   Moreover,  both have been completely instantiated.  

(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.  

DO NOT DO THIS!!!!!  

  IO.println (a [0]);
  IO.println (a [1]);
  IO.println (a [2]);
  IO.println (a [3]);
  IO.println (a [4]);
 

THIS IS WHAT YOU WANT TO DO....  

  for (int x = 0;  x < = 4;  x = x + 1)
  {
      IO.println (a [x]);
 
}