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

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

CMPT 125: Lecture 4 Conditionals and Loops

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

Loops. CSE 114, Computer Science 1 Stony Brook University

Java Coding 3. Over & over again!

Chapter 3. Selections

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

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

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

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

Chapter 4: Control Structures I

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

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

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

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

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

Chapter 3: Operators, Expressions and Type Conversion

Introduction to Computer Science Unit 2. Exercises

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

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

CSC 1051 Data Structures and Algorithms I

H212 Introduction to Software Systems Honors

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

More on control structures

JAVA OPERATORS GENERAL

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

CSC 1051 Data Structures and Algorithms I

COMP 202 Java in one week

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

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

Programming with Java

Object-Oriented Programming in Java

Repetition, Looping. While Loop

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Java I/O and Control Structures

Date: Dr. Essam Halim

Conditional Programming

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

Arithmetic Compound Assignment Operators

COMP 202. Java in one week

ECE 122. Engineering Problem Solving with Java

ITERATION WEEK 4: EXMAPLES IN CLASS

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

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

Selection and Repetition Revisited

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

Object Oriented Programming Lecture (2.1) Supervisor Ebtsam AbdelHakam Department of Computer Science Najran University

Loops and Expression Types

Java I/O and Control Structures Algorithms in everyday life

CSC 1051 Data Structures and Algorithms I

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

Question: Total Points: Score:

Program Control Flow

Program Control Flow

In this chapter, you will:

bitwise inclusive OR Logical logical AND && logical OR Ternary ternary? : Assignment assignment = += -= *= /= %= &= ^= = <<= >>= >>>=

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

Midterm Examination (MTA)

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

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

Prof. Navrati Saxena TA: Rochak Sachan

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

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

IEEE Floating-Point Representation 1

Topic 11 Scanner object, conditional execution

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

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

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

Conditionals and Loops Chapter 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Algorithms and Conditionals

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

Data Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87

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

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

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

Selection and Repetition Revisited

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

Selection Statements and operators

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

Object-Oriented Programming

Handout 5 cs180 - Programming Fundamentals Spring 15 Page 1 of 8. Handout 5. Loops.

Operators in java Operator operands.

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

AP COMPUTER SCIENCE A

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

Bjarne Stroustrup. creator of C++

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

More Programming Constructs -- Introduction

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

Chapter 3 Selections. 3.1 Introduction. 3.2 boolean Data Type

CMPS 11 Introduction to Programming Midterm 1 Review Problems

Selenium Class 9 - Java Operators

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

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

Lecture 1 Java SE Programming

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

Selection Statements and operators

Building Java Programs

Building Java Programs

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 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 2

Control structures: lecture outline Boolean expressions and variables The IF statement The conditional The WHILE statement The SWITCH statement The DO statement The FOR statement Shorthand operators Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 3 The IF statement (example) import import java.util.scanner; class class AgeCheck AgeCheck { static static final final int int AGELIMIT AGELIMIT = 18; 18; public public static static void void main(string[] args) args) { Scanner Scanner scan scan = new new Scanner(System.in); 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."); Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 4

The IF statement Syntax: if if (condition) statement statement condition statement IF: the most basic branching mechanism The condition s value determines which branch to take Condition: a Boolean expression that evaluates to either TRUE or FALSE. Syntax convention: Throughout the slides in this lecture, statement stands for either a single statement or a block of statements, grouped by curly brackets. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 5 The IF / ELSE statement (example) import import java.util.scanner; class class AgeCheck2 AgeCheck2 { static static final final int int AGELIMIT AGELIMIT = 18; 18; public public static static void void main(string[] args) args) { Scanner Scanner scan scan = new new Scanner(System.in); 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...");..."); Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 6

The IF / ELSE statement Syntax: if if (condition) statement1 statement1 else else statement2 statement2 statement1 condition statement2 Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 7 Nested IF (example 1) 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 = scan.nextint(); if if (cardnumber > 0) 0) // // (simulating a more more elaborate elaborate CC CC test) test) System.out.println("Welcome!...");..."); else else System.out.println("Sorry, bad bad card"); card"); Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 8

Nested IF (example 2) // // 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); System.out.print("Enter a number:"); int int a = scan.nextint(); System.out.print("Enter another another number"); number"); int int b = scan.nextint(); if if (a (a!=!= b) b) if if (a (a > b) b) System.out.println(a + " is is greater"); else else System.out.println(b + " is is greater"); else else System.out.println("the numbers numbers are are equal"); equal"); Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 9 Nested IF Syntax: if if (condition1) if if (condition2) statement statement if if (condition1) statement1 statement1 else else if if (condition2) statement2 statement2 if if (condition1) statement1 statement1 else else if if (condition2) statement2 statement2 else else if if (condition3) statement3 statement3 // // etc. etc. The nesting can go as deep as you want Use with caution: telescoped code is hard to read and comprehend. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 10

Example: using IF to validate inputs Whenever we request a user to enter some input, we must assume that an invalid value can be entered Valid / invalid: according to the application s requirements. System.out.println("Enter number number of of items:") items:") int int n = scan.nextint(); if if (n (n < 0) 0) { System.out.println("Number of of items items must must be be positive!"); else else { double double total total = n * ITEM_PRICE; System.out.println("The total total price price is:" is:" + total); total); This code is asking for trouble. Can you see why? Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 11 Control structures: lecture outline Boolean expressions and variables The IF statement The conditional The WHILE statement The SWITCH statement The DO statement The FOR statement Shorthand operators Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 12

Control structures are always based on evaluating some condition: if if ((age ((age > 18) 18) && && (city (city == == "LA")) "LA")) // // accept accept application condition Where do these conditions come from? Algorithmic needs Requirements analysis We We accept accept applications applications from from LA LA residents residents older older than than 18 18 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 if if x 2 2 + + yy 2 2 = = z 2 2 Such statements can be expressed in computer programs as Boolean expressions. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 13 Boolean expressions We accept applications from LA residents older than 18 if if ((age ((age > 18) 18) && && (city (city == == "LA")) "LA")) // // accept accept application condition Boolean expressions anatomy: (age > 18) && && (city == == "LA") George Boole, 1815-1864 ( A Calculus of Logic ) Relational operator Boolean operator Relational operator Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 14

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 Each operator operates on two operands 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 15 Logical (Boolean) operators Boolean expressions can be combined using logical operators Java offers three logical operators: Operator! && Operation Logical NOT Logical AND Logical OR Each operator takes a Boolean operand and returns a Boolean result Logical NOT is unary (takes one operand); Logical AND and logical OR are binary (two operands). Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 16

Truth tables NOT (!) a!a Boolean expressions are functions taking inputs and returning outputs A truth table shows the output of the Boolean expression for every possible input The truth table can be viewed as the definition of the logical operator. 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 17 Complex Boolean expressions Boolean expressions can be combined using logical operators, creating more complex expressions: if if (a<1 (a<1 a%2!=0) a%2!=0) System.out.println("The input input must must be be a positive positive even even number!"); The result of any Boolean expression can be calculated using a truth table: a<1 a%2!= 0 a<1 a%2=0 Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 18

Boolean variables Boolean expressions can be assigned to Boolean variables: // // x must must be be between between 0 and and 100 100 boolean boolean b, b, c; c; b = (x (x >= >= 0); 0); // // if if x >= >= 0 c = b && && (x (x <= <= 100); 100); // // if if (x (x >= >= 0) 0) AND AND (x (x <= <= 100) 100) if if (c) (c) System.out.println("x is is in in range"); range"); Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 19 Example // // 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 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 20

The conditional operator: a shorthand IF/ELSE mechanism Example int int max max = (a (a > b) b)? a : b; b; Syntax condition condition? expression1 : expression2 ; The conditional is a ternary operator, requiring 3 operands Similar to an IF/ELSE statement; However, the conditional is not a statement, but an expression that returns a value If the condition is, the expression returns the value of expression1; else, the expression returns the value of expression2; Example Systems.out.println("Thanks! you you bought bought + count count + ((count==1)? "item" "item" : "items"); "items"); Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 21 Control structures: lecture outline Boolean expressions and variables The IF statement The conditional The WHILE statement The SWITCH statement The DO statement The FOR statement Shorthand operators Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 22

The WHILE statement Syntax: while while (condition) statement statement condition statement A while loop executes zero or more times. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 23 Example: counting...... // // Counts Counts from from 1 to to n. n. System.out.print("Enter a number"); number"); n = scan.nextint(); int int count count = 1; 1; while while (count (count <= <= n) n) { System.out.println(count); count count = count count + 1; 1; System.out.println("done");...... Simulate the program: 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

Example: factors...... // // Gets Gets an an integer integer and and prints prints its its factors factors System.out.print("Enter a number"); number"); 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 + 1; 1; Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 25 Using WHILE to validate inputs // // Get Get the the number number of of items items and and make make 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:") int int n = scan.nextint(); System.out.println("The total total price price is:" is:" + (n (n * ITEM_PRICE)); This code is bullet-proof : there is no way to enter an invalid input. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 26

PalindromeTester 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 (str.charat(left) == == str.charat(right) && && left left < right) right) { left++; left++; right--; right--; 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 27 Control structures: lecture outline Boolean expressions and variables The IF statement The conditional The WHILE statement The SWITCH statement The DO statement The FOR statement Shorthand operators Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 28

The SWITCH statement Syntax switch switchexpression { case casevalue1 : statement1 statement1 case casevalue2 : statement2 statement2..... default default : statement statement statementi refers to one or more statements The default part is optional The expression value is compared to each case value; if there is a match, the corresponding statement is executed If none of the values matches, the default statement is executed The expression and the values must be integral values, e.g. either integer or character. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 29 SWITCH Example import import java.util.scanner; // // ATM ATM user user selection selection logic logic public public class class ATMlogic ATMlogic { public public static static final final int int VIEW_BALANCE = 1; 1; public public static static final final int int VIEW_SAVINGS = 2; 2; public public static static final final int int CASH_TRANSFER = 3; 3; // //...... // // Inside Inside the the program s program s main main loop: loop: Scanner Scanner scan scan = new new Scanner(System.in); System.out.print("Enter your your choice:"); int int option option = scan.nextint(); BREAK can be used to shortcut execution and transfer control to the end of the SWITCH SWITCH is equivalent to a nested IF/ELSE. switch switch (option) (option) { case case VIEW_BALANCE: showbalance(); break; break; case case VIEW_SAVINGS: showsavings(); break; break; // // Etc. Etc. default: default: System.out.println( No such such option! );...... Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 30

Control structures: lecture outline Boolean expressions and variables The IF statement The conditional The WHILE statement The SWITCH statement The DO statement The FOR statement Shorthand operators Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 31 The DO statement Syntax: do do statement statement while while (condition); statement 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 32

Example: powers of 2 import import java.util.scanner; // // Prints Prints the the powers powers of of 2 up up to to a limit limit class class PowerOf2V1 { public public static static void void main(string[] args) args) { Scanner Scanner scan scan = new new Scanner(System.in); System.out.print("Enter a number:"); int int limit limit = scan.nextint(); 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); What happens if the user enters 1? Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 33 The FOR statement Syntax: for for ( initialization ; condition condition ; increment increment ) statement; statement; Equivalent to: initialization while whilecondition { statement; statement; increment; increment; Many loops have this common pattern Comes to play when the number of iterations is known in advance initialization Example: condition for for (int (int count=0; count=0; count count <= <= 75; 75; count++) count++) { System.out.println (count); (count); statement increment Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 34

Example: powers of 2 Prints the powers of 2 up to a limit for(int for(int n = 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 can yield tighter code; better handling of control variables. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 35 Omitting parts of 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; Infinite FOR loop: for for ( initialization; ;increment ) statement; statement; Examples: for for (;;) (;;) { // // an an infinite infinite loop loop System.out.println ("beep"); ("beep"); for for (; (; count count < max max ; count count ++ ++ ) { System.out.println (count); (count); Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 36

Example: Multiplication table // // 10 10 by by 10 10 multiplication table table class class MultiplicationTable { public public static static void void main(string[] args) args) { for(int for(int j=1 j=1 ; j <= <= 10 10 ; j++) j++) { for(int for(int k=1 k=1 ; k <= <= 10 10 ; k++) k++) System.out.print(j*k); System.out.println(); Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 37 BREAK and CONTINUE BREAK can be used to terminate a loop; Execution continues after the loop s end CONTINUE can be used to terminates the current iteration; Execution continues by evaluating 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); double double 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.nextin(); scan.nextin(); 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 38

Control structures: lecture outline Boolean expressions and variables The IF statement The conditional The WHILE statement The SWITCH statement The DO statement The FOR statement Shorthand operators Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 39 Increment / decrement operators k ++ ++ Is equivalent to k = k + 1 k -- -- Is equivalent to k = k - 1 k must be a numeric variable. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 40

Prefix / postfix notation: k ++ ++ Has the same impact on count as ++ ++ k Prefix: the operator is written before the operands Postfix: the operators is written after the operands When used in the context of larger expression, the prefix / postfix notations make a difference: n = k ++ ++ Is not the same as n = ++ ++ k The rules of the game: Expressions count++ ++count count-- --count Operation add 1 add 1 subtract 1 subtract 1 Value Of expression old value new value old value new value Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 41 Examples count count = 30 30 total total = count++ count++ // // now now count=31 count=31 and and total=30 total=30 count count = 30 30 total total = ++count ++count // // now now count=31 count=31 and and total=31 total=31 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 42

Assignment operators Often we perform an operation on a variable, and then assign the result to the same variable. Example: sum = + x sum sum = + x is equivalent to: sum sum += += x The rules of the game: Operator += -= *= /= %= Example x+=y x-=y x*=y x/=y x%=y Equivalent to x = x + y x = x - y x = x * y x = 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 43