Control Statements Review CSC 123 Fall 2018 Howard Rosenthal

Similar documents
Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Repetition CSC 121 Fall 2014 Howard Rosenthal

REPETITION CONTROL STRUCTURE LOGO

Chapter 3. Selections

Introduction. C provides two styles of flow control:

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

STUDENT LESSON A12 Iterations

Flow Control. CSC215 Lecture

Repetition Structures

Chapter 4: Making Decisions

Chapter 4: Making Decisions

CS 106 Introduction to Computer Science I

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Full file at

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

Chapter 4: Making Decisions. Copyright 2012 Pearson Education, Inc. Sunday, September 7, 14

Program Development. Chapter 3: Program Statements. Program Statements. Requirements. Java Software Solutions for AP* Computer Science A 2nd Edition

Chapter 3: Program Statements

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

LECTURE 04 MAKING DECISIONS

Conditionals and Loops

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

Repetition, Looping. While Loop

Introduction to Java & Fundamental Data Types

Conditional Statement

3 The L oop Control Structure

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

CS 251 Intermediate Programming Java Basics

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

5. Control Statements

printf( Please enter another number: ); scanf( %d, &num2);

Topics. Chapter 5. Equality Operators

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

4.1. Chapter 4: Simple Program Scheme. Simple Program Scheme. Relational Operators. So far our programs follow a simple scheme

DECISION STRUCTURES: USING IF STATEMENTS IN JAVA

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

Controls Structure for Repetition

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 5. Repetition in Programs. Notes. Notes. Notes. Lecture 05 - Loops

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

Pace University. Fundamental Concepts of CS121 1

Decisions. Arizona State University 1

Flow of Control: Loops. Chapter 4

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

CS112 Lecture: Repetition Statements

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

CSCE150A. Introduction. While Loop. Compound Assignment. For Loop. Loop Design. Nested Loops. Do-While Loop. Programming Tips CSCE150A.

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

2.8. Decision Making: Equality and Relational Operators

Loops (while and for)

Chapter 4: Conditionals and Loops

Java Coding 3. Over & over again!

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

Chapter 4: Loops and Files

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Module 4: Decision-making and forming loops

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

Programming with Java

Chapter 3: Operators, Expressions and Type Conversion

Programming for Engineers Iteration

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

Loops. CSE 114, Computer Science 1 Stony Brook University

Decision Making in C

LECTURE 5 Control Structures Part 2

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Fundamental of Programming (C)

Lecture 7 Tao Wang 1

Loops and Files. of do-while loop

Chapter 17. Iteration The while Statement

Chapter 5: Control Structures

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Computer Programming I - Unit 5 Lecture page 1 of 14

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

Control Structures in Java if-else and switch

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

C++ Programming: From Problem Analysis to Program Design, Third Edition

Introduction to Java Applications

Chapter 5: Loops and Files

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

Text Input and Conditionals

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

Information Science 1

Chapter 4: Loops and Files

Lesson 6A Loops. By John B. Owen All rights reserved 2011, revised 2014

Transcription:

Control Statements Review CSC 123 Fall 2018 Howard Rosenthal

Lesson Goals Review some of Java s control structures Review how to control the flow of a program via selection mechanisms Understand if, if-else, else-if and switch statements Build programs with nested layers of decision making Building blocks of execution code Review how to deal with the dangling else Understand the conditional operator Review the following three repetition structures in Java, their syntax, their similarities and differences, and how to avoid common errors when using them: while do-while for Review nested looping Review how to use break statements to exit a loop Review and expand knowledge of blocks and scope 2

3

Control Structures in Java There are three control structures in Java Sequence Structure Built into Java Ensures that statements execute one after the other in the order they are written, unless directed otherwise Selection Structure Based on truth or falsity In Java includes the if, if else, if... else if, and switch statements Repetition Structure Allows for repetition of the same group of statements multiple times, as long as a condition is met In Java includes the do, do while, for, and enhanced for statements Also known as iteration statements or looping statements 4

Two Way Decisions Windshield wipers are controlled with an ON-OFF switch. The flowchart at right shows how this decision is made. Start at the top of the chart then follow the line to the question: is it raining? The answer is either true or false. If the answer is true, follow the line labeled True, perform the instructions in the box "wipers on", follow the line to "continue". If the answer is false, follow the line labeled False, perform the instructions in the box "wipers off", follow the line to "continue". The windshield wiper decision is a two-way decision (sometimes called a binary decision). The decision seems small, but in programming, complicated decisions are made by executing many small decisions. 5

The Basic Syntax of the if Statement if (boolean expression) statement 1; statement 2; o 0 o statement n; The statements inside the block (delineated by a pair of braces) are executed only if the boolean statement (in parentheses) is true You should use the braces even if there is only a single statement inside the block even though this isn t required No semicolon on the if statement An if with a single statement following it does not require curly braces, however, it is best to use them all the time at first if (boolean expression) statement 1; 6

Basic Terminology An if statement is also called a conditional or selection statement The phrase if (boolean expression) is called the if clause The boolean expression itself is called the condition The statements inside the curly braces comprise a block You can nest if statements inside each other Write out the statements that will add 3 to int x initialized to 4 if the boolean value y is true. Initialize y to either true or false. 7

Answer boolean y = true; int x = 4; if (y == true) x = x+3; 8

A Very Simple Example public class SimpleIfStatementDemo1 public static void main(string [] args) //Declaring a variable "test" and initializing it with a value 10 int test = 10; //Checking if "test" is greater than 5 if (test > 5) //This block will be executed only if "test" is greater than 5 System.out.printf("Success\n"); //The if block ends. System.out.printf("Executed successfully\n"); 9

The Basic Syntax of the if-else Statement Similar to the if statement, but exclusively executes an alternative set of statement(s) if the conditional is false if (boolean expression) // always evaluates to either true or false statement 1; statement 2; o 0 o statement n; else statement a; statement b; o 0 o statement x; Note: Once again if there is only a single statement then braces are not required if (boolean expression) // always evaluates to either true or false statement 1; else statement a; 10

A Simple Example of if-else import java.util.scanner; public class NumberTester public static void main (String[] args) Scanner keyboard = new Scanner( System.in ); int num; System.out.printf ("Enter an integer: "); num = keyboard.nextint(); if ( num < 0 ) System.out.printf("The number is %d negative\n, num); num = num +5; else System.out.printf("The number %d is zero or positive\n, num); num = num -4; System.out.printf("The number is now %d, num ); System.out.printf("Good-bye for now\n"); 11

if else if Syntax Allows for testing for multiple different conditions Only the first case that tests as true will be executed If there is no else statement at the end then it is possible that none of the blocks are executed if (boolean expression) // always evaluates to either true or false statement 1; statement 2; o 0 statement n; else if (boolean expression) // always evaluates to true or false statement a; statement b; o 0 statement x; else //optional statement a; statement b; o 0 statement x; 12

An else if Example //This program assigns a letter grade based on a character grade import java.util.scanner; class IfElseIfDemo public static void main(string[] args) Scanner keyboard = new Scanner(System.in); System.out.printf("Enter the grade: "); int testscore = keyboard.nextint(); char grade; if (testscore >= 90) grade = 'A'; else if (testscore >= 80) grade = 'B'; else if (testscore >= 70) grade = 'C'; else if (testscore >= 60) else grade = 'D'; grade = 'F'; System.out.printf("Grade = %c\n, grade); Note: If you reverse the order then you would need to compare from bottom to top using <= Be careful in use of > vs. >=, etc. Remember, for any particular level of if, else-if, else, only the block after the first true statement is executed 13

A Note On boolean Expressions Be careful when using float or double type variables in boolean expressions Since there is always limited precision the possibility of an execution error exists, especially after more complex mathematical operations Example: (7.13*2.9)/(3.6*2.95) may be different than (7.13/(3.6*2.95))*2.9 See DecimalCompare.java and DecimalCompare2.java With DecimalCompare and println you can see where the difference shows up, which is far beyond the second decimal place 14

The Dangling if (1) Rule - An else matches with the nearest, previous, unmatched if that's not in a block. if ( num > 0 ) if ( num < 10 ) // Previous unmatched if System.out.printf( "aaa\n" ); else // Matches with previous unmatched if System.out.printf( "bbb\n" ); In the example above, the else is indented with the inner if statement. It prints "bbb" only if num > 0 and num >= 10, which means it prints only if num is 10 or greater. In the example below, the else is indented with the outer if statement. if ( num > 0 ) if ( num < 10 ) // Previous unmatched if System.out.printf( "aaa\n" ) ; else // Matches with previous unmatched if System.out.printf( "bbb\n" ) ; Which one does else match with? It picks the closest if unless there is a further clarification with the use of braces. This phenomenon of having to pick between one of two possible if statements is called the dangling else. Depending on which if the else is paired with, you can get different results. By now, you should know that Java doesn't pay attention to indentation. So both examples above are the same to Java, which means that it makes its determination based strictly on the syntax. To the Java Compiler there is no ambiguity (You can t say That s not what I really meant ) The compiler doesn t care about indenting. But you should for clarity 15

The Dangling if (2) What if we wanted the else to match with the first if? Then, we need braces. if ( num > 0 ) // Previous unmatched if if ( num < 10 ) // Unmatched, but in block System.out.printf( "aaa\n" ) ; else // Matches with previous unmatched if not in block System.out.printf( "bbb\n" ) ; //This prints if num <= 0. The else above matches with the previous, unmatched if not in the lower level block. This happens to be the outer if. There is an unmatched if that's the inner if, but that's in a block, so you can't match to it. Notice the else sits outside of the block. An else does not match to a previous if if the else is outside the block, where the closest if is found. 16

Dangling if Flows F if num > 0 if num > 0 F T T if num <10 F F if num <10 T Print aaa Print bbb T Print aaa Print bbb 17

The Dangling if The Rules Summarized Every else must match with a unique if. You can't have two or more else matching to the same if. If there is no matching if for an else, then your program won't compile. Each else must be preceded by a valid if Fortunately, your program fails to compile if you don't do this. Use Braces If you always use a block for if body and else body, then you can avoid confusion. However, it's useful to know the correct rules. 18

The switch Statement The syntax of a switch statement looks like: switch ( expr ) case literal1: case literal1 body case literal2: case literal2 body case literal3: case literal3 body default: default body Unlike if statements which contain a condition in the parentheses, switch contains an expression. This expression must be type byte, short, int, char or String. (Note: String is a newer feature, and the book says only int or char). Wrapper classes or an evaluation of an enumeration type can also be The semantics of switch are: Evaluate the expression Begin looking at each case, starting top to bottom If the value of the expression matches the case, then run the body Note: The case keyword has to be followed by a literal or a constant expression. It can't be a range If you run a break statement, you then exit the switch If you don't run a break statement, and you are at the end of a body, run the next body. Keep running bodies until you exit or hit a break statement If no match is made to the cases, run the default, if it exists. The default case is always run last, no matter where it appears. (It should be placed last, though). It is not mandatory to have a default statement. 19

Examples of the switch Statement int x = 4 ; switch ( x ) case 2: System.out.printf( "TWO\n" ) ; break ; case 4: System.out.printf( "FOUR\n" ) ; break ; case 6: System.out.printf( "SIX\n" ) ; break ; default: System.out.printf( "DEFAULT\n" ) ; See SwitchExample.java for full program This evaluates x to 4. It skips case 2 since the value 4 doesn't match 2. It does match case 4. It runs the body and prints FOUR". Then it runs break and exits the switch. 20

Examples of the switch Statement (2) Most of the times, you will end each case with break. Let's see what happens when you leave it out. int x = 4 ; switch ( x ) case 2: System.out.printf( "TWO\n" ) ; case 4: System.out.printf( "FOUR\n" ) ; case 6: System.out.printf( "SIX\n" ) ; default: System.out.printf( "DEFAULT\n" ) ; This prints out: FOUR SIX DEFAULT That's probably not what the user had in mind. Without the break, each time a body runs, it falls through and starts running the next body, and the next, after it matches the correct case. However, there are cases where you will want to execute multiple statements from multiple cases (see next example) See full program in SwitchExample2.java 21

Examples of the switch Statement (3) You can combine cases together. int x = 4 ; switch ( x ) case 1: case 3: case 5: System.out.printf( "ODD\n" ) ; break ; case 2: case 4: case 6: System.out.printf( "EVEN\n" ) ; break ; default: System.out.printf( "DEFAULT\n" ) ; See full program as SwitchExample3.java 22

A Few Additional Notes On the switch Statement Every switch statement can be implemented as an if/if else type statement It doesn t always work the other way around Obviously if the if/else is doing more complex comparisons or using boolean values or floating point numbers, then this can t be implemented in a switch statement 23

The Conditional Operator (1) The conditional operator is used like this: true-or-false-condition? value-if-true : value-if-false Here is how it works: The true-or-false-condition evaluates to true or false. That value selects one choice: If the true-or-false-condition is true, then evaluate the expression between? and : If the true-or-false-condition is false, then evaluate the expression between : and the end. The result of evaluation is the value of the entire conditional expression. This approach can be used in assignment statements 24

The Conditional Operator (2) int a = 7, b = 21; System.out.printf ("The min is: %d\n,(a < b? a : b ) ); The output would be: The min is 7 25

The Conditional Operator (3) double value = -34.569; double absvalue; absvalue = ((value < 0 )? -value : value) ; ------------- ------ The constant value +34.569 is assigned to absvalue 26

An Example Using String Features import java.util.scanner; class RainTester public static void main (String[] args) Scanner keyboard = new Scanner( System.in ); String answer; System.out.printf("Is it raining? (Y or N): "); answer = keyboard.nextline(); if ( answer.equals("y") ) // is answer exactly "Y"? System.out.printf("Wipers On\n ); // true branch else System.out.printf("Wipers Off\n"); // false branch 27

A Few Note For Good Programming Always check your programs through each of the else cases, switch gates etc. To do this you need to develop a set of test cases A test case has components that describe an input, action or event and an expected response, to determine if a feature of an application is working correctly Your test cases must be expansive enough to cover the full range of possibilities For instance if there is a statement if (x>4) you don t need to test for every possibility greater than 4, but you need to test for at least one that is greater than 4, one that equals 4 and one that is less than 4. Typically we build a software test verification matrix 28

Sample Test Matrix Y 2 3 4 X 1 R1 R2 R3 2 R4 R5 R6 5 R7 R8 R9 7 R10 R11 R12 Test for all possible combinations When there are multiple variables break the testing into smaller pieces Always test for different and outlying conditions Positive, zero and negative numbers First and last number and some element in the middle when processing a list 29

30

Introduction to Loops Many of the tasks performed by computers require repetition, often massive repetition Using repetitive syntax can make your code more concise and easier to write and debug Java has three types of repetitive constructs (also known as loops): while, dowhile or for Loops are built out of several fundamental statements because there are three things (in each of the three types of loops) that must be done correctly: The variables used to control the loop must be initialized correctly The ending condition for the loop must be tested correctly The body of the loop or the loop statement must change the condition that is tested otherwise you can wind up with an infinite loop Overlooking one of these aspects results in a defective loop and a sometimes difficult to find program bug! Usually each of these three considerations is located in a different spot. No wonder that loops often go wrong! You have to plan out the logic of your program in order to effectively use loops and conditionals Anything that can be done with one loop structure can be done with either of the other two, but sometimes the logic makes one preferable to the other 31

Types of Loops Type counting loop sentinel-controlled loop result-controlled loop Description Uses a loop control variable to count upwards or downwards (usually by an integer increment.) Example: Keep going until you run 100 miles. Loop keeps going until a special value is encountered in the data. Example: Keep going until you hit a red light. Loop keeps going until a test determines that the desired result has been achieved. Example. Keep going until you reach your home. 32

The while Statement Here is a program with a loop. It contains a while statement, followed by a block of code. Remember, a block is a group of statements enclosed in braces. // Example of a while loop public class WhileLoopExample1 public static void main (String[] args ) // start count out at one int count = 1; while ( count <= 3 ) System.out.printf( Count is: %d\n, count ); count = count + 1; // add one to count System.out.printf( "Done with the loop\n ); 33

The Basic Syntax of the while Statement while (condition) statement 1; statement 2; o 0 o statement n; You execute through the entire block repetitively until the condition is false unless you encounter a break statement The break will typically occur based on a separate condition tested with an if statement 34

Basic Terminology of the while Statement The condition is a boolean expression: something that evaluates to true or false The condition can be complicated, using many relational operators and logical operators. Due to the precision of integers, integers are almost always used as counters for loops A single statement is allowed Without braces only one statement is executed inside the loop The block or single executable statement is sometimes called the loop body If one of the statements in the while block doesn t eventually change the value of the condition then the loop goes on forever The while loop may not be executed at all if the initial condition is false There is no semi-colon after the while statement If you put one there you will end the loop before it executes anything 35

Counters Can Be Decremented Rather Than Incremented When The Need Arises Here is a program with a loop It contains a while statement, followed by a block of code The condition is checked when entering the loop, and for each iteration If the condition is false the loop is skipped over Remember, a block is a group of statements enclosed in braces. // Pseudocode example public class WhileLoopExample2 public static void main (String[] args ) int count = 2; // count is initialized while ( count >= 0 ) // count is tested System.out.printf( Count is: %d\n, count ); count = count - 1; // count is changed by -1 System.out.printf( "Done counting down\n" ); 36

Using a Flag To Guarantee Execution Of a While Statement Sometimes you want to ensure at least one execution of a loop so you use a boolean flag set to true (or false depending on the statement) /// Example of a while loop with flag import java.util.scanner; public class WhileLoopFlag public static void main (String[] args ) int number, sum = 0; boolean flag = true; // flag is initialized Scanner keyboard = new Scanner(System.in); while ( flag == true) // flag is tested System.out.printf( Enter an integer value, with a zero ending the accumulation: ); number =keyboard.nextint(); if (number == 0) flag = false; else sum = sum+number; System.out.printf( Sum is %d\n, sum); 37

The do-while Statement Here is a program with a loop It contains a do statement, followed by a block of code, followed by a while statement The condition is checked at the end of each execution of the loop which is always executed at least once // Example of a do-while loop that executes only once public class DoWhileLoopExample public static void main (String[] args ) int count = 1000; // initialize do System.out.printf( Count is: %d\n, count ); count++ ; while ( count < 10 ); // test System.out.printf( "Done with the loop\n" ); 38

The Basic Syntax of the do-while Statement do statement1; statement2; o 0 0 statementn; while (condition); 39

Basic Terminology of the do-while Statement The condition is a boolean expression: something that evaluates to true or false The condition can be complicated, using many relational operators and logical operators A single statement is allowed Without braces to create a block only one statement is executed inside the loop The block or single executable statement is sometimes called the loop body. The do-while is always executed at least once, if the do statement is executed There is a semi-colon after the while statement in a dowhile 40

The for Statement Here is a program with a loop. It contains a for statement, followed by a block of code. A block is a group of statements enclosed in braces. // Example of a for loop public class ForLoopExample public static void main (String[] args ) int sum=0; for ( int count = 0; count <= 5; count++ ) sum = sum + count ; System.out.printf( Count is: %d, count); System.out.printf( \nsum is: %d\n, sum ); sum = 0 Initialization count = 0 loop condition count <= 5 sum = sum + count Print count count++ Print sum false 41

The Basic Syntax of the for Statement for (initialization; loop condition; update statements) statement1; statement2; o 0 0 statementn; 42

Basic Terminology of the for Statement initialization Used to initialize basic variables used in the loop condition More than one variable can be set, separated by commas You can declare the variable in the for statement, but then it is only valid within the for loop within which it is created for (int j=3, k=4; ; ) If no variables are set, you must have a ; before the loop condition this typically means that the variable has been set prior to the for statement The initialization portion of the for statement is only executed once, each time you enter the loop. This allows you to nest loops loop condition A boolean expression evaluates as true or false Evaluated at the beginning of each loop Although this statement can be left out, leaving it out could lead to an infinite do loop, unless you execute a break statement inside the loop 43

Basic Terminology of the for Statement (2) update statement(s) Increases or decreases a value, typically one or more used in the loop condition Always executed at the end of the loop body Can include more than one statement, separated by commas for( ; ; i++, j= j+5) Usually use postfix notation, but in this case prefix work exactly the same Notes: If you are eliminating multiple parts of a for statement it may be better to use a while or do-while Don t stuff too many extraneous things into the for statement, you ll confuse yourself Most people use for statements when executing a loop a specific number of times 44

Nested Loops A nested loop is a (inner) loop that appears in the loop body of another (outer) loop. The inner or outer loop can be any type: while, do while, or for. For example, the inner loop can be a while loop while an outer loop can be a for loop. Of course, they can be the same kind of loops too. Inner loops always stay completely inside their outer loops An inner loop may be skipped over during the execution of an outer loop If the inner loop has a tested condition that starts out false or If the loop is inside of an if block that isn t executed, then that loop wouldn t be executed 45

Nested Loop Example // Example of nested loop that prints a rectangle of stars public class NestedLoops public static void main (String[] args ) int height =5; int width = 4; for ( int i = 0 ; i < height ; i++ ) for ( int j = 0 ; j< width ; j++ ) System.out.printf( %s, "*" ) ; System.out.printf( \n" ) ; 46

The Multiplication Table Is A Good Example Of Nested Looping 1 2 3 4 5 6 7 8 9 1 1 2 3 4 5 6 7 8 9 2 2 4 6 8 10 12 14 16 18 3 3 6 9 12 15 18 21 24 27 4 4 8 12 16 20 24 28 32 36 5 5 10 15 20 25 30 35 40 45 6 6 12 18 24 30 36 42 48 54 7 7 14 21 28 35 42 49 56 63 8 8 16 24 32 40 48 56 64 72 9 9 18 27 36 45 54 63 72 81 47

How Can We Use Loops To Help Construct This Table 1. Write the Top Row a. Use a loop to write the numbers 1-9 2. Draw a horizontal line line 3. For each row a. Write the row number b. Draw a vertical line c. For each column 1) Calculate the product 2) Write the product d. Skip to the next row Now we ll look at the solution in MultTable.java and MultTablePrintln.java 48

The break Statement Used to immediately exit the innermost loop that the break is found within, unless the loop is labeled Loop is labeled with looplabelname: followed by the loop the name begins with an alpha character followed by alphas, number, $, _ characters The next statement executed is the first statement beyond the scope of that loop If you label a loop the break statement can be used to exit through an outer nesting We ll look at SimpleBreakLoop.java and BreakLabeledLoop.java Note: any bock can be labeled, not just iterations label: You can then use a break label; to to exit out of the block with the name label 49

The continue Statement When executed in a repetition statement, the remainder of the statements in that iteration of the loop body are skipped, and the next iteration test is executed. In the for statement the update statements are executed We ll look at the ContinueExample.java 50

The flag or sentinel A flag or sentinel is a value appended to a data collection that signals the end of the data. The idea of a sentinel controlled loop is that there is a special value (the sentinel) that is used to control when the loop is done. In following code fragment, the user enters a zero when the sum is complete. Zero is the sentinel. Here is how the program should work import java.util.scanner; // Add up integers entered by the user. // After the last integer, the user enters a 0 class AddUpNumbers public static void main (String[] args ) Scanner keyboard = new Scanner( System.in ); int value, sum = 0; System.out.printf("Enter first integer (enter 0 to quit): ); value = keyboard.nextint(); //we initialize value before entering the loop while ( value!= 0 ) sum = sum + value; System.out.printf( Enter next integer (enter 0 to quit): ); value = keyboard.nextint(); //update value inside the loop System.out.printf("Sum of the integers is: %d\n, sum); 51

The hasnext() Method of the Scanner class The hasnext() method keeps reading data unto there is no more data to read When there is no more data to read it returns false Once we start reading from files (Chapter 9), that means that it will test to see if we have reached the end of the file Working interactively we can use a while or do while and enter <Ctrl> z on a Windows System or <Ctrl> d on a Mac to indicate end of data See HasNextTest.java 52

Bad Input Data There are cases when erroneous data is entered There are many options Request revised data - preferred Exit the program In order to do either you must check the data first Note: Some inputs will cause the program to crash Can you name 0ne? We will learn how to capture error conditions and perform soft exits Look at ErroneousData.java We will look at GeneralAverage.java in a few minutes 53

Scope of a Variable (1) A variable s scope is determined by the highest level of braces within which it is defined. It works at that level and all nested level If you use the same variable name in an outer and nested blocks, an error will occur. In Java you cannot have local variables with the same name in overlapping scope If you exit a block where a variable is defined you can reuse the variable name It s values are separate from the originally named variable Don t use the same variable name twice in a program it only confuses things. (exception may reuse loop counters) You are allowed to continuously redeclare a variable in the same statement within a loop again this allows for nesting Scope is extremely important to understand in nested loops. Once you leave the loop a variable declared in the loop no longer exists. 54

Scope of a Variable (2) // Demonstrate block scope. public class Scope public static void main(string args[]) int n1; // Visible in main n1 = 10; if (n1 == 10) // start new scope int n2 = 20; // visible only to this block // n1 and n2 both visible here. System.out.printf( n1 = %d n2 = %d\n, n1, n2); // n2 = 100; // Error! n2 not known here // n1 is still visible here. System.out.printf("n1 is %d\n, n1); 55

Scope of a Variable (3) public class LifeTime public static void main(string args[]) int i; for(i = 0; i < 3; i++) int y = -1; System.out.printf("y is : %d\n, y); Variable y is declared inside for loop block Each time when control goes inside for loop block the y variable is declared and used in loop When control goes out of the for loop then the variable becomes inaccessible 56

Scope of a Variable (4) public class ScopeInvalid public static void main(string args[]) int num = 1; // creates a new scope int num = 2; // Compile-time error // num already defined public class ScopeValid public static void main(string args[]) // creates a new scope int num = 1; // creates a new scope int num = 2; Okay doesn t overlap with the num in the prior b;ock 57

58

Programming Exercise 1 Sort Three Write a program that requests the entry of three integers and displays the numbers in order from lowest to highest. Note: You will need to test all possible cases 59

Programming Exercise 2 TollFreeNumbers As of the year 2008, a 10 digit number that begins with 800, 888, 877, or 866 has been toll free. Write a program that reads in a 10 digit phone number and displays a message that states whether the number is toll free or not. Hints: Use long as the variable type, extract first three digits with integer arithmetic 60

Programming Exercises 3 GradeConversion A certain school assigns number grades ranging from 0-100. Write a program that queries the user for a numerical score and converts the score to a letter grade according to thee following criteria: 0-59:F; 60-69 D: 70-72, C-: 73-76, C: 77-79 C+; 80-82: B-; 83-86: B; 87-89: B+; 90-92: A-; 93-96: A; 97-100 A+ 61

Programming Exercise 4 GeneralAverage Write a program that calculates the average of n test scores, such that each score is an integer in the range 0 to 100. There should be a minimum of two scores. Your program should first prompt for an integer n and then request n scores. There should be a minimum of two scores. Your program should also test for invalid data. If a user enters a number outside the correct range, the program should prompt for another value. Round the average to the closest integer. 62

Programming Exercise 5 MorePictures Write a program that accepts an integer n and prints out the following picture of a diamond with 2n-1 rows 1 X 2 X X X 3 X X X X X n XXXXXXXXXXX (2n-1 times). 2n-1 X 63

Pseudo Code for More Pictures Read in n to determine total number of rows as 2n-1 Calculate the width = 2*n-1 For each row in top half up from 1 to n Calculate the number of x s (2*rowNumber-1) Calculate the blanks = (width numexes)/2 Print the blanks (a loop) Print the X s (a loop) Skip to next line For each row in the bottom half from n-1 to 1 Calculate the number of x s (2*rowNumber-1) Calculate the blanks = (width numexes)/2 Print the blanks (a loop) Print the x s (a loop) Skip to next line 64