INFORMATION & COMPUTER SCIENCE DEPARTMENT, KFUPM

ICS102, SECTION 65  (002 Semester)

INTRODUCTION TO COMPUTING

LAB  #08 Loop Structures

 

Instructor: Bashir M. Ghandi

 


Objectives:

 

1.  Loop Structures:

for loop:  this has the following format:

for (control = start;  condition;  update)

      statement;                                                       or

for (control = start;  condition;  update) {

      statements;

}

 

It is preferable to use the for loop when the number of repetition is known or can be easily counted.  Thus, the for loop is sometimes called counting loop.  The example method below uses for loop to compute the sum of even numbers from 1 to 100;

   public int sumOfEven() {

      int sum = 0;

      for (int i=0; i<100; i+=2)

          sum+=i;

      return sum;

   }

 

while loop:  this usually has the following format:

intialize control variable;

while (condition) {

      statements;

      update;

}                                                              or

intialize control variable;

while (condition) {

      update;

      statements;

}             

 

It is preferable to use while loop when the number of repetition is not know and it is possible that it could be zero. The example method below counts the number of digits in a positive integer number n.

   public int numberOfDigits(int n) {

      int count = 1;

      while (n > 9) {

         count++;

         n = n/10;

      }

      return count;

   }

 

 

do-while loop: This usually has the following format:

do {

      statements;

      update;

} (condition);                                                        or

do {

      update;

     statements;

} (condition);       

 

Because the condition of the do-while loop is checked at the end of the loop, its statements must execute at least once.  Thus, it is preferable to use do-while loop when the number of repetition is not known but it is at least one.

 

The following example uses do-while loop to ensure that a number entered by a user in the range 1…5.

   static int getChoice() {

      int choice;

      do {

         System.out.println("Enter your choice: ");

         choice = Integer.parseInt(stdin.readLine());

      } while (choice < 0 || choice > 5);

      return choice;

   }

2.  Example programs.

In practice, we may need to use more than one type of loop in a program as the following examples shows.  It is also worth noting that these loops structures can be nested within each other to solve more complex problems.

 

Example 1: The following program reads an integer number from the user and prints the times table for that integer.

import java.io.*;

 

class TimesTable {

     

      public static void printTable(int n) {

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

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

      }

     

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

            BufferedReader stdin = new BufferedReader(new InputStreamReader( System.in ));

           

            int number;

            String input;

           

            do {

                  System.out.print("\nEnter a number to display table or Q to stop: ");

                  input = stdin.readLine();

                 

                  if (!input.equalsIgnoreCase("q")) {

                        number = Integer.parseInt(input);

                 

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

                        TimesTable.printTable(number);

                  }

            } while (!input.equalsIgnoreCase("q"));

      }

}

 

 

Example 2: The following example is an applet that uses nested for loop to print a chess board

import java.awt.*;

 

public class ChessBoard extends Applet {

     

      public void paint(Graphics g) {

           

            Graphics2D g2 = (Graphics2D)g;

            final int SIZE = 40;

            int i,j;

            int x =10, y=10;

            Rectangle square = new Rectangle(x,y,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);

                      x+=SIZE;

                      square.setFrame(x,y, SIZE, SIZE);  

                  }

                  x=10;

                  y+=SIZE;

                  square.setFrame(x,y,SIZE,SIZE);    

            }

      }

}          

Examples 3: The following is an example of a sentinel control loop.

import java.io.*;

 

class Student {

      private String name;

      private double totalScore = 0;

      private int countOfExams;

     

      public double average() {

            if (totalScore > 0)

                  return totalScore/countOfExams;

            else

                return 0;

      }

      public void addExam(double exam) {

            countOfExams++;

            totalScore+=exam;

      }

}

     

public class TestStudent {

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

            BufferedReader stdin = new BufferedReader(new InputStreamReader( System.in ));

           

            double score;

            String input;

            Student s = new Student();

            do {

                  System.out.print("\nEnter next score or Q to stop: ");

                  input = stdin.readLine();

                 

                  if (!input.equalsIgnoreCase("q")) {

                        score = Double.parseDouble(input);

                        s.addExam(score);

                  }

            } while (!input.equalsIgnoreCase("q"));

            System.out.println("Average for this student is: "+s.average());

      }

}

 

Examples 4: The following is an example of a menu-driven application.

import java.io.*;

 

class Calculator {

      private double first;

      private double second;

     

      public Calculator(double first, double second) {

            this.first = first;

            this.second = second;

      }

      public double add() {

            return first+second;

      }

      public double subtract() {

            return first - second;

      }

      public double multiply() {

            return first*second;

      }

     

      public double divide() {

            return first/second;

      }

}

 

 

public class TestCalculator {

    static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));

 

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

      int choice;

      double operand1, operand2;

     

      do {

         showMenu();

         choice = getChoice();

           

               if (choice == 5)

                  return;

                 

               operand1 = getNumber("Enter first number: ");

               operand2 = getNumber("Enter second number: ");

               Calculator c = new Calculator(operand1, operand2);

           

               switch (choice) {

                     case 1 :  System.out.println("Sum : "+ c.add());

                                   break;

                     case 2 :  System.out.println("Difference : "+ c.subtract());

                                   break;

                     case 3 :  System.out.println("Product : "+ c.multiply());

                                   break;

                     case 4 :  if (operand2 == 0)

                                   System.out.println("Input error! Division by 0");

                               else

                                   System.out.println("Divisor : "+ c.divide());

                                   break;

               }

           

      } while (choice != 4);

    }

   

    static void showMenu() {

            System.out.println("\n***************************");

            System.out.println("*   Simple Calculator  *");

            System.out.println("***************************\n");

     

            System.out.println("1. Addition");

            System.out.println("2. Subtraction");

            System.out.println("3. Multiplication");

            System.out.println("4. Division");

            System.out.println("5. Quit");

      }

 

    static int getChoice() throws IOException{

      int choice;

      do {

         System.out.print("\nYour choice? : ");

         choice = Integer.parseInt(stdin.readLine());

      } while (choice < 0 || choice > 5);   

      return choice;

   }

  

   static double getNumber(String prompt) throws IOException {

         System.out.print(prompt);

         return Double.parseDouble(stdin.readLine());

   }

}

 

 

4.  Assignments

1.        Write Java program involving two classes: OddAndEven and TestOddAndEven.

OddAndEven has the following:

·         instance varaibales countOfOdd and countOfEven both of type int

·         A method addNumber that takes a number as parameter and increment countOfOdd if the number is odd, else increment countOfEven.

·         A method toString that returns a string in the form: “Number of Odd: x,  Number of Even : y”, where x and y are the values of the instance variables.

The TestOddAndEven class first creates OddAndEven object, then in a loop, read a number and use it to call the addNumber method until the user enters Q.  Finally, it prints the count of odd and even numbers entered.

 

 

2.        Write an applet that displays circles in alternating colors of black and white on a blue background as shown below.  Note: the diameter of the circles is 20

 

3.        Use the BankAccount class of lab06 and write a menu-driven application, TestBankAccount as described below:

The application first reads the account number, customer name and initial balance and uses these to create a BankAccount object.  It then displays a menu that allows the user to deposit, withdraw or display his balance.  The program should continue to execute until the user chooses the Quit option.  Note: After each withdrawal or deposit, the new balance should be displayed.