Iterative Statements, While Loop - Programming I - Notes | COP 2210, Study notes of Computer Science

Material Type: Notes; Professor: Smith; Class: Programming I; Subject: Computer Programming; University: Florida International University; Term: Unknown 1989;

Typology: Study notes

Pre 2010

Uploaded on 03/19/2009

koofers-user-hix
koofers-user-hix 🇺🇸

10 documents

1 / 39

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
ITERATIVE STATEMENTS ............................................................................................................................................ 1
The while Statement .............................................................................................................................................. 2
Nested while Loop ............................................................................................................................................ 8
The do…while Statement ..................................................................................................................................... 20
The for Statement ................................................................................................................................................ 22
Nesting for Loops. .......................................................................................................................................... 28
Scope of a Loop control variable .................................................................................................................... 29
PitFall ............................................................................................................................................................. 29
Pitfall I – Updating the loop variable incorrectly ................................................................................. 29
Pitfall II – Modifying the loop variable in loop body ........................................................................... 29
Iterative Statements
So far in our studies, we have discussed and have been using two forms of Java statements – sequence and selection.
There is a third type of Java statement – the iterative statements, commonly called loops. Iterative statements cause a
program to repeat certain statement or block of statements. The statement or block of statements is referred to as the
loop body. You may be wondering how the program knows to execute the loop body repeatedly. The answer is, a
conditional expression is used to determine if the loop is to continue to execute, or to terminate.
If you were asked to add all the integers from 1 to 1000 and the only method that you know was addition, you would
more than likely write something like this:
1 + 1 = 2
2 + 1 = 3
3 + 1 = 4
4 + 1 = 5
5 + 1 = 6
:
:
:
Surely it will not be long before you realize that this approach is repetitive and laborious. The concept, iteration,
which is a fundamental tool to programming, relieves us from this drudgery. In likewise manner, the computer is
capable of carrying out tasks on a repetitive basis.
Java provides three forms of iterative statements. These are the while statement, the do…while statement, and
the for statement.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27

Partial preview of the text

Download Iterative Statements, While Loop - Programming I - Notes | COP 2210 and more Study notes Computer Science in PDF only on Docsity!

ITERATIVE STATEMENTS............................................................................................................................................ 1

The while Statement .............................................................................................................................................. 2 Nested while Loop............................................................................................................................................ 8 The do…while Statement ..................................................................................................................................... 20 The for Statement ................................................................................................................................................ 22 Nesting for Loops........................................................................................................................................... 28 Scope of a Loop control variable.................................................................................................................... 29 PitFall............................................................................................................................................................. 29 Pitfall I – Updating the loop variable incorrectly................................................................................. 29 Pitfall II – Modifying the loop variable in loop body........................................................................... 29

Iterative Statements

So far in our studies, we have discussed and have been using two forms of Java statements – sequence and selection. There is a third type of Java statement – the iterative statements, commonly called loops. Iterative statements cause a program to repeat certain statement or block of statements. The statement or block of statements is referred to as the loop body. You may be wondering how the program knows to execute the loop body repeatedly. The answer is, a conditional expression is used to determine if the loop is to continue to execute, or to terminate. If you were asked to add all the integers from 1 to 1000 and the only method that you know was addition, you would more than likely write something like this: 1 + 1 = 2 2 + 1 = 3 3 + 1 = 4 4 + 1 = 5 5 + 1 = 6 : : : Surely it will not be long before you realize that this approach is repetitive and laborious. The concept, iteration, which is a fundamental tool to programming, relieves us from this drudgery. In likewise manner, the computer is capable of carrying out tasks on a repetitive basis. Java provides three forms of iterative statements. These are the while statement, the do…while statement, and the for statement.

The while Statement

The format of the while statement is as follows: while ( conditional_expression ) body; Where the word while is the Java keyword indicating a repetitive construct. Within the pair of parentheses is a conditional expression that must be tested, in order to determine if the loop body must be executed again, and again, until a certain condition stops it. The while statement specifies that the conditional expression must be tested at the beginning of the loop. If the conditional expression is initially false, then the loop body is skipped. Figure 4.14 shows a diagrammatical representation of the while loop. false true Figure 4.14 symbolic representation of the while loop. Example 4. Write a while loop that prints all the integers from 1 and 1000. Solution The solution to this problem focuses on two key issues - counting from 1 to 1000, and print the number. The solution is depicted in Figure 4.. Loop body (Usually includes updating the loop variable. Program execution continues counter = 1 conditional expression Initialize the loop variable

Analysis: Based on the problem definition, we cannot tell in advance the number of digits contained in a given number. We must however, print the digits from the rightmost to the leftmost one. That is:

  1. Given a number, say, N.
  2. The rightmost digit that is to be printed is determined by N%10. For example, if the number is 234, then the rightmost digit to be printed is 234%10 , which is 4.
  3. The next rightmost digit in N is determined by N/10. Using the example 234 , the next rightmost digit is 234/10 which is the number 23. This is N.
  4. Steps 2 and 3 are repeated until the new value in N is zero. For instance, let N = 234, then the process works this way: N Process Digit printed 234 234%10 4 23 234/ 23 23%10 3 2 23/ 2 2%10 2 0 2/ Listing 4.16 shows the class ReverseNumber. It is a translation of the algorithm worked out above. 1. public class ReverseNumber 2. { 3. private int N; 4. private String s; 5. public ReverseNumber(int N) 6. { 7. this.N = N; 8. s = ""; 9. } 10. void reverse() 11. { 12.while (N > 0) 13.{ 14.s = s + N%10; 15.N = N/10; 16.} 17. } 18. public String toString() { return s; } 19. }

Listing 4.16 shows how the digits in a given integer can be reversed. The constructor accepts an arbitrary integer N. The method reverse() , shown on Lines 10 – 17 shows the process by which the digits are reversed. The while clause shows the conditional expression which governs the loop body – Lines 14 and 15. As long as the conditional expression is evaluate to true, the loop continues to iterate. The iteration stops when N becomes zero. Note: instead of printing the digits immediately after generating them, they are appended by the string variable s , Line 15. Listing 4.17 shows a typical test class that utilizes the class ReverseNumber.

  1. public class TestReverseNumber
  2. {
  3. public static void main(String[] arg)
  4. {
  5. ReversingNumber r = new ReversingNumber(24500);
  6. r.reverse();
  7. System.out.println(r);
  8. }
  9. } Listing 4.17 Test class for the class ReverseNumber. Sometimes the conditional expression stated in the problem is less intuitive than what we have seen in the previous section. When such situations arise, there is a high degree that two or more relational expressions are involved. If you are faced with situations of this kind, design a Boolean method solely to formulate and test the condition under which the loop will operate. Example 4. The XYZ School wants to carry its grade 10 students on a trip. The cost of the trip is $5,000.00. The school has only thirty days in which to collect the funds in order to go on the trip. Design a class called SchoolContribution that creates a contribution account. Incorporate the following:  A method called totalContribution(..) that accepts and accumulates the daily contributions.  A Boolean method called hasMoreTime() that determines if more time is needed to reach the targeted amount.  A Boolean method called hasNotMadeTarget() that determines if more contribution is needed.
  1. static final float TARGET = 5000;
  2. int day;
  3. double totalContribution;
  4. String s;
  5. NumberFormat df;
  6. public SchoolContribution()
  7. {
  8. totalContribution = 0;
  9. day = 0;
  10. s = "Day \tDaily Contribution\tTotal Contribution\n";
  11. df = NumberFormat.getCurrencyInstance();
  12. }
  13. public void addContribution(double amount)
  14. {
  15. totalContribution = totalContribution + amount;
  16. day = day + 1;
  17. s = s + day + "\t " + df.format(amount);
  18. s = s + "\t\t " + df.format(totalContribution) + "\n";
  19. }
  20. public boolean hasNotMadeTarget ()
  21. {
  22. return totalContribution < TARGET;
  23. }
  24. public boolean hasMoreTime()
  25. {
  26. return day < MAX_DAYS;
  27. }
  28. public boolean metTarget ()
  29. {
  30. return day <= MAX_DAYS && totalContribution > TARGET;
  31. }
  32. public String toString() { return s; }
  33. } Listing 4.18 the class SchoolContribution To summarize, this class simply does the following:  It accepts the daily amounts, accumulates the contributions, and updates the day count. These activities are shown the method addContribution(…).  Determines the conditional expression for the loop as seen in the method didNotMakeTarget().

 Determines whether or not the target was made. See the method isInadequate(). Listing 4.19 shows the code for the test class, TestContribution. The class does the following:  Creates an empty contribution account.  Continuously check if the target has been met. It uses the result from the method didNotMakeTarget() to control the loop after a day’s contribution has been made.  Prints the result after the loop is exited. The if statement on Line 12 uses the result from the Boolean method isInadequate() to print the result.

1. import javax.swing.JOptionPane; 2. public class TestContribution 3. { 4. public static void main(String[] arg) 5. { 6. SchoolContribution s = new SchoolContribution(); **_7. while (s. hasNotMadeTarget() && s.hasMoreTime())

  1. {
  2. s.addContribution(Double.parseDouble( 10.JOptionPane.showInputDialog("Make contribution"))); 11.} 12._** if (s. metTarget ()) System.out.println(s); else System.out.println("We did not make the target" + "\nSorry we cannot go on the trip\n" + s); 13. } 14. } Listing 4. 19 the test class TestContribution. In Listing 4.19, the while statement monitors the loop body. It calls the methods hasNotMadeTarget() and hasMoreTime() to tell if the loop must continue.

Nested while Loop

The while statement like the if statement, can be nested. Recall that the format of the while statement is: while (condition)

This diagram is interpreted as follows – if condition 1 is true, then the inner part of the diagram is executed; but the execution contains another condition. That is, what follows condition1 represents the outer loop body. This loop body constitutes condition2. If this condition is true, then what follows is the inner loop body. This loop repeats until condition 2 is false, at which time execution returns to the outer loop. The outer loop continues until condition1 is false, at which time the entire loop terminates. Example 4.xx A company has five stores – A , B , C , D , and E – at different locations across the state of Florida. At the end of each week the company’s management prints a report of the daily sales and the total sales for each of the stores. Write a class called Sales that prints the sales and the total sales for each of the stores, row by row.

  1. import javax.swing.JOptionPane;
  2. import java.text.NumberFormat;
  3. public class Sales
  4. {
  5. private double totalSales;
  6. private static final int DAYS = 7;
  7. private static final char STORES = 'E';
  8. private String header;
  9. private String s;
  10. private static final NumberFormat nf= NumberFormat.getCurrencyInstance();
  11. public Sales()
  12. {
  13. totalSales = 0;
  14. s = "";
  15. header = "Store\t\t\tDay\n" +
  16. "\t1\t2\t3\t4\t5\t6\t7\tTotal\n";
  17. }
  18. public void getSales()
  19. {
  20. char store = 'A';
  21. while (store <= STORES)
  22. {
  23. s = s + store + " - ";
  24. int day = 1;
  25. totalSales = 0;
  26. while (day <= DAYS)
  27. {
  28. double amount = Double.parseDouble(JOptionPane.showInputDialog( "Store " + store + "\nDay " + day + "\nEnter amount"));
  29. s = s + "\t" + nf.format(amount);
  1. day++;
  2. totalSales = totalSales + amount;
  3. }
  4. s = s + "\t" + nf.format(totalSales) + "\n";
  5. store++;
  6. }
  7. }
  8. public String toString()
  9. }
  10. return header + s;
  11. }
  12. } _1. import javax.swing.JOptionPane;
  13. import javax.swing.JScrollPane;
  14. import javax.swing.JTextArea;

5._ public class TestSales 6. { 7. public static void main(String[] arg) 8. { 9. Sales s = new Sales(); 10. s.getSales(); 11. JTextArea t = new JTextArea(s.toString(), 8, 50); 12. JScrollPane p = new JScrollPane(t); 13. JOptionPane.showMessageDialog(null, p, "Weekly Sales", JOptionPane.INFORMATION_MESSAGE 14. );} 15. }

StringTokenizer(String s) This constructor parses a string into tokes by using default delimiters. These default delimiters are: the space character, the tab character, the new line character, the carriage- return character, and the form-feed character.  StringTokenizer(String s, String delimiter) This constructor parse a string according to the delimiter specified. The delimiter itself is not part of any of the tokens. The second constructor is more applicable in this problem, because we can use the comma character as the delimiter between tokens. Three of the more frequently used methods in this class are:  boolean hasMoreTokens() This method tests if there are more tokens available in the string.  String nextToken() This method returns the next available token from the string.  String nextToken(String delimiter) This method uses the argument given to set a new default delimiter. It then returns the next available token.  countTokens() This method returns a count of the number of tokens in the string. The class StringTokenizer is found in the java.util package. It must be imported. Now that we have the requisite tools, we can move on to solving the problem. Let us do the following:

  1. Name the class that makes the mailing labels MailingLabels.
  2. Define a method called makeLabels(…) that accepts string values, one at a time and tokenizes each. Figure 4.13 shows how the method will loop through a tokenized string to get the next available token. Listing 4.20 shows the code for the class MailingLabels. false true Tokenize string

hasMoreTokens(

Get nextToken() and process it Next statement

Figure 4.13 shows how the while loop will be used to get a get a token. Listing 4.20 implements the flow diagram shown in Figure 4..

1. import java.util.StringTokenizer; 2. public class MailingLabels 3. { 4. String s; 5. MailingLabels() { s = ""; } **_6. void makeLabels(String str)

  1. {
  2. String token = "";
  3. StringTokenizer t = new StringTokenizer(str, ","); 10.while (t.hasMoreTokens()) 11.{ 12.token = t.nextToken(); 13.token = token.trim(); 14.s = s + token + "\n"; 15.} 16.s = s + "\n\n"; 17.} 18._** public String toString() { return s; } 19. } Listing 4.20 the code for the class MailingLabels****. The focus in this class is how the while construct makes use of the StringTokenizer class. First of all, in order to use the StringTokenizer class, it has to be imported, as seen in Listing 4.20, Line 1. The method makeLabels is the next key issue. This class accepts a string value. See the method header, Line 6. Line 9 thru Line 16 is a translation of Figure 4.13. First the string is tokenized, using the comma as the delimiter. See Line 9. Next the Boolean method hasMoreTokens() checks to see if there is another token in the tokenized string. See Line 10. If there is another token, it processes it; if there is no more, then the loop body is skipped, and control passes to Line 16. Also, notice the loop body: Line 12 fetches the next available token; Line 13 trims any blank that may be to the left or to the right of the string; and Line 14 simply concatenates this new token and the new line character to the existing output string, s. Listing 4.21 show a typical test class for the class MailingLabels.

In general the ith^ term is: xi = (-1)i/(2i + 1)

This type of problem requires you to compare the absolute value of the difference of two successive terms. If the value is less that the threshold or margin of error, then the new value generated is the approximation to the actual value. In other words, while ( |xnew – xold| > some margin of error) { sum the new value to previous amount save the new as old. generate the new value, xnew. } In this example the margin of error is 0.00000005. In addition, each new term may be generated as follows expression: xn = Math.pow(-1.0, n)/(2 * n + 1); Listing 4.22 shows the class PI.

1. import java.text.NumberFormat; 2. import java.text.DecimalFormat; 3. public class PI 4. { 5. static final double MARGIN_OF_ERROR = 0.00000005; 6. double sum; 7. int iterate; 8. public PI() { sum = 1; } 9. public double findXnew(int n) 10. { 11. return Math.pow(-1.0, n)/(2 * n + 1); 12. } 13. public void findPi() 14. { 15. int i = 1; 16. double xold = 1.0; 17. double xnew = findXnew(i); 18.while (Math.abs(xnew - xold) > MARGIN_OF_ERROR) 19.{

20.sum = sum + xnew; 21.xold = xnew; 22.i++; 23.xnew = findXnew(i); 24.}

25. iterate = i; 26. } 27. public String toString() 28. { 29. NumberFormat nf = NumberFormat.getInstance(); 30. DecimalFormat df = (DecimalFormat)nf; 31. df.applyPattern("0.00000000"); 32. return "The approximate value of pi is " + df.format((4*sum)) + "\n" + "The number of iterations is " + iterate; 33. } 34. } Listing 4.22 the class PI. The test class shown in Listing 4.23 simply creates a PI object, calls the method findPi, and then prints the result.

  1. public class TestPI
  2. {
  3. public static void main(String[] arg)
  4. {
  5. PI p = new PI();
  6. p.findPi();
  7. System.out.println(p);
  8. }
  9. } Listing 4.23 the test class TestPI. Exercises 4c
  10. Study the following programs and write down what will appear on the screen you compile and execute them. (a) public class Mystry { public static void main(String[] arg)

while (j >= 1) { System.out.println("\t" + j); j--; } System.out.println("---------"); i--; } } }

  1. Write a class called TestScores. For any given student the initial score is 0. Write a method called addScores that accepts the score for each individual and sums them. Also, write a method called avergarScore that calculates and return the average score for each student. Write a test class called TestScores. This class uses the JOptionPane input dialog window to read each score. The first number read, represents the number of scores for each student. This is followed by the actual scores.
  2. Write a class called Numbers to find the minimum of a sequence of nonnegative numbers. The class is supplied the numbers one by one. Write a method called findMinimum to determine the number that is the least. Provide methods to return the numbers in the order that they were read, the number of entries, and the number which is the least in the sequence. The value that terminates the process must not be printed. Write a test class that generates the numbers. When a negative number is entered, the process stops, and the output is generated. For example, given the following input values 120 250 450 50 200 100 75 -10, the program should generate an output similar to the following.
  3. Modify Exercise 3 to incorporate a method to find the largest number in the sequence. The program should generate out similar to the following.
  1. Write a Java program that can be used to produce patterns of the following form:

The do…while Statement

The do …while statement is opposite in a way to the while statement, in that the conditional expression comes after the loop body. The format of the do … while statement is: do { statement; } while ( condition ) ; Where the word do is the keyword, indication the beginning of the do..while loop. The pair of curly braces is mandatory, even if the loop body is a single statement. The statement finishes with the while clause. Notice that the conditional expression is enclosed within parentheses. In addition, the entire statement must terminate with a semi-colon. true conditional_express ion Loop body