Lectures 3-1, 3-2. Control Structures. Control Structures, Shimon Schocken IDC Herzliya, slide 1

Similar documents
Introduction to Computer Science, Shimon Schocken, IDC Herzliya. Lectures Control Structures

Loops. CSE 114, Computer Science 1 Stony Brook University

Java Coding 3. Over & over again!

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

CMPT 125: Lecture 4 Conditionals and Loops

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

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

CSC 1051 Data Structures and Algorithms I

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

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

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

Chapter 3. Selections

CSC 1051 Data Structures and Algorithms I

10/30/2010. Introduction to Control Statements. The if and if-else Statements (cont.) Principal forms: JAVA CONTROL STATEMENTS SELECTION STATEMENTS

H212 Introduction to Software Systems Honors

Java I/O and Control Structures

Java I/O and Control Structures Algorithms in everyday life

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Program Control Flow

Program Control Flow

Arithmetic Compound Assignment Operators

Expression statements are formed by adding a semicolon to the end of certain types of expressions.

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Date: Dr. Essam Halim

FLOW CONTROL. Author: Boaz Kantor The Interdisciplinary Center, Herzliya Introduction to Computer Science Winter Semester

Midterm Examination (MTA)

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

ITERATION WEEK 4: EXMAPLES IN CLASS

Repetition, Looping. While Loop

For that purpose, java provides control structures that serve to specify what has to be done by our program, when and under which circumstances.

Flow Control. Key Notion. Statement Categories. 28-Oct-10

COMP 202 Java in one week

CS110 Programming Language I. Lab 6: Multiple branching Mechanisms

COSC 123 Computer Creativity. Java Decisions and Loops. Dr. Ramon Lawrence University of British Columbia Okanagan

Chapter 4: Control Structures I

Chapter 4 Loops. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk

Example: Monte Carlo Simulation 1

Conditional Programming

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Flow Control. Boaz Kantor Introduction to Computer Science, Fall semester IDC Herzliya

More on control structures

ECE 122. Engineering Problem Solving with Java

CS212 Midterm. 1. Read the following code fragments and answer the questions.

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

Computer Programming, I. Laboratory Manual. Experiment #6. Loops

Selection and Repetition Revisited

Logic is the anatomy of thought. John Locke ( ) This sentence is false.

Topic 11 Scanner object, conditional execution

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

COMP 202. Java in one week

CSC 1051 Data Structures and Algorithms I

CS111: PROGRAMMING LANGUAGE II

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

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

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Full file at

For that purpose, java provides control structures that serve to specify what has to be done by our program, when and under which circumstances.

Introduction to Computer Science Unit 2. Exercises

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

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

Question: Total Points: Score:

Introduction to Computer Programming

CS111: PROGRAMMING LANGUAGE II

CS 112 Introduction to Programming

Flow of Control of Program Statements CS 112 Introduction to Programming. Basic if Conditional Statement Basic Test: Relational Operators

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137

Programming with Java

++x vs. x++ We will use these notations very often.

Question: Total Points: Score:

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

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

Selection and Repetition Revisited

AP COMPUTER SCIENCE A

New York University Introduction to Computer Science Exam Sample Problems 2013 Andrew I. Case. Instructions:

Scanner Objects. Zheng-Liang Lu Java Programming 82 / 133

STUDENT LESSON A12 Iterations

IEEE Floating-Point Representation 1

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

CompSci 125 Lecture 11

Over and Over Again GEEN163

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to write programs for executing statements repeatedly using a while, do while and for loop

Selection Statements and operators

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Simple Control Flow: if-else statements

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

COMP 202. Programming With Iterations. CONTENT: The WHILE, DO and FOR Statements. COMP Loops 1

Loops and Expression Types

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

Following is the general form of a typical decision making structure found in most of the programming languages:

Key Points. COSC 123 Computer Creativity. Java Decisions and Loops. Making Decisions Performing Comparisons. Making Decisions

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn

Control Structures: if and while A C S L E C T U R E 4

Building Java Programs

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Building Java Programs

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Full file at

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Chapter 3 Selections. 3.1 Introduction. 3.2 boolean Data Type

Transcription:

Introduction to Computer Science Shimon Schocken IDC Herzliya Lectures 3-1, 3-2 Control Structures Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 1 Shorthand operators (increment / decrement) k++ k++ Is equivalent to k k + 1 k-- k-- Is equivalent to k k - 1 k must be a numeric variable. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 2

Shorthand operators (increment / decrement) int int k 10, 10, n 0; 0; k k + 1; 1; // // k11 k11 k++; k++; // // k12 k12 ++k; ++k; // // k13 k13 n k++; k++; // // k14, k14, n13 n13 n ++k ++k // // k15, k15, n15 n15 The rules of the game: Expressions Operation Value Of expression count++ ++count count-- --count add 1 add 1 subtract 1 subtract 1 old value new value old value new value sum sum 50 50 System.out.println(sum +" +" "+ "+ sum++ sum++ +" +" "+ "+ ++sum ++sum +" +" "+ "+ sum sum +" +" "+ "+ sum-- sum-- +" +" "+ "+ sum) sum) What will it print? Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 3 Shorthand operators (assignment) Often we perform an operation on a variable, and then assign the result to the same variable. Example: sum + x sum sum sum sum + x is equivalent to: sum sum + + x The rules of the game: Operation Equivalent to x + y x x + y x - y x x - y x * y x x * y x / y x x / y x % y x x % y The right hand side, which can be a complex expression, is evaluated first, and then combined with the rest of the assignment: x / / x - y is equivalent to: x x / (x (x - y) y) Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 4

Control structures A program is a sequence of statements. On the right we see the same program, in two separate runs In each run some statements execute (the underlined ones); the other statements are skipped In order to affect such different flows of execution, we need programming mechanisms that tell the computer to branch to different code segments. Run(input1) s0 s0 s1 s1 s2 s2 s3 s3 s4 s4 s5 s5 s6 s6 s7 s7 s8 s8 s9 s9...... Run(input2) s0 s0 s1 s1 s2 s2 s3 s3 s4 s4 s5 s5 s6 s6 s7 s7 s8 s8 s9 s9...... Low level programming languages affect branching using GOTO statements High level programming languages affect branching using high-level abstractions like if, while, switch, and so on Taken together, these statements are called control structures. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 5 Control structures: lecture outline If Boolean expressions and variables While switch do for Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 6

The if statement (example) System.out.println("Enter your your age:"); age:"); int int age age scan.nextint(); if if (age (age < AGELIMIT) AGELIMIT) System.out.println("Sorry, " + age age + " is is under under the the allowed allowed age."); age."); // // Code Code continues continues...... The body of the IF can be either a single statement or a a block of statements: if if (age (age < AGELIMIT) AGELIMIT) { System.out.println("Sorry, " + age age + " is is under under the the allowed allowed age."); age."); System.out.println("Try again again when when you you are are old old enough."); enough."); // // Code Code continues continues...... Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 7 The if statement Syntax: if if (condition) conditional code code if: the most basic branching mechanism Condition: a Boolean expression that evaluates to either or The condition s value determines which branch to take (Beautiful flow chart images from http://articles.sitepoint.com/article/mysql-3-getting-started-php/3) Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 8

The if else statement (example) System.out.println("Enter your your age:"); age:"); int int age age scan.nextint(); if if (age (age < AGELIMIT) AGELIMIT) System.out.println("Sorry, you you are are under under the the allowed allowed age."); age."); else else System.out.println("Welcome! Wait Wait while while the the game game is is loading loading...");..."); // // code code continues continues...... Compare to: // // bug bug System.out.println("Enter your your age:"); age:"); int int age age scan.nextint(); if if (age (age < AGELIMIT) AGELIMIT) System.out.println("Sorry, you you are are under under the the allowed allowed age."); age."); System.out.println("Welcome! Wait Wait while while the the game game is is loading loading...");..."); Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 9 The if else statement Syntax: if if (condition) if if code code else else else else code code Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 10

Nested if (example) System.out.println("Enter your your age:"); age:"); int int age age scan.nextint(); if if (age (age < AGELIMIT) AGELIMIT) System.out.println("Sorry, you you are are under under the the allowed allowed age."); age."); else else { System.out.println("Enter your your credit credit card:"); card:"); int int cardnumber cardnumber scan.nextint(); if ifverify(cardnumber) // // calling calling a Boolean Boolean method method System.out.println("Welcome!...");..."); else else System.out.println("Sorry, bad bad card"); card"); Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 11 Nested if (example) // // Reads Reads two two integers integers and and compares compares them them import import java.util.scanner; class class Compare2Numbers { public public static static void void main(string[] args) args) { Scanner Scanner scan scan new new Scanner(System.in); The nesting can go as deep as you want Use with caution: telescoped code is hard to read and comprehend. System.out.print("Enter a number:"); number:"); int int a scan.nextint(); System.out.print("Enter another another number"); number"); int int b scan.nextint(); What s the difference if if (a (a!! b) b) between these if if (a (a > b) b) System.out.println(a + " is is greater"); two solutions? greater"); else else System.out.println(b + " is is greater"); greater"); else else System.out.println("the numbers numbers are are equal"); equal"); if if (a (a > b) b) System.out.println(a + " is is greater"); greater"); if if (a (a < b) b) System.out.println(b + " is is greater"); greater"); if if (a (a b) b) System.out.println("the numbers numbers are are equal"); equal"); Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 12

Example: using if to validate inputs Whenever we request users to enter inputs, we must assume that an invalid value can be entered Valid / invalid: according to the application s requirements. True / Conditions System.out.println("Enter number number of of items:") items:") are expressed as int int n scan.nextint(); Boolean expressions if if (n (n < 0) 0) System.out.println("Number of of items items must must be be non-negative!"); else else { double double total total n * ITEM_PRICE; System.out.println("The total total price price is:" is:" + total); total); // // Code Code continues continues That s a naïve solution to input validation. Can you see why? Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 13 Control structures: lecture outline If Boolean expressions and variables While switch do for Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 14

Control structures are based on evaluating some condition: if if ( (age (age > > 21) 21) && &&(driverlicenseisvalid() ) // // allow allow car car rental rental condition Where do these conditions come from? Algorithmic needs Requirements analysis Only Only drivers drivers older older than than 21 21 can can rent rent a a car car Continue Continue the the loop loop until until Math.abs(r-x*x) < < epsilon epsilon If If the the package package weights weights more more than than 10 10 kg kg or or the the shipping shipping distance distance is is more more than than 100 100 km km we we charge charge 10% 10% extra extra (ambiguous (ambiguous ) ) Three Three numbers numbers x, x, y, y, z are are said said to to be be Pythagorean Pythagorean if if x 2 2 + + yy 2 2 z 2 2 Such statements are expressed in computer programs as Boolean expressions. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 15 Boolean expressions in action // // Some Some electronic electronic commerce commerce application: if if ((weight ((weight < 10) 10) && &&(destination USA")) USA")) shippingcost 0 else else shippingcost weight weight * COST_PER_POUND; if if ( (x (x < 0) 0) (x (x > 100) 100) ) System.out.println( x must must be be between between 0 and and 100 ); 100 ); // // Logically Logically equivalent equivalent to: to: if if (!((x!((x > > 0) 0) && &&(x (x < < 100)) 100)) ) System.out.println( x must must be be between between 0 and and 100 ); 100 ); Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 16

Boolean expressions anatomy Conditional operator ( (weight (weight < 10) 10) && &&(destination USA") USA")) Relational operator Relational operator A relational operator computes a Boolean function on it s operand(s) and returns or A conditional operator computes a Boolean operation on it s Boolean operand(s) and returns or. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 17 Relational operators Operator! < < > > Meaning equal to not equal to less than less than or equal to greater than greater than or equal to Examples: age age > 18 18 city city "LA" "LA" x!! 100 100 gpa gpa < < 3.75 3.75 tailisdown() bob.bandwidth > alice. alice. bandwidth bandwidth Each operator operates on two operands and returns a Boolean value Called relational operators since they test how the operands relate to each other Return a Boolean value. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 18

Conditional operators Boolean expressions can be combined using conditional operators, of which Java offers three: Examples: Operator! && Operation Logical not Logical and Logical or!(tailisdown() ) )! tailisdown() tailisdown() && &&(n (n < 100) 100) (city (city Tel Tel Aviv ) Aviv ) (city (city Haifa ) Haifa )!dubim!dubim&& &&!yaar Each operator operates on one or two Boolean operands and returns a Boolean result. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 19 Truth tables NOT (!) a!a A truth table shows the output of a Boolean function for every possible input The truth table can be viewed as the definition of the Boolean function. AND (&&) OR ( ) a b a && b a b a b!a is if a is and otherwise (a && b) is if both a and b are and otherwise (a b) is if either a or b or both are and otherwise. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 20

Boolean expressions and Boolean variables in action Boolean expressions can be made as complex as necessary: if if (!((a (!((a > 0) 0) && &&((a ((a% 2) 2) 0))) 0))) System.out.println("The input input must must be be a positive positive even even number!"); number!"); // // Determines Determines if if a given given triangle triangle is is right. right. class class RightTriangle { public public static static void void main(string[] args) args) { // // Get Get the the triangle s triangle s three three edges edges a,b,c a,b,c (omitted) (omitted) boolean boolean righttriangle (a*a (a*a + b*b b*b c*c) c*c) (a*a (a*a + c*c c*c b*b) b*b) (b*b (b*b + c*c c*c a*a); a*a); if if (righttriangle) System.out.println("It s a right right triangle"); else else System.out.println("It s not not a right right triangle"); Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 21 The conditional operator: a shorthand if/else mechanism Example int int max max (a (a > b) b)? a : b; b; Equivalent to: int int max; max; if if (a (a > b) b) max max a; a; else else max max b; b; Syntax condition condition? expression1 expression1 : expression2 expression2 ; If the condition is, the expression returns the value of expression1; else, the expression returns the value of expression2 Similar to an if/else statement However, the conditional is not a statement; it s an expression that can returns a value Example Systems.out.println("Thanks! you you bought bought + count count + ((count ((count 1) 1)? "item" "item": "items"); "items"); Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 22

Control structures: lecture outline If Boolean expressions and variables While switch do for Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 23 Example // // Counts Counts from from 1 to to n int int count count 0; 0; while while (count (count < n) n) { System.out.println(count); count++; count++; count count + 1; 1; What will the program print when... n 5? n 1? n 0? n -3? Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 24

The while statement Syntax: while while (condition) conditional code code A while loop executes zero or more times. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 25 Example: factors // // Prints Prints the the factors factors of of a given given integer integer public public static static void void main main (String (String args[]) args[]) { Scanner Scanner scan scan new new Scanner(System.in); System.out.print("Enter a number: number: "); "); int int n scan.nextint(); System.out.println("The divisors divisors of of " + n + " are:"); are:"); int int i 1; 1; while while (i (i < < n) n) { if if (n (n% i 0) 0) System.out.println(i); i++; i++; Output: Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 26

Example: input testing public public static static void void main main (String (String args[]) args[]) { final final int int ITEM_PRICE ITEM_PRICE 100; 100; Scanner Scanner scan scan new new Scanner(System.in); // // Gets Gets an an input input and and makes makes sure sure it s it s non-negative System.out.print("Enter number number of of items: items: "); "); int int n scan.nextint(); while while (n (n < < 0) 0) { System.out.println("Number of of items items must must be be positive!"); System.out.print("Enter number number of of items: items: "); "); n scan.nextint(); System.out.println("The total total price price is: is: " + (n (n* ITEM_PRICE)); Output: This code is bullet-proof : there is no way to enter an invalid input. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 27 Example: palindrome tester radar kayak import import java.util.scanner; drab bard able was I ere I saw elba public public class class PalindromeTester { public public static static void void main main (String[] (String[] args) args) { Dennis and Edna sinned Rise to vote, sir Scanner Scanner scan scan new new Scanner Scanner (System.in); Doom an evil deed, liven a mood System.out.print("Enter some some text: text: "); "); String String txt txt scan.nextline(); Go hang a salami; I m a lasagna hog A man, a plan, a canal, Panama int int left left 0; 0; int int right right txt.length() - 1; 1; while while (txt.charat(left) txt.charat(right) && && left left < right) right) { left++; left++; // // shorthand shorthand notation notation for for left left left left + 1; 1; right--; right--; // // shorthand shorthand notation notation for for right right right right - 1; 1; if if (left (left < right) right) System.out.println ("The ("The text text is is NOT NOT a palindrome."); else else System.out.println ("The ("The text text IS IS a palindrome."); Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 28

Control structures: lecture outline If Boolean expressions and variables While switch do for Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 29 The switch statement Syntax switch switchexpression { value 1 : 1 statement statement 1 1 value 2 : 2 statement statement 2 2...... default: default: statement statement The expression value is compared to each value; if there s a match, the corresponding statement is executed If none of the values matches, the default statement is executed default is optional The types of the expression and the values must be either integral or character The flow of control falls through all the s, even after a match; Can be terminated with the break keyword. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 30

Example (typical ATM application) final final int int WITHDRAWAL WITHDRAWAL 1; 1; final final int int DEPOSIT DEPOSIT 2; 2; final final int int BALANCE BALANCE 3; 3; // //... // // The The user user selects selects some some banking banking operation, operation, which which is is represented in in // // this this program program by by an an int int variable variable named named operation that that can can be be // // either either 1, 1, 2, 2, or or 3. 3. switch switch (operation) { WITHDRAWAL: dowithdrawal(); BALANCE: BALANCE: showbalance(); DEPOSIT: DEPOSIT: dodeposit(); Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 31 Example (from the Java tutorials) // // Returns Returns the the number number of of days days for for a a given given month month / / year year switch switch (month) (month) { { 1: 1: 3: 3: 5: 5: 7: 7: 8: 8: 10: 10: 12: 12: numdays numdays 31; 31; break; break; 4: 4: 6: 6: 9: 9: 11: 11: numdays numdays 30; 30; break; break; 2: 2: if if ( ( ((year ((year % % 4 4 0) 0) && &&!(year!(year % % 100 100 0)) 0)) (year (year % % 400 400 0) 0) ) ) numdays numdays 29; 29; else else numdays numdays 28; 28; break; break; default: default: System.out.println("Invalid System.out.println("Invalid month."); month."); break; break; Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 32

Control structures: lecture outline If Boolean expressions and variables While switch do for Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 33 The do statement Syntax: do do conditional conditional code code while while (condition); (condition); conditional code condition Similar to while, except that the condition evaluates at the end of the loop while loop executes 0 or more times do loop executes 1 or more times. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 34

Example // // Prints Prints the the powers powers of of 2 up up to to a limit limit...... // // Get Get the the value value of of limit limit somehow somehow...... int int n 1; 1; do do { n n * 2; 2; System.out.println("Next power power of of 2: 2: " + n); n); while while (n (n < < limit); limit); Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 35 The for statement Syntax: for for (initialization ; condition condition ; increment) increment) conditional code; code; Equivalent to: initialization while while condition condition { statement; statement; increment; increment; Many loops have this common pattern Comes to play when the number of iterations is known in advance. Example: for for (int (intcount 0; 0; count count < < 10; 10; count++) count++) { System.out.println (count); (count); Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 36

Example Prints the powers of 2 up to a limit for(int for(int n 1; 1; n < < limit; limit; n n * 2) 2) { System.out.println("Next power power of of 2: 2: " + n); n); Equivalent to: do do { n n * 2; 2; System.out.println("Next power power of of 2: 2: " + n); n); while while (n (n < < limit); limit); for yields tighter and clearer code than do and while, and is preferred when suitable. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 37 The for statement for loop without initialization for for (; ( (; condition condition ; increment increment ) statement; statement; Any one of the three expressions in the for header is optional The two semicolons are always required. for loop without increment: for for ( initialization; condition condition ;) ;) statement; statement; Example: for for (;;) (;;){ // // an an infinite infinite loop loop System.out.println ("beep"); ("beep"); Infinite for loop: for for ( initialization;; increment increment ) statement; statement; Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 38

Example // // 10 10 by by 10 10 multiplication table table class classmultiplicationtable { public public static static void voidmain(string[] args) args) { for(int for(int j 1 ; j < < 10 10 ; j++) j++) { for(int for(int k 1 ; k < < 10 10 ; k++) k++) System.out.print(j * k); k); System.out.println(); Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 39 break and continue break can be used to terminate a loop; Execution continues after the loop s end continue can be used to terminate the current iteration; Execution continues by jumping to evaluate the loop s condition // // Reads Reads a a series series of of positive positive numbers numbers from from the the user, user, until until // // 0 0 is is read. read. Computes Computes and and prints prints the the series' series' average. average. class class Average Average { { public public static static void void main(string[] main(string[] args){ args){ Scanner Scanner scan scan new new Scanner(System.in); Scanner(System.in); int int x, x, sum sum 0; 0; count count 0; 0; while() while() { { System.out.print("Enter System.out.print("Enter a a positive positive number: ); number: ); x x scan.nextint(); scan.nextint(); if if (x (x 0) 0) break; break; if if (x (x < < 0) 0) { { System.out.println( Only System.out.println( Only positive positive numbers! ); numbers! ); continue; continue; sum sum + + x; x; count++; count++; System.out.println( The System.out.println( The average average is is + + (sum/count)); (sum/count)); Ugly code... Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 40

ERROR: undefined OFFENDING COMMAND: STACK: