Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 4: Program Control Flow

Similar presentations


Presentation on theme: "Lecture 4: Program Control Flow"— Presentation transcript:

1 Lecture 4: Program Control Flow
Dr. Kyung Eun Park Summer 2017

2 Default Control Flow: Top to Bottom
Flow Chart start statement 1 statement 2 statement 3 end

3 Method Invocation From main(), call method1(), return from the method and continue … start main() { int num; num = 10; method1(); System.out } method1 { } method2 { } end

4 Conditional Execution : if Statement
if Conditional Statement start start main() { int num; if (num>50) { } statements test test Yes redrawn num>50 Yes_statements Yes_statements … statements end end

5 The if Statement Executes a block of statements only if a test is true
if (test) { statement; ... } Example: double gpa = console.nextDouble(); if (gpa >= 2.0) { System.out.println("Application accepted.");

6 The if-else Statement Executes one block if a test is true, another if false if (test) { statement(s); } else { } Example: double gpa = console.nextDouble(); if (gpa >= 2.0) { System.out.println("Welcome to Mars University!"); System.out.println("Application denied.");

7 Conditional Execution: if-else Statement
start if-else Conditional Statement start statements test main() { int num; if (num>50) { } else { } No Yes num>50 test Yes_statements … redrawn No_statements Yes_statements No_statements … statements end end

8 Nested if-else Statement
Chooses between outcomes using many tests if (test1) { statement1; } else if (test2) { statement2; } else { statement3; } Example: if (x > 0) { System.out.println("Positive"); } else if (x < 0) { System.out.println("Negative"); System.out.println("Zero");

9 Nested if-else-if Statement
If it ends with else, exactly one path must be taken. If it ends with if, the code might not execute any path. if (test1) { statement1; } else if (test2) { statement2; } else if (test3) { statement3; } Example: if (place == 1) { System.out.println("Gold medal!"); } else if (place == 2) { System.out.println("Silver medal!"); } else if (place == 3) { System.out.println("Bronze medal.");

10 Program I – if-else, return statement
Write a method quadrant that accepts a pair of real numbers x and y and returns the quadrant for that point: Example: quadrant(-4.2, 17.3) returns 2 If the point falls directly on either axis, return 0 y+ quadrant 2 quadrant 1 x- x+ quadrant 3 quadrant 4 y-

11 Program I – if-else, return statement
quadrant method public static int quadrant(double x, double y) { if (x > 0 && y > 0) { return 1; } else if (x < 0 && y > 0) { return 2; } else if (x < 0 && y < 0) { return 3; } else if (x > 0 && y < 0) { return 4; } else { // at least one coordinate equals 0 return 0; }

12 Boolean Expressions Tests use relational operators:
if statements and for loops both use logical tests. if (i <= 10) { ... for (int i = 1; i <= 10; i++) { ... These are boolean expressions Tests use relational operators: Operator Meaning Example Value == equals 1 + 1 == 2 true != does not equal 3.2 != 2.5 < less than 10 < 5 false > greater than 10 > 5 <= less than or equal to 126 <= 100 >= greater than or equal to 5.0 >= 5.0 Note that == tests equality, not = . The = is used for the assignment operator!

13 Logical Operators Tests can be combined using logical operators:
"Truth tables" for each, used with logical values p and q: Operator Description Example Result && and (2 == 3) && (-1 < 5) false || or (2 == 3) || (-1 < 5) true ! not !(2 == 3) p q p && q p || q true false p !p true false

14 Evaluating Logic (Boolean) Expressions
Relational operators have lower precedence than math. 5 * 7 >= * (7 - 1) 5 * 7 >= * 6 35 >= 35 >= 33 true Relational operators cannot be "chained" as in algebra. 2 <= x <= 10 true <= (assume that x is 15) error! Instead, combine multiple tests with && or || 2 <= x && x <= 10 true && false false

15 Logical Questions What is the result of each of the following expressions? int x = 42; int y = 17; int z = 25; y < x && y <= z x % 2 == y % 2 || x % 2 == z % 2 x <= y + z && x >= y + z !(x < y && x < z) (x + y) % 2 == 0 || !((z - y) % 2 == 0) Answers: true, false, true, true, false

16 Repetition with for Loops
We don’t like repetition, but computer does well. System.out.println("Homer says:"); System.out.println("I am so smart"); System.out.println("S-M-R-T... I mean S-M-A-R-T"); Keeping repeating statements is not efficient!!!  Loop Structure for (int i = 1; i <= 4; i++) { // repeat 4 times }

17 for loop syntax for (initialization; test; update) { statement; ... }
Perform initialization once. Repeat the following: Check if the test is true. If not, stop. Execute the statements. Perform the update loop body loop header

18 Initialization Tells Java what variable to use in the loop
for (int i = 1; i <= 6; i++) { System.out.println("I am so smart"); } Tells Java what variable to use in the loop Performed once as the loop begins The variable, i is called a loop counter can use any name, not just i can start at any value, not just 1 visible only within the for loop : Variable scope

19 Test Tests the loop counter variable against a limit
for (int i = 1; i <= 6; i++) { System.out.println("I am so smart"); } Tests the loop counter variable against a limit Uses comparison operators: < less than <= less than or equal to > greater than >= greater than or equal to

20 Update: Increment and Decrement
shortcuts to increase or decrease a variable's value by 1 Shorthand Equivalent longer version variable++; variable = variable + 1; variable--; variable = variable - 1; int x = 2; x++; // x = x + 1; // x now stores 3 double gpa = 2.5; gpa--; // gpa = gpa - 1; // gpa now stores 1.5

21 Modify-and-Assign shortcuts to modify a variable's value
Shorthand Equivalent longer version variable += value; variable = variable + value; variable -= value; variable = variable - value; variable *= value; variable = variable * value; variable /= value; variable = variable / value; variable %= value; variable = variable % value; x += 3; // x = x + 3; gpa -= 0.5; // gpa = gpa - 0.5; number *= 2; // number = number * 2;

22 Repetition over a Range
System.out.println("1 squared = " + 1 * 1); System.out.println("2 squared = " + 2 * 2); System.out.println("3 squared = " + 3 * 3); System.out.println("4 squared = " + 4 * 4); System.out.println("5 squared = " + 5 * 5); System.out.println("6 squared = " + 6 * 6); Intuition: "I want to print a line for each number from 1 to 6“  The for loop does exactly that!  "For each integer i from 1 through 6, print ...“ for (int i = 1; i <= 6; i++) { System.out.println(i + " squared = " + (i * i)); }

23 Loop Walkthrough Output: for (int i = 1; i <= 4; i++) {
2 4 for (int i = 1; i <= 4; i++) { System.out.println(i + " squared = " + (i * i)); } System.out.println("Whoo!"); Output: 1 squared = 1 2 squared = 4 3 squared = 9 4 squared = 16 Whoo! 3 5 1 2 3 4 5

24 Multi-line Loop Body Output: System.out.println("+----+");
for (int i = 1; i <= 3; i++) { System.out.println("\\ /"); System.out.println("/ \\"); } Output: +----+ \ / / \

25 Degree Conversion: Celsius to Fahrenheit
int highTemp = 5; for (int i = -3; i <= highTemp / 2; i++) { System.out.println(i * ); } Output:

26 Cumulative Algorithms
Find the sum of all integers from : // This may require a lot of typing int sum = ; System.out.println("The sum is " + sum); What if we want the sum from 1 - 1,000,000? Or the sum up to any maximum?  How can we generalize the above code?

27 Cumulative Sum Loop cumulative sum: A variable that keeps a sum in progress and is updated repeatedly until summing is finished. Cumulative sum variable, sum must be declared outside the loop that updates it, so that it will still exist after the loop. int sum = 0; for (int i = 1; i <= 1000; i++) { sum = sum + i; } System.out.println("The sum is " + sum);

28 Homework I – Cumulative Product
Write a method cumProduct that accepts a positive number and returns the cumulative product up to the number starting from 1. Example: cumProduct(10) returns If the number in negative, please make it positive and continue…

29 Homework II – File and Cumulative Sum
Write a program which generates the grade statistics including the average grade, the highest, and the lowest grade with the names of student. Given data (student.txt) 10 Kim Eric 86 Stef 79 Joe 50 Lauren John Emily 89 Grace Tim Amy 87 Output (grade.txt) /*Statistics from student data */ Avg. Grade = 83.9 Max. Grade = 98 (Lauren) Min. Grade = 50 (Joe)


Download ppt "Lecture 4: Program Control Flow"

Similar presentations


Ads by Google