INFORMATION & COMPUTER SCIENCE DEPARTMENT, KFUPM

ICS102, SECTIONS 52, 54 & 55  (001 Semester)

INTRODUCTION TO COMPUTING

LAB  #06 Loop Structures

 

Instructor: Bashir M. Ghandi

 


Objectives:

To gain experience with:

 

1.  Nested while loop:

We recall that while loop has the following format:

while (test)

  statement

 

or

 

while (test) {

  statements

}

 

Now, since while loop is also a java statement, we can replace the statement or any of the statements in the above structures with another while loop.  If we do that, then we have what is called Nested while Loop. 

 

Example 1:  In the following example, we use nested while loop to print the indices of a 3X3 matrix:

/* prints the indices of a 3X3 matrix */

public class NestedWhileLoop {

 

      public static void main(String[] args) {

            int i=1,j;

            while(i<=3) {

                 

               j=1;

               while(j<=3) {

                    System.out.print(i+","+j+"\t");

                    j++;

               }

               System.out.println();

               i++;      

            }

      }

}

Notice that a while loop has the following three properties:

·         The condition part usually involve at least one variable called the control variable or index

·         The control variable must be initialized before the loop

·         The control variable must be updated inside the loop

 

2.  for Loop.

The for statement in java combines all the three properties of a while statement into one line.  The syntax is:

      for (initialization; condition; update)

            statement;

 

 Again if there is more than statement, we must put them into a block using { .. }:

      for (initialization; condition; update) {

            statements;

        }

 

 

While it is possible to convert any while loop into a for loop, it is better restrict its use to counting loops – Those loop which the number of iterations can be determined by the programmer,  and use while and do .. while loops for those cases in which the number of iterations can only be determined at run-time.

 

Example 2: The following program reads the size of a section and then reads the grades of students in the section and compute and prints the average of the section.

/*  reads the size of a section and then reads the grades of students in the section and compute and prints the average of the section.

*/

import TextIO;

 

public class AverageScore {

     

      static TextIO stdin = new TextIO(System.in);

     

      public static void main(String[] args) throws java.io.IOException {

           

            double score, average, sum=0;

            int sectionSize;

           

            System.out.print("Enter section size: ");

            sectionSize=stdin.readInt();

            System.out.println();

           

            for (int i=1; i<=sectionSize; i++) {

                 

                  System.out.print("Enter Score #"+i+": ");

                  score=stdin.readDouble();

                sum+=score;

            }

            average=sum/sectionSize;

            System.out.println("The average is: "+average);

      }

}

 

 

Example 3:  The following example reads initial and final temperature in Celsius and the incremental value, it then prints a table of both Celsius and equivalent Fahrenheit temperatures.

/* reads initial and final temperature in Celsius and the incremental value

   prints a table of both Celsius and equivalent Fahrenheit temperatures

*/

import TextIO;

 

public class TemperatureTable {

 

      static TextIO stdin = new TextIO(System.in);

 

      public static void main(String[] args) throws java.io.IOException  {

 

            double start, stop, increment;

 

            System.out.print("Enter starting temperature in Celsius: ");

            start=stdin.readDouble();

            System.out.print("Enter stopping temperature in Celsius: ");

            stop=stdin.readDouble();

            System.out.print("Enter increment value: ");

            increment=stdin.readDouble();

            System.out.println();

           

            if (stop > start) {

                System.out.println("CELSIUS"+"\t"+"FAHRENHEIT");

           

                for (double celsius=start; celsius<=stop; celsius+=increment)

                    System.out.println(celsius+"\t"+ ((9.0/5.0)*celsius+32));

            }

            else

               System.out.println("Starting value must be smaller than stopping value"); 

      }

}

 

We can use the DecimalFormat class contained in the java.text package to specify exactly how many decimal digits we want after the decimal point.


Example 4:  The following program modifies the Temperature table program above by formatting the temperature values to print using three decimal places using a DecimalFormat object.

/* reads initial and final temperature in Celsius and the incremental value

   prints a table of both Celsius and equivalent Fahrenheit temperatures */

import TextIO;

import java.text.DecimalFormat;

 

public class TemperatureTable2 {

      static TextIO stdin = new TextIO(System.in);

      public static void main(String[] args) throws java.io.IOException  {

            DecimalFormat df3 = new DecimalFormat("0.000");

            double start, stop, increment;

            double fahrenheit;

           

            System.out.print("Enter starting temperature in Celsius: ");

            start=stdin.readDouble();

            System.out.print("Enter stopping temperature in Celsius: ");

            stop=stdin.readDouble();

            System.out.print("Enter increment value: ");

            increment=stdin.readDouble();

            System.out.println();

           

            if (stop > start) {

                System.out.println("CELSIUS"+"\t\t"+"FAHRENHEIT");

           

                for (double celsius=start; celsius<=stop; celsius+=increment) {

                  fahrenheit = 9.0/5.0*celsius+32;

                  System.out.println(df3.format(celsius)+"\t\t"+

                                          df3.format(fahrenheit));

                }

            }

            else

               System.out.println("Starting value must be smaller than stopping value"); 

      }

}

 

Example 5: The following example is an applet that uses a nested for-loop to draw a chess board using read and black color.  It make use of the translate(x,y) method which is used to move a graphic object along x and y direction.

import java.applet.Applet;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.Rectangle;

import java.awt.Color;

 

public class ChessBoard extends Applet {

      public void paint(Graphics g) {

            Graphics2D g2 = (Graphics2D)g;

            int i,j;

            int xPos =10, yPos=10,size=20;

            Rectangle square = new Rectangle(xPos,yPos,size,size);

           

            for (i=1; i<=8; i++) {

                  for (j=1; j<=8; j++) {

                        if ((i+j)%2==0)

                              g2.setColor(Color.red);

                        else

                            g2.setColor(Color.black);

 

                        g2.fill(square);

                        square.translate(size,0);

                  }

                  square.translate(-size*8,size);

            }

      }

}

3.  do … while loop:

This is another version of the while loop in which the body of the loop is executed before testing the condition.  The syntax is:

do {

      statements

            }  while ( condition ) ;

 

do … while loop is usually convinient when when we need to execute at least once before checking the condition.  Example is when the value of control variable is entered as input by the user.

 

Examples 6: The following example reads integer numbers from the user and prints the times table [1 ..12]  for that number.  

                    It  repeats as long as the user type y or Y to run again.

/*  reads integer numbers from the user and prints the times table [1 ..12]

    for that number, repeats as long as the user type y or Y to run again

*/

import TextIO;

 

public class TimesTable {

     

      static TextIO stdin = new TextIO(System.in);

     

      public static void main(String[] args) throws java.io.IOException {

            int number;  //a number to be enterted by the user

            char response;

           

            do {

                  System.out.print("\nTimes Table for which number: ");

                  number = stdin.readInt();

           

                  System.out.println("\nTimes Table for "+number);

                  for (int i=1; i <= 12;  i++)

                      System.out.println(i+"x"+number+" = "+i*number);

                     

                  System.out.print("\nDo you wish to display another table [Y/N]?");

                  response = stdin.readChar();

            } while (response == 'Y' || response == 'y');

      }

}

 

4.  Assignments

1.        (a)   Write a program that prints a table for the trigonometric functions sine, cosine and tangent for angles between 00 to 1200 in steps of 150.  Your program should print “INFINITY” for tangent of 900.

(b)   use DecimalFormat object to format your table to print 6 digits after decimal point.

2.        Write a program to print the following pattern:

3.        Modify Example 4 so that the program does not just stop when the initial temperature is starting temperature, instead, the program loops back and ask the user to enter the starting and stopping temperatures again until valid values are entered.

 

4.        The rate of drilling a well is 20 meters per hour for the first hour. For each subsequent hour the depth drilled is 8 % less than in the previous hour. Write a program to tabulate the depth drilled and the depth reached at the end of each hour as long as the depth drilled in a particular hour is greater than 9 meters. The output of your program should be:

 

5.  Home Work

1.        Write a program that finds an approximation for p using the first one million terms (1000000) of the following infinite series:

p  =  4   -   4 / 3   +   4 / 5   -   4 / 7   +   4 / 9    -  .  .  .

 

As your program loops to one million, it should print each power of 10 encountered and the corresponding approximate value of  p as shown below.  Name your program as PiApproximation.

 

2.        Write an applet that displays an alternating pattern of 10 by 10, black and white circles each of diameter 20.  The circles should be drawn on a blue background as shown below.  Name your program as CirclePatterns.  Hint: ellipse objects do not have translate method, but you can move a circle object into a new location using the method:  setFrame(x,y,width, height).      e.g:  myEllipse.setFrame(5, 5, 20, 20).   

 

3.        SAUDIA has code numbers and maximum free baggage for its three classes of customers according to the following table:

CLASS

CLASS CODE

FREE BAGGAGE  (KILOGRAMS)

FIRST

1

40

HORIZON

2

30

ECONOMY

3

20

 

Assuming that excess baggage is charged at 1% of the first class single fare per kilogram, write a program that repeatedly reads, code number, baggage and the first class single fare and computes the cost of excess baggage until the user enters,  0   0   0,  to stop the program.  Name your program as ExcessBaggage.

 

6.  Important Notes on Submitting Home Works:

1.                    Name your files as instructed

2.                    Type your ID# and name as a comment on the first line in your source file

3.                    Submit both hard and soft copy of your home work.

4.                    Submit both the source file (.java) and the compiled file (.class) file.  In case of question two, submit the html file as well.

5.                    If your program needs TextIO.class, you must include it in the appropriate folder in your diskette.

6.                    All your files should be saved in a folder HW2 on your diskette, except if your diskette does not contain any other files.

7.                    Hand-written programs are not acceptable

8.                    Name you classes and variables according to our conventions:

·         Class name should begin with a capital letter

·         method, variable and object names should begin with small letters

·         if your names involve more than one word, each word should begin with capital letter (except the first in the case of variables, methods and objects as stated above)

·         single letter variables and abbreviations are not acceptable except for control variables in a loop where you may use i and j.  You must use complete names (e.g.  MyFirstClass, myFirstVariable).