Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/29 The switch Statement The switch statement provides another way.

Slides:



Advertisements
Similar presentations
1 Chapter 3: Program Statements Lian Yu Department of Computer Science and Engineering Arizona State University Tempe, AZ
Advertisements

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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Comparing Data Comparing More than Numbers. Comparing Data When comparing data using boolean expressions, it's important to understand the nuances of.
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.
ECE122 L8: More Conditional Statements February 7, 2007 ECE 122 Engineering Problem Solving with Java Lecture 8 More Conditional Statements.
Java Program Statements Selim Aksoy Bilkent University Department of Computer Engineering
Logical Operators and Conditional statements
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 Conditionals and Loops Now we will examine programming statements.
Chapter Day 12. © 2007 Pearson Addison-Wesley. All rights reserved5-2 Agenda Day 12 Problem set corrected  1 A, 2 B’s and 1 D Starting Late and not turning.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 Conditionals and Loops Now we will examine programming statements.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
CSCI 1100/1202 January 28, The switch Statement The switch statement provides another means to decide which statement to execute next The switch.
Chapter 3: Program Statements
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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.
5-1 Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements,
Chapter 5 Loops.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops.
Switch Statements Comparing Exact Values. The Switch Statement: Syntax The switch statement provides another way to decide which statement to execute.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
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.
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. © 2004 Pearson Addison-Wesley. All rights reserved5-2 Conditionals and Loops Now we will examine programming statements.
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.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
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.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
1 More about Flow of Control. Topics Debugging Logical Operators (Chapter 5) Comparing Data (Chapter 5) The conditional operator The switch Statement.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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.
Programming in Java (COP 2250) Lecture 12 & 13 Chengyong Yang Fall, 2005.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CprE 185: Intro to Problem Solving (using C)
Chapter 4 Repetition Statements (loops)
The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression,
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Flow of Control Unless specified otherwise, the order of statement execution through a method is linear: one after another Some programming statements.
Chapter 6 More Conditionals and Loops
Outline Altering flow of control Boolean expressions
The ‘while’ Statement September 27, 2006
Chapter 3: Program Statements
CprE 185: Intro to Problem Solving (using C)
Outline Boolean Expressions The if Statement Comparing Data
‘do’ and ‘for’ loops October 1, 2007 ComS 207: Programming I (in Java)
CprE 185: Intro to Problem Solving (using C)
‘do’ and ‘for’ loops October 2, 2006 ComS 207: Programming I (in Java)
Presentation transcript:

Chapter 5 Conditionals and Loops

© 2004 Pearson Addison-Wesley. All rights reserved2/29 The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression, then attempts to match the result to one of several possible cases Each case contains a value and a list of statements The flow of control transfers to statement associated with the first case value that matches

© 2004 Pearson Addison-Wesley. All rights reserved3/29 The switch Statement The general syntax of a switch statement is: switch ( expression ) { case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case... }//end switch switch and case are reserved words If expression matches value2, control jumps to here

© 2004 Pearson Addison-Wesley. All rights reserved4/29 The switch Statement eachOften a break statement is used as the last statement in each case's statement list A break statement causes control to transfer to the end of the switch statement  If a break statement is not used, the flow of control will continue into the next case  Sometimes this may be appropriate, but often we want to execute only the statements associated with one case

© 2004 Pearson Addison-Wesley. All rights reserved5/29 The switch Statement switch (option) { case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; }// end switch An example of a switch statement: Assumes we have a character variable named option that has a character value… as in char option = ‘C’;

© 2004 Pearson Addison-Wesley. All rights reserved6/29 The switch Statement A switch statement can have an optional default case The default case has no associated value and simply uses the reserved word default  If the default case is present, control will transfer to it if no other case value matches  if there is no default case, and no other value matches, control falls through to the statement after the switch

© 2004 Pearson Addison-Wesley. All rights reserved7/29 The switch Statement  The expression of a switch statement must result in an integral type, meaning an int or a char  It cannot be a boolean value, a floating point value ( float or double ), or another integer type The implicit boolean condition in a switch statement is equality You cannot perform relational checks with a switch statement See GradeReport.javaGradeReport.java

© 2004 Pearson Addison-Wesley. All rights reserved8/29 public class GradeReport { // Again, I omitted lines so I could fit this on one slide. public static void main (String[] args) { int grade, category; Scanner scan = new Scanner (System.in); // you may use a Buffered Reader object as well…. Look these up… System.out.print ("Enter a numeric grade (0 to 100): "); grade = scan.nextInt(); // we use Wrapper classes to convert the String grade to an int grade. category = grade / 10; // What does this do? System.out.print ("That grade is "); switch (category) { case 10: System.out.println ("a perfect score. Well done."); break; case 9: System.out.println ("well above average. Excellent."); break; case 8: System.out.println ("above average. Nice job."); break; case 7: System.out.println ("average."); break; case 6: System.out.println ("below average. You should see the"); System.out.println ("instructor to clarify the material " + "presented in class."); break; default: System.out.println ("not passing."); } // end switch } // end main() } // end class What would you do if I wanted to branch to a specific case and then continue with the remaining cases until the end?

© 2004 Pearson Addison-Wesley. All rights reserved9/29 Outline The if Statement and Conditions Other Conditional Statements Comparing Data The while Statement Iterators Other Repetition Statements

© 2004 Pearson Addison-Wesley. All rights reserved10/29 Comparing Data – Very Important!! When comparing data using boolean expressions, it's important to understand the nuances of certain data types Let's examine some key situations:  Comparing floating point values for equality  Comparing characters  Comparing strings (alphabetical order)  Comparing object vs. comparing object references

© 2004 Pearson Addison-Wesley. All rights reserved11/29 Float Values Comparing Float Values  You should rarely use the equality operator ( == ) when comparing two floating point values ( float or double ) Two floating point values are equal only if their underlying binary representations match exactly Computations often result in slight differences that may be irrelevant In many situations, you might consider two floating point numbers to be "close enough" even if they aren't exactly equal

© 2004 Pearson Addison-Wesley. All rights reserved12/29 Comparing Float Values To determine the equality of two floats, you may want to use the following technique: if (Math.abs(f1 - f2) < TOLERANCE) System.out.println ("Essentially equal"); If the difference between the two floating point values is less than the tolerance, they are considered to be equal The tolerance could be set to any appropriate level, such as

© 2004 Pearson Addison-Wesley. All rights reserved13/29 Characters Comparing Characters As we've discussed, Java character data is based on the Unicode character set Unicode establishes a particular numeric value for each character, and therefore an ordering We can use relational operators on character data based on this ordering  For example, the character '+' is less than the character ' J' because it comes before it in the Unicode character set  One of the appendices provides an overview of Unicode  Look at this Appendix!!

© 2004 Pearson Addison-Wesley. All rights reserved14/29 Comparing Characters In Unicode, the digit characters (0-9) are contiguous and in order Likewise, the uppercase letters (A-Z) and lowercase letters (a-z) are contiguous and in order CharactersUnicode Values 0 – 948 through 57 A – Z65 through 90 a – z97 through 122 Know These.

© 2004 Pearson Addison-Wesley. All rights reserved15/29 Strings Comparing Strings objectRemember that in Java a character string is an object equals methodThe equals method can be called with strings to determine if two strings contain exactly the same characters in the same order The equals method returns a boolean result Assuming name1 and name2 are objects of type String and already have values, we can say: if (name1.equals(name2)) System.out.println ("Same name"); Note the syntax!!! This is how you do it.

© 2004 Pearson Addison-Wesley. All rights reserved16/29 Comparing Strings  We cannot use the relational operators to compare strings comes beforeThe String class contains a method called compareTo to determine if one string comes before another  (like if we are sorting or alphabetizing…) A call to name1.compareTo(name2)  returns zero if name1 and name2 are equal (contain the same characters)  returns a negative value if name1 is less than name2  returns a positive value if name1 is greater than name2

© 2004 Pearson Addison-Wesley. All rights reserved17/29 Comparing Strings – VIP Example!! if (name1.compareTo(name2) < 0) System.out.println (name1 + "comes first"); else if (name1.compareTo(name2) == 0) System.out.println ("Same name"); else System.out.println (name2 + "comes first"); Because comparing characters and strings is based on a character set, it is called a lexicographic ordering Also note that the above code was a ‘nested-if.’

© 2004 Pearson Addison-Wesley. All rights reserved18/29 Lexicographic Ordering not strictly alphabetical  Lexicographic ordering is not strictly alphabetical when uppercase and lowercase characters are mixed For example, the string "Great" comes before the string "fantastic" because all of the uppercase letters come before all of the lowercase letters in Unicode Also, short strings come before longer strings with the same prefix (lexicographically) Therefore "book" comes before "bookcase“  Characters are compared one-by-one until a difference is discovered!!

© 2004 Pearson Addison-Wesley. All rights reserved19/29 Comparing Objects The == operator can be applied to objects – it returns true if the two references are aliases of each other  What does this mean to you??? The equals method is defined for all objects, but unless we redefine it when we write a class (whoa! Later!), it has the same semantics as the == operator has beenIt has been redefined in the String class to compare the characters in the two strings When you write a class, you can redefine the equals method to return true under whatever conditions are appropriate. More later….

© 2004 Pearson Addison-Wesley. All rights reserved20/29 Outline The if Statement and Conditions Other Conditional Statements Comparing Data The while Statement Iterators Other Repetition Statements

© 2004 Pearson Addison-Wesley. All rights reserved21/29 Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements, they are controlled by boolean expressions  Java has three kinds of repetition statements:  the while loop  the do loop  the for loop  The programmer should choose the right kind of loop for the situation

© 2004 Pearson Addison-Wesley. All rights reserved22/29 The while Statement A while statement has the following syntax: while ( condition ) statement; If the condition is true, the statement is executed Then the condition is evaluated again, and if it is still true, the statement is executed again The statement is executed repeatedly until the condition becomes false

© 2004 Pearson Addison-Wesley. All rights reserved23/29 Logic of a while Loop statement true false condition evaluated Note: there is a ‘pretest.’ What does this mean??

© 2004 Pearson Addison-Wesley. All rights reserved24/29 The while Statement An example of a while statement: int count = 1; while (count <= 5) { System.out.println (count); count++; }// end while If the condition of a while loop is false initially, the statement is never executed Therefore, the body of a while loop will execute zero or more times

© 2004 Pearson Addison-Wesley. All rights reserved25/29 The while Statement Let's look at some examples of loop processing A loop can be used to maintain a running sum A sentinel value is a special input value that represents the end of input See Average.java (next slide)Average.java A loop can also be used for input validation, making a program more robust See WinPercentage.javaWinPercentage.java Look at these two routines. You may see them again! If you have any questions, please let me know!!

© 2004 Pearson Addison-Wesley. All rights reserved26/29 … import java.text.DecimalFormat; import java.util.Scanner; public class Average { ….. Comments …. public static void main (String [ ] args) { int sum = 0; value, count = 0; double average; Scanner scan = new Scanner (System.in); System.out.print (“Enter an integer (0 to quit): “); value = scan.nextInt(); while (value != 0)// note the indentation; note the braces and alignment! {// note the ‘blocks’ and then (below) single statements in the if. count++; sum += value; System.out.println (“The sum so far is “ + sum); System.out.print (“Enter an integr (0 to quit): “); value = scan.nextInt(); } // end while System.out.println (); if (count == 0) System.out.println (“No values were entered.”); else { average = (double)sum/count; DecimalFormat fmt = new DecimalFormat (“0.###”); System.out.println (“The average is “ + fmt.format(average)); } // end if } // end main() } // end class Average

© 2004 Pearson Addison-Wesley. All rights reserved27/29 Infinite Loops The body of a while loop eventually must make the condition false If not, it is called an infinite loop, which will execute until the user interrupts the program  This is a common logical error You should always double check the logic of a program to ensure that your loops will terminate normally

© 2004 Pearson Addison-Wesley. All rights reserved28/29 Infinite Loops An example of an infinite loop: int count = 1; while (count <= 25) { System.out.println (count); count = count - 1; }// end while This loop will continue executing until interrupted (Control-C) or until an underflow error occurs

© 2004 Pearson Addison-Wesley. All rights reserved29/29 Nested Loops Similar to nested if statements, loops can be nested as well That is, the body of a loop can contain another loop For each iteration of the outer loop, the inner loop iterates completely

© 2004 Pearson Addison-Wesley. All rights reserved30/29 Nested Loops – Very Important e.g. How many times will the string "Here" be printed? count1 = 1; while (count1 <= 10) { count2 = 1; while (count2 <= 20) { System.out.println ("Here"); count2++; }// end inner while count1++; } // end out while

© 2004 Pearson Addison-Wesley. All rights reserved31/29 Questions I like to ask about loops What is the value of the loop control variable when I exit from the loop? How many times will I execute the body of the loop? What is missing in this loop? What is the output of the loop? Then, I will leave off (or add) braces within the body of a loop and question you as to how the loop will execute. Ditto for nexted loops.