The break and continue statements. Introduction There are 2 special statements that can affect the execution of loop statements (such as a while-statement)

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Numeric literals and named constants. Numeric literals Numeric literal: Example: A numeric literal is a constant value that appears in a Java program.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Nested conditional statements. Previously discussed Conditional statements discussed so far: Syntax of the if-statement: if-statement if-else-statement.
The switch statement: an N-way selection statement.
Writing algorithms using the while-statement. Previously discussed Syntax of while-statement:
Writing algorithms using the for-statement. Programming example 1: find all divisors of a number We have seen a program using a while-statement to solve.
Programming a computer. What does programming a computer mean ? Programming a computer: Since a computer can only execute machine instructions (encoded.
While Loops and Do Loops. Suppose you wanted to repeat the same code over and over again? System.out.println(“text”); System.out.println(“text”); System.out.println(“text”);
The for-statement. Different loop-statements in Java Java provides 3 types of loop-statements: 1. The for-statement 2. The while-statement 3. The do-while-statement.
JAVA Control Structures: Repetition. Objectives Be able to use a loop to implement a repetitive algorithm Practice, Practice, Practice... Reinforce the.
Shorthand operators.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
The character data type char
 The pool rack example could be implemented using a for loop.  It is also possible to write recursive methods that accomplish things that you might.
1 Introduction to Java Brief history of Java Sample Java Program Compiling & Executing Reading: => Section 1.1.
The string data type String. String (in general) A string is a sequence of characters enclosed between the double quotes "..." Example: Each character.
Chapter 6: Iteration Part 1. To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
The Rectangle Method. Introduction Definite integral (High School material): A definite integral a ∫ b f(x) dx is the integral of a function f(x) with.
Parameter passing mechanism: pass-by-value. Introduction In the last webpage, we discussed how to pass information to a method I have kept it (deliberately)
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
The dangling-else ambiguity. Previously discussed The Java compiler (translator) consider white space characters (i.e., SPACE, TAB and New line) as insignificant.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
1 Debugging. 2 A Lot of Time is Spent Debugging Programs Debugging. Cyclic process of editing, compiling, and fixing errors. n Always a logical explanation.
Floating point numerical information. Previously discussed Recall that: A byte is a memory cell consisting of 8 switches and can store a binary number.
What does a computer program look like: a general overview.
The scope of local variables. Murphy's Law The famous Murphy's Law says: Anything that can possibly go wrong, does. (Wikipedia page on Murphy's Law:
Boolean expressions, part 2: Logical operators. Previously discussed Recall that there are 2 types of operators that return a boolean result (true or.
CSI 1390: Introduction to Computers TA: Tapu Kumar Ghose Office: STE 5014 Office hours: Thursday 1300 – 1400hrs.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
Loops (While and For) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Working with arrays (we will use an array of double as example)
Introduction to programming in the Java programming language.
Assignment statements using the same variable in LHS and RHS.
1 while loops. 2 Definite loops definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. We.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 18 Recursion Lecture 6 Dr. Musab.
The if-else statement. The if-else statement in Java The if-else statement is the second conditional statement in Java The if-else statement selects one.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Mixing integer and floating point numbers in an arithmetic operation.
Chapter 5: Control Structures II
Introduction to Methods. Previously discussed There are similarities in make up of that can help you remember the construct of a class a class in the.
The Bisection Method. Introduction Bisection Method: Bisection Method = a numerical method in Mathematics to find a root of a given function.
Integer numerical data types. The integer data types (multiple !) The integer data types use the binary number system as encoding method There are a number.
Using the while-statement to process data files. General procedure to access a data file General procedure in computer programming to read data from a.
The while-statement. Syntax and meaning of the while-statement The LOOP-CONTINUATION-CONDITION is a Boolean expression (exactly the same as in the condition.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
The assignment expressions. The assignment operator in an assignment statement We have seen the assignment statement: Effect: var = expr; Stores the value.
The while-statement. The loop statements in Java What is a loop-statement: A loop-statement is a statement that repeatedly executes statements contained.
Arithmetic expressions containing Mathematical functions.
CSI 1390: Introduction to Computers TA: Tapu Kumar Ghose Office: STE 5014 Office hours: Thursday 1300 – 1400hrs.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Reading input from the console input. Java's console input The console is the terminal window that is running the Java program I.e., that's the terminal.
Introduction to array: why use arrays ?. Motivational example Problem: Write a program that reads in and stores away 5 double numbers After reading in.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Working with floating point expressions. Arithmetic expressions Using the arithmetic operators: and brackets (... ), we can construct arithmetic expression.
Boolean expressions, part 1: Compare operators. Compare operators Compare operators compare 2 numerical values and return a Boolean (logical) value A.
Simple algorithms on an array - compute sum and min.
The ++ and -- expressions. The ++ and -- operators You guessed it: The ++ and -- are operators that return a value.
The if-else statement. Introducing the if-else statement Programming problem: Re-write the a,b,c-formula program to solve for complex number solutions.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
Slides by Evan Gallagher
Slides by Evan Gallagher
Chapter 5: Control Structures II
Repetition-Counter control Loop
TK1114 Computer Programming
The Boolean (logical) data type boolean
The for-statement.
Presentation transcript:

The break and continue statements

Introduction There are 2 special statements that can affect the execution of loop statements (such as a while-statement) The special statements are: We will study their meaning and how to use these special statements inside the while-statement break continue

The break statement Syntax: Effect: break ; When the break statement is executed inside a loop- statement, the loop-statement is terminated immediately The execution of the program will continue with the statement following the loop-statement

The break statement (cont.) Schematically:

Programming example using the break statement: find the GCD Problem description: Write a Java program that reads in 2 numbers x and y... and prints the largest common divisor of both x and y

Programming example using the break statement: find the GCD (cont.) A concrete example: Input: x = 24 and y = 16 Output: 8

Programming example using the break statement: find the GCD (cont.) What would you do to solve this problem ? Suppose: x = 24 and y = 16 The lesser of the values is 16 Therefore, all divisors are ≤ 16

Programming example using the break statement: find the GCD (cont.) Check if 16 and 24 are divisible by 16: no Check if 16 and 24 are divisible by 15: no... Check if 16 and 24 are divisible by 10: no Check if 16 and 24 are divisible by 9: no Check if 16 and 24 are divisible by 8: YES Print 8 and STOP

Programming example using the break statement: find the GCD (cont.) Rough algorithm: input x, y; min = min(x, y); // this is the range of the brute force search for every value a = {min, min-1, min-2,..., 1} do { if (x and y are divisible by a) { print a; exit the while loop !!! }

Programming example using the break statement: find the GCD (cont.) Algorithm (structured diagram):

Programming example using the break statement: find the GCD (cont.) Java program: import java.util.Scanner; public class GCD01 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int x, y, a, min = 0; x = in.nextInt(); // Read in number y = in.nextInt(); // Read in number if ( x < y ) min = x; else min = y;

Programming example using the break statement: find the GCD (cont.) a = min; while ( a >= 1 ) // Run a = min(x,y), min(x,y)-1,..., 1 { if ( x % a == 0 && y % a == 0 ) { // a is a divisor of x and y System.out.println(a); // Print a (because it's a common divisor) break; // Exit while loop !!! (Only need the largest) } else { a--; // Move to the next number !! }

Programming example using the break statement: find the GCD (cont.) Example Program: (Demo above code) –Prog file: GCD01.java How to run the program: Right click on link and save in a scratch directory To compile: javac GCD01.java To run: java GCD01

The continue statement Syntax: continue;

The continue statement (cont.) Effect: When the continue statement is executed inside a loop- statement, the program will skip over the remainder of the loop-body to the end of the loop Note: What happens next when the program reaches the end of a loop depends on the type of loop statement !!!

The continue statement (cont.) Effect of a continue statement in a while-loop: As given previously: In the case of a while-loop, when the program reaches end of the loop, the program will jump back to the testing of the loop-continuation-condition the program will skip over the remainder of the loop-body to the end of the loop

The continue statement (cont.) Schematically:

Programming example using the continue statement: find all divisors of a number Problem description: Write a Java program that reads in an integer n... and prints all its divisors

Programming example using the continue statement: find all divisors of a number (cont.) Previously discussed solution: We try every number a = 1, 2,..., n For each number a, we check if n % a == 0.

Programming example using the continue statement: find all divisors of a number (cont.) We can re-write the same algorithm differently using a continue statement as follows:

Programming example using the continue statement: find all divisors of a number (cont.) Notice that the if-condition has been changed to x % a != 0, meaning: a is not a divisor of x When a is not a divisor of x, (the then-part), we increment a (to try next number) and jump to the end of the while- loop using the continue statement. When x % a != 0 is false, the program will print a and increment a (to try next number)

Programming example using the continue statement: find all divisors of a number (cont.) Java program: public class Continue01 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n, a; n = in.nextInt(); // Read in number a = 1;

Programming example using the continue statement: find all divisors of a number (cont.) while ( a <= n ) // Run a = 1, 2,..., n { if ( n % a != 0 ) { // a is NOT a divisor of n a++; continue; // Jump to end of while loop } /* We reach here ONLY when "n % a != 0" is FALSE I.e.: a is a divisor of x */ System.out.println(a); // Print a (because it's a divisor) a++; // Make sure we more to the next number !! // or else: infinite loop !!! }

Programming example using the continue statement: find all divisors of a number (cont.) Example Program: (Demo above code) –Prog file: Continue01.java How to run the program: Right click on link and save in a scratch directory To compile: javac Continue01.java To run: java Continue01

Programming advice Good programming practice: A computer program will be easier to understand if it is transparent. One way to improve transparency is a consistent flow of control Meaning, the program always take the same path of execution The break and the continue commands will alter the flow of control Therefore, they make a computer program less transparent It is a general recommendation to avoid using break and continue statements when you can write the algorithm easily without them.