CSC 012

Introduction to Computer Science

 

Summary of 3/20 Lecture

Today, we introduced a variation on the while loop.   It is only appropriate for counter-controlled loops.  That is, if the loop is to be ended by the end of input (eoi) signal, then we must continue to rely on the while loop.  Let's look at an example.

Example 1.  Rewrite the suffix loop problem so that the user is asked up front how many times input will be requested.

//File:    SuffixLoop2.java
/*
After trying to test all of the possibilities, we decided
that it would be nice if the computer could just ask us if
we wanted to continue. Then, we wouldn't have to keep
running our program again to try different numbers.

This brings us to the third of the big three ideas in
structured programming, repetition or loops.

All we need do is wrap up what we had done before into
a loop that keeps repeating for as long as we want it to.
*/
import java.awt.*;
import CSLib.*;

//This version first asks the user "how many suffixes to process".
//Then, for each number entered, the appropriate suffix is added.

public class SuffixLoop2
{
    public void doIt()
    {
        //KEEP REPEATING THE FOLLOWING
        //UNTIL THE USER SAYS STOP
        InputBox in = new InputBox();
        in.setPrompt ("How many suffixes do you want to process? ");
        int n = in.readInt(); //Get the number from the user
       
        for (int counter=1; counter<=n; counter++)
        {
            //INPUT SECTION
            in = new InputBox();
           
            in.setLocation (150, 150);    //Moves the InputBox over
                                                        //to make the OutputBox easier to see
            Font myFont = new Font ("Serif", Font.ITALIC+Font.BOLD, 24);
            in.setFont (myFont);
            in.setBackground (Color.yellow);
            in.setForeground (Color.red);
            in.setPrompt("Please type in a number"
                                    + " between 0 and 100.");
            int number = in.readInt();
            String suffix=" ";
       
            //CALCULATION SECTION
            if (number==11||number==12||number==13)
                    suffix = "th";
            else //take advantage of the pattern
            {
                switch (number % 10)
                {
                    case 1:        suffix = "st";
                                        break;
                           
                    case 2:        suffix = "nd";
                                        break;
                           
                    case 3:        suffix = "rd";
                                        break;
                           
                    default:     suffix = "th";
                }//end switch
            }//end else
       
            //OUTPUT SECTION
            OutputBox out = new OutputBox("Add Suffixes");
            out.setSize (350, 150);
            out.println ("You gave me the number "
                                + number + ".\n\n\n");
            out.println ("That corresponds to the"
                                + " adjective " + number
                                + suffix + ".");
        }//end while
        Timer.pause(4000);    //wait before destroying the output box
        System.exit(0);
    }
}

Example 2.  Rewrite the score averaging problem as described in Example 1.

//File:    Score.java
import CSLib.*;
//This version first asks the user "how many scores to process".
//Then,.....

//The program asks the user to enter scores between 0 and 100.  After processing
//all the scores, the program then outputs the number of scores and the average of the scores.
public class Score
{
    public static void main (String [] args)
    {
        //Declare variables
        InputBox in = new InputBox("Average Score");
        int         score,
                    sum=0;
           
        in.setPrompt("How many scores to process?");
        int n = in.readInt();    
        for (int k=1; k<=n; k++)
        {
            //Get input from user
            in.setPrompt("Enter score: ");
            score = in.readInt();
           
            sum = sum + score; //accumulate the sum of the scores entered
        }
        //Output the results
        OutputBox out = new OutputBox("Average Scores");
        out.setSize(300, 100);
        out.println ("The average of the " + n + " scores is: " + sum/n);
    }
}

The common feature of each of the above examples is that the number of repetitions desired (n) is the first data entered.  Then a counter is created, initialized, and successively incremented.  The loop is ended not at "end of input" (eoi()), but rather when the counter reaches "n", the number of cycles requested.  All of this could be accomplished without this new device, called a "for" loop, using only the familiar while loop we already know.  The general outline follows:

Input number of times to execute the loop, call it n

counter =1; //Initialize the counter
while (counter <= n) //Test the counter
{
    process the information
    counter = counter +1; //Increment the counter
}

The whole purpose of the for loop is to allow us (the programmer) to abbreviate as follows:

for (int counter=1; counter<=n; counter=counter++)
{
    process the information
}

Keep in mind, however, that both of these solutions are equivalent.   Take your pick.  I think the for loop offers a convenient, and perhaps more foolproof, alternative to the standard while syntax.  But it is ONLY a counter-controlled loop.  It cannot be used when the loop is ended by an end of input (eoi()) signal.


Lab Exercise.  Rewrite the lab exercise from last class, requiring the user to provide the number of iterations as the first piece of input.   The problem, if you've forgotten is given as follows:

Write a program that sums the integers from 1 to n, where n is provided by the user.  For example, if the user enters 6 (for n), then your program will provide the results of

1 + 2 + 3 + 4 + 5 + 6 = 21

If you're stumped for ideas, you can check my solution.


Back to CSC 012 Home Page