Computer Programming with Java

Slides:



Advertisements
Similar presentations
Flow of Control Chapter 3.
Advertisements

Topic 03 Control Statements Programming II/A CMC2522 / CIM2561 Bavy Li.
Lecture 6 Flow of Control: Branching Statements COMP1681 / SE15 Introduction to Programming.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
Lecture 7 Flow of Control: Branching Statements COMP1681 / SE15 Introduction to Programming.
Loops –For For Reading for this Lecture, L&L, Part of 5.8.
Loop Statements (Iteration). Iteration  A portion of a program that repeats a statement or group of statements is called a loop.  Each repetition of.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Branch Statements (Decision). Flow of Control  The order in which a program performs actions.  A branching statement chooses one of two or more possible.
Flow of Control Loops – Chapter 3.2. Java Loop Statements: Outline the while Statement the do-while Statement the for Statement.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
Flow of Control Chapter 3.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
1 Week 6 Branching. 2 What is “Flow of Control”? l Flow of Control is the execution order of instructions in a program l All programs can be written with.
Flow of Control Chapter 3 Flow of control Branching Loops
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Chapter 4: Control Structures II
COMP Flow of Control: Branching 1 Yi Hong May 19, 2015.
Flow of Control Chapter 3. Outline Branching Statements Java Loop Statements Programming with Loops The Type boolean.
Chapter 3 1 l Branching l Loops l exit(n) method l Boolean data type and logic expressions Flow of Control – Part 1.
Control Flow Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
COMP Loop Statements Yi Hong May 21, 2015.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Catie Welsh February 9,  Friday - No Lab! ◦ Bring questions on Project 2  Lab 3 due on Friday 2.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Structured Programming Structured Programming is writing a program in terms of only 3 basic control structures: sequence selection repetition We have already.
Chapter 7 Control Structures. Java has very flexible three looping mechanisms. You can use one of the following three loops:  while Loop  do...while.
Chapter 3Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 3 l Branching l Loops l exit(n) method l Boolean data type.
Chapter 3Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 3 l Branching l Loops l exit(n) method l Boolean data type.
Chapter 4: Control Structures I
Chapter 4 Repetition Statements (loops)
The switch Statement, and Introduction to Looping
Chapter 3 Edited by JJ Shepherd
Flow of Control.
Chapter 3 Branching Statements
Chapter 5: Control Structures II
Branching Loops exit(n) method Boolean data type and expressions
The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression,
SELECTION STATEMENTS (1)
Loops CS140: Introduction to Computing 1 Savitch Chapter 4 Flow of Control: Loops 9/18/13 9/23/13.
Flow of Control Chapter 3 Chapter 3.
Chapter 6 More Conditionals and Loops
Outline Altering flow of control Boolean expressions
In this class, we will cover:
Java Language Basics.
Flow of Control Chapter 3.
Control Statements Loops.
Chapter 6 Control Statements: Part 2
Lecture Notes – Week 4 Chapter 5 (Loops).
Control Structure Chapter 3.
Lecture Notes – Week 2 Lecture-2
PROGRAM FLOWCHART Selection Statements.
Flow of Control Chapter 3.
In this class, we will cover:
Control Statements Loops.
Repetition Statements
Java LESSON 3 Loops.
Additional control structures
Chap 7. Advanced Control Statements in Java
Announcements/Reminders
Control Structure.
Flow of Control Flow of control is the order in which a program performs actions. Up to this point, the order has been sequential. A branching statement.
Selection Statements August 22, 2019 ICS102: The course.
Presentation transcript:

Computer Programming with Java Chapter 3 Flow of Control

Contents Overview Branching Statements Loop Statements Programming with Loops

Overview Flow of control the order in which actions are performed by your program. Branching statements choose one action from a list of two or more possible actions Loop statements repeats some action again and again until some stopping condition is met

Branching Statements The if-else- statement if (Boolean_Expression) If the Boolean_Expression is true, then Statement_1 is executed; otherwise, Statement_2 is executed.

public class BankBalance { public static final double OVER_DRAWN_PENALTY = 8.00; public static final double INTEREST_RATE = 0.02;//2% annually public static void main(String[] args) double balance; System.out.print("Enter your checking account balance: $"); balance = SavitchIn.readLineDouble(); System.out.println("Original balance $" + balance); if (balance >= 0) balance = balance + (INTEREST_RATE * balance)/12; else balance = balance - OVER_DRAWN_PENALTY; System.out.println("After adjusting for one month"); System.out.println("of interest and penalties,"); System.out.println("your new balance is $" + balance); } Display 3.1: A Program using if-else

Branching Statements (1) Comparison Operators

public class StringEqualityDemo{ public static void main(String[] args){ String s1, s2; System.out.println("Enter two lines of text:"); s1 = SavitchIn.readLine(); s2 = SavitchIn.readLine(); if (s1.equals(s2)) System.out.println("The two lines are equal."); else System.out.println("The two lines are not equal."); if (s2.equals(s1)) if (s1.equalsIgnoreCase(s2)) System.out.println("But, the lines are equal ignoring case."); System.out.println("Lines are not equal even ignoring case."); } Display 3.3: Testing Strings for Equality

Branching Statements (2) Boolean Expression an expression that is either true or false. “and”: && When you form a larger boolean expression by connecting two smaller expression with &&, the entire larger expression is true provided that both of the smaller expressions are true. (sub_expression1) && (sub_expression2) e.g.) if ((pressure > min) && (pressure < max)) System.out.println(“Pressure is OK.”); else System.out.println(“Warning: Pressure is out of range.”);

Branching Statements (3) “or” the meaning is essentially the same as the word “or” (sub_expression1) || (sub_expression2) e.g.) if ((salary > expenses) || (savings > expenses)) System.out.println(“Solvent.”); else System.out.println(“Bankrupt.”);

&& (and) || (or) ! (not) Display 3.12: Truth tables for boolean operators

Branching Statements (4) Nested statements an if-else statement contains two smaller statements within it. Compound statements these statements formed by enclosing a list of statements within curly brackets. Rule of thumb To eliminate some confusion in the nested if-else statements, you had better use curly brackets to group things.

Nested statements if (balance >= 0) if (INTEREST_RATE >= 0) balance = balance + (INTEREST_RATE * balance)/12; else System.out.println(“Cannot have a negative interest.”); balance = balance - OVER_DRAWN_PENALTY; Compound statements if(balance >= 0){ System.out.println(“Good for you. You earned interest.”); balance = balance + (INTEREST_RATE * balance) /12; }else{ System.out.println(“You will be charged a penalty.”); }

Branching Statements (4) Multibranch if-else statements you can use nested if-else statements to produce multiway branches that branch into any number of possibilities. If ( Boolean_Expression1) Action1 else if ( Boolean_Expression2) Action2 … else if ( Boolean_Expression n) Action n else Default_Action if (balance >= 0) System.out.println(“Positive balance.”); else if (balance < 0) System.out.println(“Negative balance.”); else if (balance == 0) System.out.println(“Zero balance.”);

public class Grader{ public static void main(String[] args){ int score; char grade; System.out.println("Enter your score: "); score = SavitchIn.readLineInt(); if (score >= 90) grade = 'A'; else if (score >= 80) grade = 'B'; else if (score >= 70) grade = 'C'; else if (score >= 60) grade = 'D'; else grade = 'F'; System.out.println("Score = " + score); System.out.println("Grade = " + grade); } Display 3.4: Multibranch if-else-Statement

Branching Statements (5) The switch statement a multiway branch that makes its decision on which way to branch based on the value of an integer or character expression switch (Controlling_Expression){ case Case_Label: statement; … break; … default: }

public class MultipleBirths{ public static void main(String[] args){ int numberOfBabies; System.out.print("Enter number of babies: "); numberOfBabies = SavitchIn.readLineInt(); switch (numberOfBabies){ case 1: System.out.println("Congratulations."); break; case 2: System.out.println("Wow. Twins."); break; case 3: System.out.println("Wow. Triplets."); break; case 4: case 5: System.out.println("Unbelieveable."); System.out.println(numberOfBabies + " babies"); break; default: System.out.println("I don't believe you."); break; } Display 3.5: A switch-Statement

Loop Statements Program often need to repeat some action. Terminology loop: A portion of a program that repeats a statement or group of statements body: the statement (or group of statements) to be repeated in a loop iteration: each repetition of the loop body infinite loop: A loop that iterates its body repeatedly without ever ending see text p116.

General structure of a Loop initializing statements loop body mechanism for ending the loop Rule of thumb When you design a loop, you need to determine what action the body of the loop will take and you need to determine a mechanism for deciding when the loop should stop repeating the loop body. How do you decide whether to use one of loop statements? See text p 124: Choosing a Loop statement

Loop Statements (1) while statements repeats its action again and again until a controlling boolean expression becomes false. Note that the body of a while-loop can be executed zero times. while(Boolean_Controlling_Expression){ Body } The Body may be either a simple statement or more likely, a compound statement consisting of a list of statements enclosed in curly brackets {}.

public class WhileDemo { public static void main(String[] args) int count, number; System.out.println("Enter a number"); number = SavitchIn.readLineInt(); count = 1; while (count <= number) System.out.print(count + ", "); count++; } System.out.println(); System.out.println("Buckle my shoe."); Display 3.6: A while-Loop

Loop Statements (2) do-while statement very similar to the while-statement, but the loop body of do-while statement is always executed at least once. do { Body }while(Boolean_Controlling_Expression); The Body may be either a simple statement or more likely, a compound statement consisting of a list of statements enclosed in curly brackets {}.

public class DoWhileDemo { public static void main(String[] args) int count, number; System.out.println("Enter a number"); number = SavitchIn.readLineInt(); count = 1; do System.out.print(count + ", "); count++; }while (count <= number); System.out.println(); System.out.println("Buckle my shoe."); } Display 3.7: A do-while-Loop

Display 3.8: Roach Population Program public class BugTrouble{ public static final double GROWTH_RATE = 0.95;//95% per week public static final double ONE_BUG_VOLUME = 0.002;//cubic feet public static void main(String[] args){ System.out.println("Enter the total volume of your house"); System.out.print("in cubic feet: "); double houseVolume = SavitchIn.readLineDouble(); System.out.println("Enter the estimated number of"); System.out.print("roaches in your house:"); int startPopulation = SavitchIn.readLineInt(); int countWeeks = 0; double population = startPopulation; double totalBugVolume = population*ONE_BUG_VOLUME; while (totalBugVolume < houseVolume){ population = population + (GROWTH_RATE*population); totalBugVolume = population*ONE_BUG_VOLUME; countWeeks++; } Display 3.8: Roach Population Program

System.out.println("Starting with a roach population of ” + startPopulation); System.out.println("and a house with a volume of " + houseVolume + " cubic feet,"); System.out.println("after " + countWeeks + " weeks,"); System.out.println("the house will be filled"); System.out.println("floor to ceiling with roaches."); System.out.println("There will be " + (int)population + " roaches."); System.out.println("They will fill a volume of " + (int)totalBugVolume + " cubic feet"); System.out.println("Better call Debugging Experts Inc."); }

Loop Statements (3) for-statement a specialized loop statement that allows you to easily convert pseudocode (see text p. 129) for(Initializing_Action; Boolean_Expression; Action_After_Each_Iteration){ Body } The Body may be either a simple statement or more likely, a compound statement consisting of a list of statements enclosed in curly brackets Do the following for each value of count from 1 to 3: System.out.println(count); System.out.println(“Go”);

public static void main(String[] args) public class ForDemo { public static void main(String[] args) int countDown; for (countDown = 3; countDown >= 0; countDown--) System.out.println(countDown); System.out.println("and counting."); } System.out.println("Blast off!"); Display 3.9: A for-statement

Loop Statements (4) break-statement exit Method if you want to end a loop in the middle of the loop body exit Method an invocation of the exit method ends the program. 0: a normal termination 1: abnormal termination e.g.) System.exit(0);

public class BreakDemo{ public static void main(String[] args) { int itemNumber; double amount, total; System.out.println("You may buy ten items, but"); System.out.println("the total price must not exceed $100."); total = 0; for (itemNumber = 1; itemNumber <= 10; itemNumber++) { System.out.print("Enter cost of item #" + itemNumber + ": $"); amount = SavitchIn.readLineDouble(); total = total + amount; if (total >= 100) { System.out.println("You spent all your money."); break; } System.out.println("Your total so far is $" + total); System.out.println("You may purchase up to "+ (10 - itemNumber) + "more items."); System.out.println("You spent $" + total); Display 3.10: Ending a loop with a break-statement