5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus.

Slides:



Advertisements
Similar presentations
5/17/ Programming Constructs... There are several types of programming constructs in JAVA. - If-else construct or ternary operator - while - do-while.
Advertisements

1 Chapter 3: Program Statements Lian Yu Department of Computer Science and Engineering Arizona State University Tempe, AZ
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Chapter 4 - Control Structures: Part 1 Outline 4.4Control Structures 4.5The if Selection Structure 4.6The if/else Selection Structure 4.7The while Repetition.
Flow of Control (1) : Logic Clark Savage Turner, J.D., Ph.D. Some lecture slides have been adapted from those developed.
Introduction to Computer Programming Decisions If/Else Booleans.
COMP 14 Introduction to Programming Miguel A. Otaduy May 18, 2004.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Aalborg Media Lab 23-Jun-15 Software Design Lecture 6 “Conditionals and Loops”
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Logical Operators and Conditional statements
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/33 Conditionals and Loops Now we will examine programming statements.
CSC 1051 M.A. Papalaskari, Villanova University Repetition CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing.
Chapter 3: Program Statements
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
Chapter 3: Program Statements
Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing.
1 Data Comparisons and Switch Data Comparisons Switch Reading for this class: L&L 5.3,
© 2004 Pearson Addison-Wesley. All rights reserved February 17, 2006 The ‘while’ Statement ComS 207: Programming I (in Java) Iowa State University, SPRING.
© 2004 Pearson Addison-Wesley. All rights reserved February 20, 2006 ‘do’ and ‘for’ loops ComS 207: Programming I (in Java) Iowa State University, SPRING.
Decision II. CSCE 1062 Outline  Boolean expressions  switch statement (section 4.8)
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Chapter 5 Loops.
Flow of Control Part 1: Selection
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus.
Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSE 1301 Lecture 8 Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Chapter 4: Control Structures II
Chapter 6. else-if & switch Copyright © 2012 Pearson Education, Inc.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 The switch Statement The switch statement provides another way.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/29 The switch Statement The switch statement provides another way.
Topics Logical Operators (Chapter 5) Comparing Data (Chapter 5) The conditional operator The switch Statement The for loop Nested Loops.
Chapter 5 Conditionals and Loops 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights.
Control Flow. Data Conversion Promotion happens automatically when operators in expressions convert their operands For example, if sum is a float and.
Flow of Control Unless indicated otherwise, the order of statement execution through a method is linear: one after the other in the order they are written.
ICT Introduction to Programming Chapter 4 – Control Structures I.
Control statements Mostafa Abdallah
1 Program Development  The creation of software involves four basic activities: establishing the requirements creating a design implementing the code.
Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
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.
Programming in Java (COP 2250) Lecture 12 & 13 Chengyong Yang Fall, 2005.
Design A software design specifies how a program will accomplish its requirements A design includes one or more algorithms to accomplish its goal.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 6 More Conditionals and Loops
The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression,
Chapter 6 More Conditionals and Loops
Outline Altering flow of control Boolean expressions
The ‘while’ Statement September 27, 2006
Chapter 3: Program Statements
Repetition Statements
Conditionals and Loops
‘do’ and ‘for’ loops October 1, 2007 ComS 207: Programming I (in Java)
‘do’ and ‘for’ loops October 2, 2006 ComS 207: Programming I (in Java)
Repetition CSC 1051 – Data Structures and Algorithms I Course website:
3.0 - Design A software design specifies how a program will accomplish its requirements A design includes one or more algorithms to accomplish its goal.
Presentation transcript:

5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Topics The if Statement and Conditions Other Conditional Statements Comparing Data The while Statement Iterators Other Repetition Statements Decisions and Graphics More Components

Program Control Structures The program executes each statement one after another, unless otherwise directed explicitly. The program executes each statement one after another, unless otherwise directed explicitly. Order of execution statement is called “flow of control.” Order of execution statement is called “flow of control.” A program needs only three control structures: A program needs only three control structures: Sequence (default) Sequence (default) Conditional (decision) Conditional (decision) Iteration (loop) Iteration (loop)

Conditional Statements Conditional statement lets you choose which statement to execute next, depending of a boolean condition. Conditional statement lets you choose which statement to execute next, depending of a boolean condition. Conditional Statements Conditional Statements if statement if statement if-else statement if-else statement switch statement switch statement

If Statement if (boolCondition) someStatement; if (boolCondition) someStatement; if (boolCondition) { someStatement1; someStatement2; } if (boolCondition) { someStatement1; someStatement2; } bool Condition someStatement true false

If Statement final int VOTE_AGE = 18; int age; Scanner scan = new Scanner(System.in); System.out.println(“How old are you?”); age = scan.nextInt(); If (age >= VOTE_AGE) { System.out.println(“Since you are over “ + VOTE_AGE + “,\nyou can vote.”); }

Relational Operations A condition often uses one of Java's equality operators or relational operators, which all return boolean results : A condition often uses one of Java's equality operators or relational operators, which all return boolean results : equal to ==equal to not equal to !=not equal to less than <less than greater than >greater than less than or equal to <=less than or equal to greater than or equal to >=greater than or equal to Note the difference between the equality operator (==) and the assignment operator (=) Note the difference between the equality operator (==) and the assignment operator (=)

Logical Operators If (5 > 3 && 8 3 && 8 <= 8) System.out.println(“Hi.”); Is (5 > 3 && 8 3 && 8 <= 8) true, or false? Logical operators take boolean expressions Logical operators take boolean expressions ! Logical NOT ! Logical NOT && Logical AND && Logical AND || Logical OR || Logical OR

Logical Operators int num; Scanner scan = new Scanner(System.in); System.out.println(“Enter a 2-digit number“); num = scan.nextInt(); if ((num >= 10) && (num < 100)) { System.out.println(“Thnak you.”); }

Your Turn Given: int a = 1; int b = 2; int c = 3; int d = 4; Given: int a = 1; int b = 2; int c = 3; int d = 4; True or False? True or False? 1.a d 2.a d 3.a a + b 4.!(c < d)

Truth Table AB!A A && B A || B TTFTT TFFFT FTTFT FFTFF

Boolean Expressions a > b found!found a > b && !found TT?? TF?? FT?? FF??

Short-circuited Operator If ((a > b) && (c b) && (c < d)) If (a > b) is false, then the whole espression is false. Thus, Java does not evaluate (c b) is false, then the whole espression is false. Thus, Java does not evaluate (c < d). If ((a > b) || (c b) || (c < d)) If (a > b) is true, then the whole expressions is true. Thus, Java does not evaluate (c b) is true, then the whole expressions is true. Thus, Java does not evaluate (c < d).

Topics The if Statement and Conditions Other Conditional Statements Comparing Data The while Statement Iterators Other Repetition Statements Decisions and Graphics More Components

If-Else Statement if (boolCondition) someStatement; else anotherStatement; if (boolCondition) someStatement; else anotherStatement; if (boolCondition) { someStatement1; someStatement2; } else { anotherStatement1; anotherStatement2; } if (boolCondition) { someStatement1; someStatement2; } else { anotherStatement1; anotherStatement2; } condition evaluated statement1 true false statement2

if –else Statements if (number > 0) System.out.println(number + " is positive.”); else System.out.println(number + " is non-pos.”); if (score >= 70) { grade = "Pass"; System.out.println("You passed the test."); } else { grade = "Fail"; System.out.println("You did not pass “ + “the test.”); }

Example Program CoinFlip.java CoinFlip.java CoinFlip.java Coin.java Coin.java Coin.java

Unmatched Else What is the output from the following example? What is the output from the following example? x = 5; if (x 0) System.out.print("Hi"); else System.out.print("Ho");

Answer Output: none Output: none An else is matched with the nearest if. An else is matched with the nearest if. Same as: Same as: x = 5; if (x 0) System.out.print("Hi"); else System.out.print("Ho");

Q & A Q: How do you associate a nested else with a particular if? Q: How do you associate a nested else with a particular if? A: A: x = 5; if (x 0) System.out.print("Hi"); } else { System.out.print("Ho"); }

Nested if Statement char grade; int score; 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’;

Nested If >= 90 score  input >= 80 >= 70 >= 60 grade = ‘A Grade = ‘F’ grade = ‘B’ grade = ‘C’ Grade = ‘D’ T T F F F F T T T

Equivalent if-else-if char grade; int score; 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’;

If-else-if >= 90 score  input >= 80 >= 70 >= 60 grade = ‘A Grade = ‘F’ grade = ‘B’ grade = ‘C’ Grade = ‘D’ T T F F F T T T F

Exercises Write a code segment which converts a letter grade into an equivalent numeric grade. I.e., A  4, B  3, C  2, D  1, F  0. Write a code segment which converts a letter grade into an equivalent numeric grade. I.e., A  4, B  3, C  2, D  1, F  0.

switch Statement Use switch statement when: Use switch statement when: Test condition involves matching with several cases Test condition involves matching with several cases Each value matched is an integer value—i.e., byte, short, int, or char (not String) Each value matched is an integer value—i.e., byte, short, int, or char (not String) Note that the switch statement cannot be used to convert a range of numeric scores to letter grades, e.g.,  A,  B, etc. Why? Note that the switch statement cannot be used to convert a range of numeric scores to letter grades, e.g.,  A,  B, etc. Why?

switch Statement: Example char grade; int score; … switch (grade){ case 'A': score = 4; break; case 'B': score = 3; break; case 'C': score = 2; break; case 'D': score = 1; break; default: score = 0; }

Your Turn Use a switch statement to count the number of vowels in a statement. Use a switch statement to count the number of vowels in a statement.

Solution String state  input String state  input int a = 0; e = 0; I = 0; o = 0; u = 0 int a = 0; e = 0; I = 0; o = 0; u = 0 for (int I = 0; I < state.lenght(); i++) ch + state.chartAt(i) for (int I = 0; I < state.lenght(); i++) ch + state.chartAt(i) switch(ch) case ‘a’: a++; break; case ‘e’: e++; break; case ‘I’: i++; break; case ‘o’; o++; break; case ‘u’; u++; switch(ch) case ‘a’: a++; break; case ‘e’: e++; break; case ‘I’: i++; break; case ‘o’; o++; break; case ‘u’; u++;

Topics The if Statement and Conditions Other Conditional Statements Comparing Data The while Statement Iterators Other Repetition Statements Decisions and Graphics More Components

Comparing Floating Point Numbers Given: int a, b; float x, y; Given: int a, b; float x, y; (a == b) is clear; but (a == b) is clear; but (x == y) should be avoided (x == y) should be avoided The expression may never be true. The expression may never be true. Two floating point numbers are equal only if they have the exact representation Two floating point numbers are equal only if they have the exact representation E.g., is represented as E.g., is represented as

Comparing Floating Point Numbers (cont.) Instead, use the following expression. final float DELTA = ; float x, y; … if (abs(a – b) <= DELTA) System.out.println(“close enough.”); Instead, use the following expression. final float DELTA = ; float x, y; … if (abs(a – b) <= DELTA) System.out.println(“close enough.”);

Comparing Characteres Comparison of characters Comparison of characters Based on Unicode numbers Based on Unicode numbers Called lexicographic order Called lexicographic order Note that numeric digit and alphabetic characters have consecutive Unicode numbers. Note that numeric digit and alphabetic characters have consecutive Unicode numbers. Characters Unicode Values 0 – 9 48 through 57 A – Z 65 through 90 a – z 97 through 122

Comparing Strings Given: String s1, s2; s1 = new String(“Abe”); s2 = new String(“Abe”); Given: String s1, s2; s1 = new String(“Abe”); s2 = new String(“Abe”); (s1 == s2) will return false, because s1 and s2 are essentially memory addresses. (s1 == s2) will return false, because s1 and s2 are essentially memory addresses. Generally speaking, do not use relational operators to compare objects. Generally speaking, do not use relational operators to compare objects.

Comparing Strings (cont.) Instead, use String mentods: Instead, use String mentods: If(s1.equals(s2)) System.out.println(“s1 == s2”); If(s1.equals(s2)) System.out.println(“s1 == s2”); n = s1.compareWith(s2); n = s1.compareWith(s2); If n is 0, then s1 == s2 If n is -1, then s1 < s2 If n = 1, then s1 > s2

Comparing Strings (cont.) The following expressions are all true. The following expressions are all true. “BOOK” < “book” “BOOK” < “book” “Venice” < “rome” “Venice” < “rome” “America” < “acupuncture” “America” < “acupuncture” “Santa Clara” < “Santa barbara” “Santa Clara” < “Santa barbara” “class” < “classical” “class” < “classical”

Topics The if Statement and Conditions Other Conditional Statements Comparing Data The while Statement Iterators Other Repetition Statements Decisions and Graphics More Components

While Statement While (boolean condition) { statement1 statement2 statement3 } While (boolean condition) { statement1 statement2 statement3 } One of the statements in the loop must cause a change in the value of the boolean condition. One of the statements in the loop must cause a change in the value of the boolean condition. statements true false condition evaluated

While Statement (cont.) cnt = 1; while (cnt <=10) { sum += cnt; cnt++; } cnt = 1; while (cnt <=10) { sum += cnt; cnt++; } While Statement Requirements: While Statement Requirements: 1. Loop control variable (LCV) is initialized 2. LCV is checked in the condition expression 3. LCV is updated in the loop  Average.java Average.java  WinPercentage.java WinPercentage.java

while Loop: Example Suppose that you save money each day, starting with 1 penny on day one, 2 pennies on day two, 4 pennies on day three, 8 pennies on day four, etc., each day doubling the amount from the preceding day. Write a program that calculates the number of days it takes to save at least $1,000,000. Suppose that you save money each day, starting with 1 penny on day one, 2 pennies on day two, 4 pennies on day three, 8 pennies on day four, etc., each day doubling the amount from the preceding day. Write a program that calculates the number of days it takes to save at least $1,000,000.

class WhileTest{ public static void main(String args[]){ int day; long total = 0; long save; long goal = ; day = 0; save = 1; while (total < goal){ day++; total = total + save; save = 2 * save; } System.out.println("It takes " + day + " days to save at least $1,000,000."); } }

Nested Loops How many times will the string "Here" be printed? How many times will the string "Here" be printed? count1 = 1; while (count1 <= 5) { count2 = 1; while (count2 <= 3) { System.out.println ("Here"); count2++; } count1++; }

Sentinel Value Read and print sum of numbers input. Stop input when -1 is read. int sum = 0; int num; num = scan.nextInt(); while (num != -1) { sum += num; num = scan.nextInt(); } System.out.println(“Sum: “ + sum); Read and print sum of numbers input. Stop input when -1 is read. int sum = 0; int num; num = scan.nextInt(); while (num != -1) { sum += num; num = scan.nextInt(); } System.out.println(“Sum: “ + sum);

Sentinel Value (Cont.) Read and print the average of numbers input. Stop input when -1 is read. int sum = 0; int count = 0; int num; double ave; num = scan.nextInt(); while (num != -1) { count++; sum += num; num = scan.nextInt(); } System.out.println(“Ave: “ + (double)sum / count); Read and print the average of numbers input. Stop input when -1 is read. int sum = 0; int count = 0; int num; double ave; num = scan.nextInt(); while (num != -1) { count++; sum += num; num = scan.nextInt(); } System.out.println(“Ave: “ + (double)sum / count);

Topics The if Statement and Conditions Other Conditional Statements Comparing Data The while Statement Iterators Other Repetition Statements Decisions and Graphics More Components

For-Loop While-loop sum = 0; cnt = 1; while (cnt <= 10) { sum += cnt; cnt++; } While-loop sum = 0; cnt = 1; while (cnt <= 10) { sum += cnt; cnt++; } For-loop sum = 0; for (int cnt = 1; cnt <= 0; cnt++) { sum += 0; } For-loop sum = 0; for (int cnt = 1; cnt <= 0; cnt++) { sum += 0; }

Example Programs Multiples.java Multiples.java Multiples.java Stars.java Stars.java Stars.java

For-Loop int[] aList = {2, 4, 6, 8, 10}; for (int i = 0; i < aList.length; i++) System.out.println(aList[i] + “ ”); int sum = 0; for (int i = 0; i < aList.length; i++) sum = sum + aList[i]; System.out.println(“Sum: “ + sum);

Triangle Patterns Q: Write a program to produce the following patterns (one after another). Q: Write a program to produce the following patterns (one after another). * ** *** **** ***** ****** ******* ******** ********* ********** Answer: Answer: Answer:

class ArrayTest { String[] names = {"Mike", "Mary", "Martha"}; String[] addresses = new String[names.length]; void printList(){ for (int i = 0; i < names.length; i++) System.out.println(names[i] + " lives at " + addresses[i]); } public static void main(String args[]){ ArrayTest aList = new ArrayTest(); aList.addresses[0] = "123 Apple St."; aList.addresses[1] = "234 Banana Blvd."; aList.addresses[2] = "345 Citrus Ct."; aList.printList(); } }

Do-Loop do { statement1; statement2; } while (boolean condition) do { statement1; statement2; } while (boolean condition) Boolean condition is checked at the bottom of the loop. Boolean condition is checked at the bottom of the loop. A Do-Loop executes at least once, but While-Loop executes 0 or more times. A Do-Loop executes at least once, but While-Loop executes 0 or more times.

Comparing Do-Loop with While-Loop statement true false condition evaluated The while Loop true condition evaluated statement false The do Loop

Topics The if Statement and Conditions Other Conditional Statements Comparing Data The while Statement Iterators Other Repetition Statements Decisions and Graphics More Components