Home
Examples
Labs
Assignment
Marks
Midterm
Final Exam
Resources

Repeated Execution of Code

Loops are used to execute the same block of code repeatedly.  In general, a loop will execute as long as its condition remains true.  Primitive data types like char, boolean and int make good loop control variables.  We have covered three different types of loops in this class :
  • while loop
  • for loop
  • do loop


while Loop

The while loop is the most general type of loop.  All looping code can be written using a while loop.  Other types of loops are used just because they are more elegant in certain situations - they are designed for particular scenarios that arise often in programming.  Here is the general form of the while loop.

         while (condition) {
              java statement;
              java statement;
              java statement;
           } // end while

For example: The following while loop will print 10 stars in a row on the screen.  The variable count is the loop control variable.  We continue looping as long as the value in count is less than the value in max (10).  Notice that every time we go through the loop we increment the value of count by 1.  Eventually, the value in count will be larger than the value in max and we will drop out of the loop.

         int count = 1;
         int max = 10;
         while (count <= max) {
              System.out.println(" * ");
              count++;
           } // end while

Another example: The following while loop will continue to read and sum numbers from the user until the user enters a `Q' to indicate that they are done.  We use the boolean variable done to keep track of whether or not the user is finished entering numbers.  Notice that if the user has entered anything but a Q, we assume that they have entered a valid numerical value.

         done = false;
         sum = 0;
         while (!done) {
              System.out.print(" Enter an int, or Q for quit >");
              String userInput = kb.readLine();
              if (userInput.charAt(0)=='Q`)
                   done = true;
              else
                   sum = sum + Integer.parseInt(userInput);
           } // end while


for Loop

The for loop is designed especially for counting.  We use a for loop when we know exactly how many times that we will need to execute the loop.  Here is the general form of the for loop:

           for (startValue; condition; count) {
              java statemetn;
              java statemetn;
              java statemetn;
            } // end for

For Example: The following for loop will execute exactly ten times.  The loop will start counting at 1.  It will continue counting as long as we have not counted past 10.   We will count forward in steps of 1.  Like the while loop above, this for loop will print 10 stars in a row on the screen.

           for (int i = 1; i <= 10; i++) {
              System.out.println(" * ");
            } // end for

Another example: Note that we can count backwards, and also use variables to represent the starting and stopping counts of the loop.  In this snippet of code, we ask the user how many stars they would like to print on the screen, and we count down from that number - stopping when we get to 1.

           System.out.print(" How many stars? > ");
           int maxStar = Integer.parseInt(kb.readLine());
           int minStar = 1;
           for (int i = maxStar; i >= minStar; i--) {
              System.out.println(" * ");
            } // end for


Bottom Tested Loops

The do loop is a bottom tested loop.  Instead of checking the loop condition at the top of the loop, the condition is checked at the bottom.  This is useful because it guarantees that we execute the body of the loop at least once.   Use a do loop when you want your loop code carried out at least one time.  Here is the general form of a do loop in java.  Notice the semicolon after the condition this time.
           do {
              java statement;
              java statement;
              java statement;
            } (condition);

For example: Display a menu and read in the user's choice until the user enters Q for quit.  We will want to show the user the menu at least one time.  The first choice that the user enters may be Q for quit - but we should show the menu and read a choice at least once.
           char choice;
           do {
             // Display a Menu
                System.out.println(" Menu ");
                System.out.println(" A - Add a List of Numbers ");
                System.out.println(" M - Multiplication Table ");
                System.out.println(" S - Calculate Square Root ");
                System.out.println();
                System.out.print(" Choice > ");

             // Read the user's choice
                String inputString = kb.readLine();

             // Convert the choice to a single uppercase char
                inputString = inputString.toUpperCase();
                char choice = inputString.charAt(0);

             // Use an if statement to check the user's choice
                if (choice == `A')
                      . . . 
                else if (choice == `M')
                      . . .
                else if (choice == `S')
                     . . .
           } (choice != `Q');   // end do



About null

In java we use null to mean an "empty object".   When a reference variable has a null value, it means that it refers to no object - it points to nothing.  In the above example s is assigned the value of null when we reach the end of the file and there are no more String objects left to read.



A Few More Loop Examples

It will not always be obvious what a piece of code does when you look at it for the first time.  This is especially true of code that uses control structures like if-else statements and loops.  If you aren't sure what a piece of code does, trace its execution.  Figure out how the value of the variables will change as each statement of the code is carried out.  The more code that you write and read the better you will become at doing this.  Here are some more examples using loops.



Sum the Numbers from 1 to 100

           int sum = 0;
           for (int i = 1; i <=100; i++) {
                sum = sum + i;
              }  // end for


Find the Largest Number in a File

Assume that each line of the file contains a single integer.  Also assume that we have a BufferedReader named br to read from the file.
           String s = br.readLine();
           int largest = Integer.parseInt(s);
           while (s != null) {
                if (Integer.parseInt(s) > largest)
                      largest = Integer.parseInt(s);
                s = br.readLine();
             }  // end while


Check if a Number is Prime

Notice that that we only need to check possible divisors up to the square root of the number.
       System.out.print("Enter an integer > ");
       int number = Integer.parseInt(b.readLine());
       boolean isPrime = true;
       int max = Math.round(Math.sqrt(Math.abs(number));

       for (int i = 2; i <= max); i++) {
                if ((number % i) == 0) 
                         isPrime = false;
          }  // end for

       if (isPrime)
            System.out.println(number + " is prime");
       else
            System.out.println(number + " is not prime");


Print all the Factors of 50

        for (int i = 1; i <= 50); i++) {
            if ((50 % i) == 0) 
                  System.out.println(i + "is a factor.");
          }  // end for