Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 4 Statement Forms. Statement types 1.Simple statements expression; println(“The total is “ + total + “.”); (method call) 2. Compound statements.

Similar presentations


Presentation on theme: "Chapter 4 Statement Forms. Statement types 1.Simple statements expression; println(“The total is “ + total + “.”); (method call) 2. Compound statements."— Presentation transcript:

1 Chapter 4 Statement Forms

2 Statement types 1.Simple statements expression; println(“The total is “ + total + “.”); (method call) 2. Compound statements { statement1;... statementn; }

3 3.Control statements Conditional statements: if, switch Iterative statements: for, while

4 3.Control statements Conditional statements: if, switch Iterative statements: for, while Example: Add more than 2 integers Three startegies Duplicating the code in Add2Integers; Repeating the input cycle a predetermined number of times; Repeating the input cycle until the user enters a special sentinel value;

5 public class Add4Integers extends ConsoleProgram { public void run() { println(“This program adds four integers.”); int n1 = readInt(“ ? “); int n2 = readInt(“ ? “); int n3 = readInt(“ ? “); int n4 = readInt(“ ? “); int total = n1 + n2 + n3 + n4; println(“The total is “ + total + “.”); } Difficult to generalize Cumbersome to add 100 values

6 The repeat-N-times idiom for (int i = 0; i < N; i++) { statements to be repeated }

7 The repeat-N-times idiom for (int i = 0; i < N; i++) { statements to be repeated } header line: for (int i = 0; i < N; i++) body: statements to be repeated control variable: i

8 /* * file: AddNIntegers.java * ------------------------------ * This program adds a predefined number of integers * and then prints the total. To change the number of * integers, change the definition of N_VALUES */ Import acm.program.*;

9 public class AddNIntegers extends ConsoleProgram { public void run() { println(“This program adds “ + N_VALUES + “integers.”); int total = 0; for (int i = 0; i < N_VALUES; i++) { int value = readInt(“ ? “); total += value; } println(“The total is “ + total + “.”); } /* specifies the number of values */ private static final int N_VALUES = 4; }

10 Tracing the program public void run() { println(“This program adds “ + N_VALUES + “integers.”); int total = 0; for (int i = 0; i < N_VALUES; i++) { int value = readInt(“ ? “); total += value; } println(“The total is “ + total + “.”); } N_VALUES (4) total (0) i ( ) value ( )

11 Tracing the program public void run() { println(“This program adds “ + N_VALUES + “integers.”); int total = 0; for (int i = 0; i < N_VALUES; i++) { int value = readInt(“ ? “); total += value; } println(“The total is “ + total + “.”); } N_VALUES (4) total (0) i (0) value ( )

12 Tracing the program public void run() { println(“This program adds “ + N_VALUES + “integers.”); int total = 0; for (int i = 0; i < N_VALUES; i++) { int value = readInt(“ ? “); total += value; } println(“The total is “ + total + “.”); } N_VALUES (4) total (0) i (0) value ( )

13 Tracing the program public void run() { println(“This program adds “ + N_VALUES + “integers.”); int total = 0; for (int i = 0; i < N_VALUES; i++) { int value = readInt(“ ? “); total += value; } println(“The total is “ + total + “.”); } N_VALUES (4) total (0) i (0) value (1)

14 Tracing the program public void run() { println(“This program adds “ + N_VALUES + “integers.”); int total = 0; for (int i = 0; i < N_VALUES; i++) { int value = readInt(“ ? “); total += value; } println(“The total is “ + total + “.”); } N_VALUES (4) total (1) i (0) value (1)

15 Tracing the program public void run() { println(“This program adds “ + N_VALUES + “integers.”); int total = 0; for (int i = 0; i < N_VALUES; i++) { int value = readInt(“ ? “); total += value; } println(“The total is “ + total + “.”); } N_VALUES (4) total (1) i (1) value (1)

16 Tracing the program public void run() { println(“This program adds “ + N_VALUES + “integers.”); int total = 0; for (int i = 0; i < N_VALUES; i++) { int value = readInt(“ ? “); total += value; } println(“The total is “ + total + “.”); } N_VALUES (4) total (1) i (1) value (1)

17 Tracing the program public void run() { println(“This program adds “ + N_VALUES + “integers.”); int total = 0; for (int i = 0; i < N_VALUES; i++) { int value = readInt(“ ? “); total += value; } println(“The total is “ + total + “.”); } N_VALUES (4) total (1) i (1) value (2)

18 Tracing the program public void run() { println(“This program adds “ + N_VALUES + “integers.”); int total = 0; for (int i = 0; i < N_VALUES; i++) { int value = readInt(“ ? “); total += value; } println(“The total is “ + total + “.”); } N_VALUES (4) total (3) i (1) value (2)

19 Tracing the program public void run() { println(“This program adds “ + N_VALUES + “integers.”); int total = 0; for (int i = 0; i < N_VALUES; i++) { int value = readInt(“ ? “); total += value; } println(“The total is “ + total + “.”); } N_VALUES (4) total (3) i (2) value (2)

20 Tracing the program public void run() { println(“This program adds “ + N_VALUES + “integers.”); int total = 0; for (int i = 0; i < N_VALUES; i++) { int value = readInt(“ ? “); total += value; } println(“The total is “ + total + “.”); } N_VALUES (4) total (3) i (2) value (2)

21 Tracing the program public void run() { println(“This program adds “ + N_VALUES + “integers.”); int total = 0; for (int i = 0; i < N_VALUES; i++) { int value = readInt(“ ? “); total += value; } println(“The total is “ + total + “.”); } N_VALUES (4) total (3) i (2) value (3)

22 Tracing the program public void run() { println(“This program adds “ + N_VALUES + “integers.”); int total = 0; for (int i = 0; i < N_VALUES; i++) { int value = readInt(“ ? “); total += value; } println(“The total is “ + total + “.”); } N_VALUES (4) total (6) i (2) value (3)

23 Tracing the program public void run() { println(“This program adds “ + N_VALUES + “integers.”); int total = 0; for (int i = 0; i < N_VALUES; i++) { int value = readInt(“ ? “); total += value; } println(“The total is “ + total + “.”); } N_VALUES (4) total (6) i (3) value (3)

24 Tracing the program public void run() { println(“This program adds “ + N_VALUES + “integers.”); int total = 0; for (int i = 0; i < N_VALUES; i++) { int value = readInt(“ ? “); total += value; } println(“The total is “ + total + “.”); } N_VALUES (4) total (6) i (3) value (3)

25 Tracing the program public void run() { println(“This program adds “ + N_VALUES + “integers.”); int total = 0; for (int i = 0; i < N_VALUES; i++) { int value = readInt(“ ? “); total += value; } println(“The total is “ + total + “.”); } N_VALUES (4) total (6) i (3) value (4)

26 Tracing the program public void run() { println(“This program adds “ + N_VALUES + “integers.”); int total = 0; for (int i = 0; i < N_VALUES; i++) { int value = readInt(“ ? “); total += value; } println(“The total is “ + total + “.”); } N_VALUES (4) total (10) i (3) value (4)

27 Tracing the program public void run() { println(“This program adds “ + N_VALUES + “integers.”); int total = 0; for (int i = 0; i < N_VALUES; i++) { int value = readInt(“ ? “); total += value; } println(“The total is “ + total + “.”); } N_VALUES (4) total (10) i (4) value (4)

28 Tracing the program public void run() { println(“This program adds “ + N_VALUES + “integers.”); int total = 0; for (int i = 0; i < N_VALUES; i++) { int value = readInt(“ ? “); total += value; } println(“The total is “ + total + “.”); } N_VALUES (4) total (10) i (4) value (4)

29 Tracing the program public void run() { println(“This program adds “ + N_VALUES + “integers.”); int total = 0; for (int i = 0; i < N_VALUES; i++) { int value = readInt(“ ? “); total += value; } println(“The total is “ + total + “.”); } N_VALUES (4) total (10) i (4) value (4)

30 The repeat-until-sentinel Read numbers until the user signals the end of input data. Sentinel: A special value, not a legitimate data value, signals the end of input data.

31 The repeat-until-sentinel Read numbers until the user signals the end of input data. Sentinel: A special value, not a legitimate data value, signals the end of input data. Examples Add a list of integers sentinel: 0 Average grades Sentinel: -1

32 Repeat-until sentinel idiom while (true) { prompt user and read in a value if (value == sentinel) break; rest of the loop body }

33 A sample output This program adds a list of integers. Enter values, one per line, using 0 to signal the end of the list. ? 1 ? 2 ? 3 ? 0 This total is 6.

34 /* * File: AddIntegerList.java * -------------------------------- * This program reads integers one per line until the * user enters a special sentinel value to signal the * end of the input. At that point, the program prints * the sum of the numbers entered so far. */ import acm.program.*;

35 public class AddIntegerList extends ConsoleProgram { public void run() { println(“This program adds a list of integers.”); println(“Enter values, one per line,”); println(“using “ + SENTINEL + “ to signal the end of the list.”); int total = 0; while (true) { int value = readInt(“ ? “); if (value == SENTINEL) break; total += value; } println(“The total is “ + total + “.”); } /* Specifies the value of the sentinel */ private static final int SENTINEL = 0; }

36 Tracing the program int total = 0; while (true) { int value = readInt(“ ? “); if (value == SENTINEL) break; total += value; } println(“The total is “ + total + “.”); SENTINEL (0) total (0) value ( )

37 Tracing the program int total = 0; while (true) { int value = readInt(“ ? “); if (value == SENTINEL) break; total += value; } println(“The total is “ + total + “.”); SENTINEL (0) total (0) value ( )

38 Tracing the program int total = 0; while (true) { int value = readInt(“ ? “); if (value == SENTINEL) break; total += value; } println(“The total is “ + total + “.”); SENTINEL (0) total (0) value (1)

39 Tracing the program int total = 0; while (true) { int value = readInt(“ ? “); if (value == SENTINEL) break; total += value; } println(“The total is “ + total + “.”); SENTINEL (0) total (0) value (1)

40 Tracing the program int total = 0; while (true) { int value = readInt(“ ? “); if (value == SENTINEL) break; total += value; } println(“The total is “ + total + “.”); SENTINEL (0) total (1) value (1)

41 Tracing the program int total = 0; while (true) { int value = readInt(“ ? “); if (value == SENTINEL) break; total += value; } println(“The total is “ + total + “.”); SENTINEL (0) total (1) value (1)

42 Tracing the program int total = 0; while (true) { int value = readInt(“ ? “); if (value == SENTINEL) break; total += value; } println(“The total is “ + total + “.”); SENTINEL (0) total (1) value (2)

43 Tracing the program int total = 0; while (true) { int value = readInt(“ ? “); if (value == SENTINEL) break; total += value; } println(“The total is “ + total + “.”); SENTINEL (0) total (1) value (2)

44 Tracing the program int total = 0; while (true) { int value = readInt(“ ? “); if (value == SENTINEL) break; total += value; } println(“The total is “ + total + “.”); SENTINEL (0) total (3) value (2)

45 Tracing the program int total = 0; while (true) { int value = readInt(“ ? “); if (value == SENTINEL) break; total += value; } println(“The total is “ + total + “.”); SENTINEL (0) total (3) value (2)

46 Tracing the program int total = 0; while (true) { int value = readInt(“ ? “); if (value == SENTINEL) break; total += value; } println(“The total is “ + total + “.”); SENTINEL (0) total (3) value (3)

47 Tracing the program int total = 0; while (true) { int value = readInt(“ ? “); if (value == SENTINEL) break; total += value; } println(“The total is “ + total + “.”); SENTINEL (0) total (3) value (3)

48 Tracing the program int total = 0; while (true) { int value = readInt(“ ? “); if (value == SENTINEL) break; total += value; } println(“The total is “ + total + “.”); SENTINEL (0) total (6) value (3)

49 Tracing the program int total = 0; while (true) { int value = readInt(“ ? “); if (value == SENTINEL) break; total += value; } println(“The total is “ + total + “.”); SENTINEL (0) total (6) value (3)

50 Tracing the program int total = 0; while (true) { int value = readInt(“ ? “); if (value == SENTINEL) break; total += value; } println(“The total is “ + total + “.”); SENTINEL (0) total (6) value (0)

51 Tracing the program int total = 0; while (true) { int value = readInt(“ ? “); if (value == SENTINEL) break; total += value; } println(“The total is “ + total + “.”); SENTINEL (0) total (6) value (0)

52 Tracing the program int total = 0; while (true) { int value = readInt(“ ? “); if (value == SENTINEL) break; total += value; } println(“The total is “ + total + “.”); SENTINEL (0) total (6) value (0)

53 Tracing the program int total = 0; while (true) { int value = readInt(“ ? “); if (value == SENTINEL) break; total += value; } println(“The total is “ + total + “.”); SENTINEL (0) total (6) value (0)

54 Average grade Changes new variable: int count new variable: double average SETINEL = -1 comments

55 public class AverageGrade extends ConsoleProgram { public void run() { println(“This program calculates average grades.”); println(“Enter grades, one per line,”); println(“using “ + SENTINEL + “ to signal the end of the list.”); int total = 0; int count = 0; while (true) { int value = readInt(“ ? “); if (value == SENTINEL) break; total += value; count++; } double average = (double) total / count; println(“The average is “ + average + “.”); } /* Specifies the value of the sentinel */ private static final int SENTINEL = -1; }

56 Zeros are not counted int total = 0; int count = 0; while (true) { int value = readInt(“ ? “); if (value == SENTINEL) break; if (value > 0) { total += value; count++; } double average = (double) total / count; println(“The average is “ + average + “.”);

57 What if count = 0? int total = 0; int count = 0; while (true) { int value = readInt(“ ? “); if (value == SENTINEL) break; if (value > 0) { total += value; count++; } if (count == 0) { println(“No grades entered.”); } else { /* count > 0 */ double average = (double) total / count; println(“The average is “ + average + “.”); }

58 Example: IsLeapYear.java /* * File: IsLeapYear.java * -------------------------- * * This program reads in a year and determines whether it is a * leap year. A year is a leap year if it is divisible by four, unless * it is divisible by 100. Years divisible by 100 are leap years only * if divisible by 400. */ Import acm.program.*;

59 public class IsLeapYear extends ConsoleProgram { public void run() { println(“This program checks for leap years.”); int year = readInt(“Enter year: “); boolean isLeapYear = (((year % 4) == 0) && ((year % 100) != 0)) || ((year % 400) == 0); if (isLeapYear) { println(year + “ is a leap year.”); } else { println(year + “ is not a leap year.”); }

60 Four forms of if statements Single-line if (condition) statement Multiline if (condition) { statements; } if-else if (condition) { statement1 } else { statement2 }

61 Cascading if (condition1) { statements1 } else if (condition2) { statements2... } else { statements }

62 Example: Sign of x If x > 0, sign(x) = 1; if x < 0, sign(x) = -1; if x == 0, sign(x) = 0. Using a table x > 0 < = 0 < 0 = 0 sign(x) 1 -1 0

63 The ? : operator condition ? expressionT : expressionF equivalent to if (condition) { expressionT } else { expressionF }

64 Examples Max = (x >y)? x : y; println(nItems + “item” + ((nItems == 1) ? “” : “s”) + “ found.”);

65 The switch statement switch (e) { case c1: statements1 break; case c2: statements2 break;... more case clauses... default: statements break; } Useful when program must choose among several cases.

66 Good programming practice Although a break is not necessary for each case, it is advised to include a break at the end of each case. Although a default clause is optional, it is advised to include a default clause unless you are absolutely sure that you have covered all the cases (using a table).

67 Example public void run() { println(“This program shows the number of days in a month.”); int month = readInt(“Enter numeric month (Jan = 1): “); switch (month) { case 2: println(“28 days (29 in leap years)”); break; case 4: case 6: case: 9 case 11: println(“30 days”); break; case 1: case 3: case 5: case 7: case 8: case 10: case 12: println(“31 days”); break; default: println(“Illegal month number”); break; } Tracing the program.

68 The while statement while (condition) { statements } The conditional test is performed only at the beginning of a loop cycle. If the condition happens to become false at some point in the middle of the loop, the program doesn’t notice the fact until it has executed a complete cycle. At that point, the program evaluates the test condition again. If it is still false, the loop terminates. If you must quit loop inside a cycle, use break. See later.

69 Example: DigitSum Pseudo code: public void run() { println(“This program sums the digits in an integer.”); int n = readInt(“Enter a positive integer: “); int dsum = 0; for each digit in the number, add that digit to dsum; println(“The sum of the digits is “ + dsum + “.”); }

70 Find digits in an integer 1729 % 10 = 9 1729 / 10 = 172... 1 % 10 = 1 1 / 10 = 0 /* for each digit in the number, add that digit to dsum */ while (n > 0) { dsum += n % 10; n /= 10; }

71 public void run() { println(“This program sums the digits in an integer.”); int n = readInt(“Enter a positive integer: “); int dsum = 0; while (n > 0) { dsum += (n % 10); n = n /10; } println(“The sum of the digits is “ + dsum + “.”); } Trace the program.

72 Tracing the program int n = readInt(“Enter a positive integer: “); int dsum = 0; while (n > 0) { dsum += (n % 10); n = n /10; } println(“The sum of the digits is “ + dsum + “.”); n (1729) dsum ( )

73 Tracing the program int n = readInt(“Enter a positive integer: “); int dsum = 0; while (n > 0) { dsum += (n % 10); n = n /10; } println(“The sum of the digits is “ + dsum + “.”); n (1729) dsum (0)

74 Tracing the program int n = readInt(“Enter a positive integer: “); int dsum = 0; while (n > 0) { dsum += (n % 10); n = n /10; } println(“The sum of the digits is “ + dsum + “.”); n (1729) dsum (0)

75 Tracing the program int n = readInt(“Enter a positive integer: “); int dsum = 0; while (n > 0) { dsum += (n % 10); n = n /10; } println(“The sum of the digits is “ + dsum + “.”); n (1729) dsum (9)

76 Tracing the program int n = readInt(“Enter a positive integer: “); int dsum = 0; while (n > 0) { dsum += (n % 10); n /= 10; } println(“The sum of the digits is “ + dsum + “.”); n (172) dsum (9)

77 Tracing the program int n = readInt(“Enter a positive integer: “); int dsum = 0; while (n > 0) { dsum += (n % 10); n /= 10; } println(“The sum of the digits is “ + dsum + “.”); n (172) dsum (9)

78 Tracing the program int n = readInt(“Enter a positive integer: “); int dsum = 0; while (n > 0) { dsum += (n % 10); n /= 10; } println(“The sum of the digits is “ + dsum + “.”); n (172) dsum (11)

79 Tracing the program int n = readInt(“Enter a positive integer: “); int dsum = 0; while (n > 0) { dsum += (n % 10); n /= 10; } println(“The sum of the digits is “ + dsum + “.”); n (17) dsum (11)

80 Tracing the program int n = readInt(“Enter a positive integer: “); int dsum = 0; while (n > 0) { dsum += (n % 10); n /= 10; } println(“The sum of the digits is “ + dsum + “.”); n (17) dsum (11)

81 Tracing the program int n = readInt(“Enter a positive integer: “); int dsum = 0; while (n > 0) { dsum += (n % 10); n /= 10; } println(“The sum of the digits is “ + dsum + “.”); n (17) dsum (18)

82 Tracing the program int n = readInt(“Enter a positive integer: “); int dsum = 0; while (n > 0) { dsum += (n % 10); n /= 10; } println(“The sum of the digits is “ + dsum + “.”); n (1) dsum (18)

83 Tracing the program int n = readInt(“Enter a positive integer: “); int dsum = 0; while (n > 0) { dsum += (n % 10); n /= 10; } println(“The sum of the digits is “ + dsum + “.”); n (1) dsum (18)

84 Tracing the program int n = readInt(“Enter a positive integer: “); int dsum = 0; while (n > 0) { dsum += (n % 10); n /= 10; } println(“The sum of the digits is “ + dsum + “.”); n (1) dsum (19)

85 Tracing the program int n = readInt(“Enter a positive integer: “); int dsum = 0; while (n > 0) { dsum += (n % 10); n /= 10; } println(“The sum of the digits is “ + dsum + “.”); n (0) dsum (19)

86 Tracing the program int n = readInt(“Enter a positive integer: “); int dsum = 0; while (n > 0) { dsum += (n % 10); n /= 10; } println(“The sum of the digits is “ + dsum + “.”); n (0) dsum (19)

87 Tracing the program int n = readInt(“Enter a positive integer: “); int dsum = 0; while (n > 0) { dsum += (n % 10); n /= 10; } println(“The sum of the digits is “ + dsum + “.”); n (0) dsum (19)

88 Loop terminationg When you use a while loop in a program, it is important to make sure the loop eventually terminates. while (n >= 0) { dsum += n % 10; n /= 10; } Infinite loop! Find out the command sequence on your computer which stops an infinite loop.

89 The loop-and-half patterns while (true) { prompt user and read in a value if (value == sentinel) break; process the data value } or the sentinel-based loop Prompt user and read in a value while (value != sentinel) { process the data value prompt user and read in a value }

90 Two drawbacks of the sentinel-based loop: 1.The order of the operations in the loop in unnatural, hard to follow. (Process the data value, then read in a new value.) 2.Duplication of code presents a serious maintenance problem. Subsequent edits to one copy might not be made in the other.

91 The for statement for (init; test; step) { statements } Example: countdown Int START = 10; for (int t = START; t >= 0; t--) { println(t); } println(“Liftoff!”);

92 The expressions init, test, and step are each optional, but semicolons must appear. If init is missing, no initialization is performed; If test is missing, it is assumed to be true; If step is missing, no action occurs between loop cycles. for ( ; ;)is equivalent towhile (true)

93 Effect of each of the following for statements for (int i = 0; i < N; i++) i: 0, 1, 2, …, N-1 for (int i = 1; i <= 10; i++) i: 1, 2, …, 10 for (int n = 99; i >= 1; n -= 2) n: 99, 97, …, 3, 1 for (int x = 1; x <= 1024; x *= 2) x: 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024

94 Simple graphic animation Moving a square diagonally. /* File: AnimatedSquare.java * ------------------------------------ * This program animates a square so that it moves from the * upper left corner of the window to the lower right corner. */ import acm.graphics.*; import acm.program.*;

95 public class AnimatedSquare extends GraphicsProgram { public void run() { GRect square = new Grect(0,0,SQUARE_SIZE, SQUARE_SIZE); square.setFilled(true); add(square); double dx = (double) (getWidth() – SQUARE_SIZE) / N_STEPS; double dy = (double) (getHeight() – SQUARE_SIZE) / N_STEPS; for (int i = 0; i < N_STEPS; i++) { square.move(dx, dy); pause(PAUSE_TIME); } /* private constants */ private static final int N_STEPS = 1000; private static final int PAUSE_TIME = 20; private static final int SQUARE_SIZE = 50; }

96 forvswhile for (init; test; step) { statements } is equivalent to Init; while (test) { statements step; } Prefer for over while, when you have choice.

97 Nested for statements 2D applications. Example: Checkerboard /* * File: Checkerboard.java * -------------------------------- * This program draws a checkerboard. The dimensions of * checkerboard are specified by the constants N_ROWS and * N_COLIMNS, and the size of the square is chosen so that the * checkerboard fills the available vertical space. */ import acm.graphics.*; import acm.program.*;

98 public class Checkerboard extends GraphicsProgram { public void run() { double sqSize = (double) getHeight() / N_ROWS; for (int i = 0; i < N_ROWS; i++) { for (int j = 0; j < N_COLUMNS; j++) { double x = j * sqSize; double y = i * sqSize; GRect sq = new GRect(x, y, sqSize, sqSize); sq.setFilled(((i + j) % 2) != 0); add(sq); } /* for j */ } /* for i */ /* private constants */ private static final int N_ROWS = 8; private static final int N_COLUMNS = 8; }

99 Using for with floating-point data double h = 0.1; for (double x = 1.0; x <= 2.0; x += h) { println(x); } Output: 1.0 1.1 1.2000000000000002... 1.9000000000000008

100 Why? Decimal 0.1 cannot be exactly represented in binary. During the assignment h = 0.1, decimal 0.1 is rounded to it closest double floating-point, which is slightly larger than 0.1. Caution: more rounding errors occur during addition. for (double x = 0.0; x <= 0.5; x += h) { println(x); } The final value of x is 0.5 exact.


Download ppt "Chapter 4 Statement Forms. Statement types 1.Simple statements expression; println(“The total is “ + total + “.”); (method call) 2. Compound statements."

Similar presentations


Ads by Google