Lectures 3-1, 3-2. Control Structures. Control Structures, Shimon Schocken IDC Herzliya, slide 1
|
|
- Madeline Harper
- 5 years ago
- Views:
Transcription
1 Introduction to Computer Science Shimon Schocken IDC Herzliya Lectures 3-1, 3-2 Control Structures Control Structures, Shimon Schocken IDC Herzliya, 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, slide 2
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 System.out.println(sum +" +" "+ "+ sum++ sum++ +" +" "+ "+ ++sum ++sum +" +" "+ "+ sum sum +" +" "+ "+ sum-- sum-- +" +" "+ "+ sum) sum) What will it print? Control Structures, Shimon Schocken IDC Herzliya, 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, slide 4
3 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 s Run(input2) s0 s0 s1 s1 s2 s2 s3 s3 s4 s4 s5 s5 s6 s6 s7 s7 s8 s8 s9 s 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, slide 5 Control structures: lecture outline If Boolean expressions and variables While switch do for Control Structures, Shimon Schocken IDC Herzliya, slide 6
4 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, 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 Control Structures, Shimon Schocken IDC Herzliya, slide 8
5 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, 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, slide 10
6 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, 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, slide 12
7 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, slide 13 Control structures: lecture outline If Boolean expressions and variables While switch do for Control Structures, Shimon Schocken IDC Herzliya, slide 14
8 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 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 kg kg or or the the shipping shipping distance distance is is more more than than 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 yy 2 2 z 2 2 Such statements are expressed in computer programs as Boolean expressions. Control Structures, Shimon Schocken IDC Herzliya, 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, slide 16
9 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, 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 > city city "LA" "LA" x!! gpa gpa < < 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, slide 18
10 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, 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, slide 20
11 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, 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, slide 22
12 Control structures: lecture outline If Boolean expressions and variables While switch do for Control Structures, Shimon Schocken IDC Herzliya, 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, slide 24
13 The while statement Syntax: while while (condition) conditional code code A while loop executes zero or more times. Control Structures, Shimon Schocken IDC Herzliya, 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, slide 26
14 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, 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, slide 28
15 Control structures: lecture outline If Boolean expressions and variables While switch do for Control Structures, Shimon Schocken IDC Herzliya, slide 29 The switch statement Syntax switch switchexpression { value 1 : 1 statement statement 1 1 value 2 : 2 statement statement 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, slide 30
16 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 switch switch (operation) { WITHDRAWAL: dowithdrawal(); BALANCE: BALANCE: showbalance(); DEPOSIT: DEPOSIT: dodeposit(); Control Structures, Shimon Schocken IDC Herzliya, 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 % % )) 0)) (year (year % % ) 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, slide 32
17 Control structures: lecture outline If Boolean expressions and variables While switch do for Control Structures, Shimon Schocken IDC Herzliya, 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, slide 34
18 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, 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, slide 36
19 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, 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, slide 38
20 Example // // by by multiplication table table class classmultiplicationtable { public public static static void voidmain(string[] args) args) { for(int for(int j 1 ; j < < ; j++) j++) { for(int for(int k 1 ; k < < ; k++) k++) System.out.print(j * k); k); System.out.println(); Control Structures, Shimon Schocken IDC Herzliya, 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, slide 40
21
22 ERROR: undefined OFFENDING COMMAND: STACK:
Introduction to Computer Science, Shimon Schocken, IDC Herzliya. Lectures Control Structures
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
More informationLoops. CSE 114, Computer Science 1 Stony Brook University
Loops CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation Suppose that you need to print a string (e.g., "Welcome to Java!") a user-defined times N: N?
More informationJava Coding 3. Over & over again!
Java Coding 3 Over & over again! Repetition Java repetition statements while (condition) statement; do statement; while (condition); where for ( init; condition; update) statement; statement is any Java
More informationIteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times
Iteration: Intro Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times 2. Posttest Condition follows body Iterates 1+ times 1 Iteration: While Loops Pretest loop Most general loop construct
More informationCMPT 125: Lecture 4 Conditionals and Loops
CMPT 125: Lecture 4 Conditionals and Loops Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 17, 2009 1 Flow of Control The order in which statements are executed
More informationCSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:
Repetition CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this
More informationJava Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition
Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Learn about repetition (looping) control structures Explore how to construct and use: o Counter-controlled
More informationCSC 1051 Data Structures and Algorithms I
Repetition CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this
More informationJava provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:
JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators
More informationJava Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition
Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Learn about repetition (looping) control structures Explore how to construct and use: o Counter-controlled
More informationCOMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements
COMP-202 Unit 4: Programming With Iterations CONTENTS: The while and for statements Introduction (1) Suppose we want to write a program to be used in cash registers in stores to compute the amount of money
More informationChapter 3. Selections
Chapter 3 Selections 1 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator 6. The Switch Statement 7. Useful Hints 2 1. Flow of
More informationCSC 1051 Data Structures and Algorithms I
Repetition CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this
More information10/30/2010. Introduction to Control Statements. The if and if-else Statements (cont.) Principal forms: JAVA CONTROL STATEMENTS SELECTION STATEMENTS
JAVA CONTROL STATEMENTS Introduction to Control statements are used in programming languages to cause the flow of control to advance and branch based on changes to the state of a program. In Java, control
More informationH212 Introduction to Software Systems Honors
Introduction to Software Systems Honors Lecture #04: Fall 2015 1/20 Office hours Monday, Wednesday: 10:15 am to 12:00 noon Tuesday, Thursday: 2:00 to 3:45 pm Office: Lindley Hall, Room 401C 2/20 Printing
More informationJava I/O and Control Structures
Java I/O and Control Structures CSC 2014 Java Bootcamp Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Some slides in this presentation are adapted from the slides accompanying
More informationJava I/O and Control Structures Algorithms in everyday life
Introduction Java I/O and Control Structures Algorithms in everyday life CSC 2014 Java Bootcamp Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Source: http://xkcd.com/627/
More informationM105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014
M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014 Question One: Choose the correct answer and write it on the external answer booklet. 1. Java is. a. case
More informationIntroduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017
Introduction to OOP with Java Instructor: AbuKhleif, Mohammad Noor Sep 2017 Lecture 03: Control Flow Statements: Selection Instructor: AbuKhleif, Mohammad Noor Sep 2017 Instructor AbuKhleif, Mohammad Noor
More informationProgram Control Flow
Lecture slides for: Chapter 3 Program Control Flow Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2
More informationProgram Control Flow
Lecture slides for: Chapter 3 Program Control Flow Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2
More informationArithmetic Compound Assignment Operators
Arithmetic Compound Assignment Operators Note that these shorthand operators are not available in languages such as Matlab and R. Zheng-Liang Lu Java Programming 76 / 141 Example 1... 2 int x = 1; 3 System.out.println(x);
More informationExpression statements are formed by adding a semicolon to the end of certain types of expressions.
Expression statements are formed by adding a semicolon to the end of certain types of expressions. Variable declaration statements declare variables. int width, height, area; String hello = "Hello, world!";
More informationExample. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.
Example Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct. 1... 2 Scanner input = new Scanner(System.in); 3 int x = (int) (Math.random()
More informationDate: Dr. Essam Halim
Assignment (1) Date: 11-2-2013 Dr. Essam Halim Part 1: Chapter 2 Elementary Programming 1 Suppose a Scanner object is created as follows: Scanner input = new Scanner(System.in); What method do you use
More informationFLOW CONTROL. Author: Boaz Kantor The Interdisciplinary Center, Herzliya Introduction to Computer Science Winter Semester
Author: Boaz Kantor The Interdisciplinary Center, Herzliya Introduction to Computer Science Winter 2008-9 Semester FLOW CONTROL Flow Control Hold 2 balls in left hand, 1 ball in right Throw ball from left
More informationMidterm Examination (MTA)
M105: Introduction to Programming with Java Midterm Examination (MTA) Spring 2013 / 2014 Question One: [6 marks] Choose the correct answer and write it on the external answer booklet. 1. Compilers and
More informationCOMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015
COMP-202: Foundations of Programming Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015 Announcements Slides will be posted before the class. There might be few
More informationITERATION WEEK 4: EXMAPLES IN CLASS
Monday Section 2 import java.util.scanner; public class W4MSection2 { ITERATION WEEK 4: EXMAPLES IN CLASS public static void main(string[] args) { Scanner input1 = new Scanner (System.in); int CircleCenterX
More informationRepetition, Looping. While Loop
Repetition, Looping Last time we looked at how to use if-then statements to control the flow of a program. In this section we will look at different ways to repeat blocks of statements. Such repetitions
More informationFor that purpose, java provides control structures that serve to specify what has to be done by our program, when and under which circumstances.
Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose, java provides control structures
More informationFlow Control. Key Notion. Statement Categories. 28-Oct-10
Boaz Kantor Introduction to Computer Science, Fall semester 2010-2011 IDC Herzliya Flow Control Raistlin: This alters time. Astinus: This alters nothing...time flows on, undisturbed. Raistlin: And carries
More informationCOMP 202 Java in one week
CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator COMP 202 Java in one week The Java Programming Language A programming language
More informationCS110 Programming Language I. Lab 6: Multiple branching Mechanisms
CS110 Programming Language I Lab 6: Multiple branching Mechanisms Computer Science Department Fall 2016 Lab Objectives: In this lab, the student will practice: Using switch as a branching mechanism Lab
More informationCOSC 123 Computer Creativity. Java Decisions and Loops. Dr. Ramon Lawrence University of British Columbia Okanagan
COSC 123 Computer Creativity Java Decisions and Loops Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Key Points 1) A decision is made by evaluating a condition in an if/else
More informationChapter 4: Control Structures I
Chapter 4: Control Structures I Java Programming: From Problem Analysis to Program Design, Second Edition Chapter Objectives Learn about control structures. Examine relational and logical operators. Explore
More informationChapter 4 Loops. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk
Chapter 4 Loops Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk ١ while Loop Flow Chart while (loop-continuation-condition) { // loop-body;
More informationExample: Monte Carlo Simulation 1
Example: Monte Carlo Simulation 1 Write a program which conducts a Monte Carlo simulation to estimate π. 1 See https://en.wikipedia.org/wiki/monte_carlo_method. Zheng-Liang Lu Java Programming 133 / 149
More informationConditional Programming
COMP-202 Conditional Programming Chapter Outline Control Flow of a Program The if statement The if - else statement Logical Operators The switch statement The conditional operator 2 Introduction So far,
More informationSequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;
Control Statements Control Statements All programs could be written in terms of only one of three control structures: Sequence Structure Selection Structure Repetition Structure Sequence structure The
More informationFlow Control. Boaz Kantor Introduction to Computer Science, Fall semester IDC Herzliya
Boaz Kantor Introduction to Computer Science, Fall semester 2010-2011 IDC Herzliya Flow Control Raistlin: This alters time. Astinus: This alters nothing...time flows on, undisturbed. Raistlin: And carries
More informationMore on control structures
Lecture slides for: Chapter 5 More on control structures Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2
More informationECE 122. Engineering Problem Solving with Java
ECE 122 Engineering Problem Solving with Java Lecture 10 For Loops and Arrays Outline Problem: How can I perform the same operations a fixed number of times? Considering for loops Performs same operations
More informationCS212 Midterm. 1. Read the following code fragments and answer the questions.
CS1 Midterm 1. Read the following code fragments and answer the questions. (a) public void displayabsx(int x) { if (x > 0) { System.out.println(x); return; else { System.out.println(-x); return; System.out.println("Done");
More informationJAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods
Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Computer Programming Lab (ECOM 2114) ABSTRACT In this Lab you will learn to define and invoke void and return java methods JAVA
More informationComputer Programming, I. Laboratory Manual. Experiment #6. Loops
Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #6
More informationSelection and Repetition Revisited
Selection and Repetition Revisited CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/
More informationLogic is the anatomy of thought. John Locke ( ) This sentence is false.
Logic is the anatomy of thought. John Locke (1632 1704) This sentence is false. I know that I know nothing. anonymous Plato (In Apology, Plato relates that Socrates accounts for his seeming wiser than
More informationTopic 11 Scanner object, conditional execution
Topic 11 Scanner object, conditional execution "There are only two kinds of programming languages: those people always [complain] about and those nobody uses." Bjarne Stroustroup, creator of C++ Copyright
More informationMotivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018
Motivating Examples (1.1) Selections EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG 1 import java.util.scanner; 2 public class ComputeArea { 3 public static void main(string[] args)
More informationCOMP 202. Java in one week
COMP 202 CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator Java in one week The Java Programming Language A programming language
More informationCSC 1051 Data Structures and Algorithms I
Repetition CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this
More informationCS111: PROGRAMMING LANGUAGE II
CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1(c): Java Basics (II) Lecture Contents Java basics (part II) Conditions Loops Methods Conditions & Branching Conditional Statements A
More informationSelections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG
Selections EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG Learning Outcomes The Boolean Data Type if Statement Compound vs. Primitive Statement Common Errors
More informationThe for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming
The for Loop, Accumulator Variables, Seninel Values, and The Random Class CS0007: Introduction to Computer Programming Review General Form of a switch statement: switch (SwitchExpression) { case CaseExpression1:
More informationCS 112 Introduction to Programming
CS 112 Introduction to Programming Conditional Statements Boolean Expressions and Methods Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu
More informationCS 112 Introduction to Programming
CS 112 Introduction to Programming Conditional Statements Boolean Expressions and Methods Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu
More informationFull file at
Chapter 3 Flow of Control Multiple Choice 1) An if selection statement executes if and only if: (a) the Boolean condition evaluates to false. (b) the Boolean condition evaluates to true. (c) the Boolean
More informationFor that purpose, java provides control structures that serve to specify what has to be done by our program, when and under which circumstances.
Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose, java provides control structures
More informationIntroduction to Computer Science Unit 2. Exercises
Introduction to Computer Science Unit 2. Exercises Note: Curly brackets { are optional if there is only one statement associated with the if (or ) statement. 1. If the user enters 82, what is 2. If the
More informationChapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.
Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 1 Motivations If you assigned a negative value for radius
More informationSelec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal
Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program
More informationQuestion: Total Points: Score:
CS 170 Exam 1 Section 001 Fall 2014 Name (print): Instructions: Keep your eyes on your own paper and do your best to prevent anyone else from seeing your work. Do NOT communicate with anyone other than
More informationIntroduction to Computer Programming
Introduction to Computer Programming Lecture 3 Counting Loops Repetition with for Loops So far, repeating a statement is redundant: System.out.println("Homer says:"); System.out.println("I am so smart");
More informationCS111: PROGRAMMING LANGUAGE II
1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1: Introduction Lecture Contents 2 Course info Why programming?? Why Java?? Write once, run anywhere!! Java basics Input/output Variables
More informationCS 112 Introduction to Programming
CS 112 Introduction to Programming (Spring 2012) Lecture #8: More on Conditional & Loop Zhong Shao Department of Computer Science Yale University Office: 314 Watson http://flint.cs.yale.edu/cs112 Acknowledgements:
More informationFlow of Control of Program Statements CS 112 Introduction to Programming. Basic if Conditional Statement Basic Test: Relational Operators
Flow of Control of Program Statements CS 112 Introduction to Programming (Spring 2012) q Java provides two types of program flow of control statements: decision statements, or conditional statements: decide
More information1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137
1 class Lecture3 { 2 3 "Selections" 4 5 } 6 7 // Keywords 8 if, else, else if, switch, case, default Zheng-Liang Lu Java Programming 89 / 137 Flow Controls The basic algorithm (and program) is constituted
More informationProgramming with Java
Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules
More information++x vs. x++ We will use these notations very often.
++x vs. x++ The expression ++x first increments the value of x and then returns x. Instead, the expression x++ first returns the value of x and then increments itself. For example, 1... 2 int x = 1; 3
More informationQuestion: Total Points: Score:
CS 170 Exam 1 Section 000 Fall 2014 Name (print): Instructions: Keep your eyes on your own paper and do your best to prevent anyone else from seeing your work. Do NOT communicate with anyone other than
More informationAlgorithms and Java basics: pseudocode, variables, assignment, and interactive programs
Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs CSC 1051 Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova
More informationSelec%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 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program
More informationSelection and Repetition Revisited
Selection and Repetition Revisited CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/
More informationAP COMPUTER SCIENCE A
AP COMPUTER SCIENCE A CONTROL FLOW Aug 28 2017 Week 2 http://apcs.cold.rocks 1 More operators! not!= not equals to % remainder! Goes ahead of boolean!= is used just like == % is used just like / http://apcs.cold.rocks
More informationNew York University Introduction to Computer Science Exam Sample Problems 2013 Andrew I. Case. Instructions:
Name: New York University Introduction to Computer Science Exam Sample Problems 2013 Andrew I. Case Instructions: KEEP TEST BOOKLET CLOSED UNTIL YOU ARE INSTRUCTED TO BEGIN. This exam is double sided (front
More informationScanner Objects. Zheng-Liang Lu Java Programming 82 / 133
Scanner Objects It is not convenient to modify the source code and recompile it for a different radius. Reading from the console enables the program to receive an input from the user. A Scanner object
More informationSTUDENT LESSON A12 Iterations
STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of
More informationIEEE Floating-Point Representation 1
IEEE Floating-Point Representation 1 x = ( 1) s M 2 E The sign s determines whether the number is negative (s = 1) or positive (s = 0). The significand M is a fractional binary number that ranges either
More informationMore Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements
More Things We Can Do With It! More operators and expression types More s 11 October 2007 Ariel Shamir 1 Overview Variables and declaration More operators and expressions String type and getting input
More informationCompSci 125 Lecture 11
CompSci 125 Lecture 11 switch case The? conditional operator do while for Announcements hw5 Due 10/4 p2 Due 10/5 switch case! The switch case Statement Consider a simple four-function calculator 16 buttons:
More informationOver and Over Again GEEN163
Over and Over Again GEEN163 There is no harm in repeating a good thing. Plato Homework A programming assignment has been posted on Blackboard You have to convert three flowcharts into programs Upload the
More informationJAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to write programs for executing statements repeatedly using a while, do while and for loop
Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Computer Programming Lab (ECOM 2114) ABSTRACT In this Lab you will learn to write programs for executing statements repeatedly
More informationSelection Statements and operators
Selection Statements and operators CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/
More informationWentworth Institute of Technology. Engineering & Technology WIT COMP1000. Simple Control Flow: if-else statements
WIT COMP1000 Simple Control Flow: if-else statements Control Flow Control flow is the order in which program statements are executed So far, all of our programs have been executed straight-through from
More informationJava Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2
Java Foundations Introduction to Program Design and Data Structures 4th Edition Lewis TEST BANK Full download at : https://testbankreal.com/download/java-foundations-introduction-toprogram-design-and-data-structures-4th-edition-lewis-test-bank/
More informationCOMP 202. Programming With Iterations. CONTENT: The WHILE, DO and FOR Statements. COMP Loops 1
COMP 202 Programming With Iterations CONTENT: The WHILE, DO and FOR Statements COMP 202 - Loops 1 Repetition Statements Repetition statements or iteration allow us to execute a statement multiple times
More informationLoops and Expression Types
Software and Programming I Loops and Expression Types Roman Kontchakov / Carsten Fuhs Birkbeck, University of London Outline The while, for and do Loops Sections 4.1, 4.3 and 4.4 Variable Scope Section
More informationfalse, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4
1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4 5 } 6 7 // Keywords: 8 byte, short, int, long, char, float, double, boolean, true, false, import, new Zheng-Liang Lu Java Programming 45
More informationFollowing is the general form of a typical decision making structure found in most of the programming languages:
Decision Making Decision making structures have one or more conditions to be evaluated or tested by the program, along with a statement or statements that are to be executed if the condition is determined
More informationKey Points. COSC 123 Computer Creativity. Java Decisions and Loops. Making Decisions Performing Comparisons. Making Decisions
COSC 123 Computer Creativity Java Decisions and Loops Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Key Points 1) A decision is made by evaluating a condition in an if/
More informationSchool of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn
CPS109 Course Notes 6 Alexander Ferworn Unrelated Facts Worth Remembering Use metaphors to understand issues and explain them to others. Look up what metaphor means. Table of Contents Contents 1 ITERATION...
More informationControl Structures: if and while A C S L E C T U R E 4
Control Structures: if and while A C S - 1903 L E C T U R E 4 Control structures 3 constructs are essential building blocks for programs Sequences compound statement Decisions if, switch, conditional operator
More informationBuilding Java Programs
Building Java Programs Chapter 2 Lecture 2-2: The for Loop reading: 2.3 1 2 Repetition with for loops So far, repeating a statement is redundant: System.out.println("Homer says:"); System.out.println("I
More informationJump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.
Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:
More informationBuilding Java Programs
Building Java Programs Chapter 2 Lecture 2-2: The for Loop reading: 2.3 1 Repetition with for loops So far, repeating a statement is redundant: System.out.println("Homer says:"); System.out.println("I
More informationJump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.
Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:
More informationFull file at
Chapter 3 Flow of Control Key Terms parentheses, p. 95 if-else, p. 95 if-else with multiple statements, p. 96 compound statements, p. 96 indenting, p. 98 multiway if-else, p. 98 switch statement, p. 101
More informationBasic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java
Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word Chapter 1 Introduction to Computers, Programs, and Java Chapter 2 Primitive Data Types and Operations Chapter 3 Selection
More informationChapter 3 Selections. 3.1 Introduction. 3.2 boolean Data Type
3.1 Introduction Chapter 3 Selections Java provides selections that let you choose actions with two or more alternative courses. Selection statements use conditions. Conditions are Boolean expressions.
More information