Introduction to Computer Science, Shimon Schocken, IDC Herzliya. Lectures Control Structures
|
|
- Britton Dennis
- 5 years ago
- Views:
Transcription
1 Introduction to Computer Science, Shimon Schocken, IDC Herzliya Lectures Control Structures Control Structures, Shimon Schocken IDC Herzliya, 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 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 2
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, 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, slide 4
3 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, 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, slide 6
4 The IF / ELSE statement Syntax: if if (condition) statement1 statement1 else else statement2 statement2 statement1 condition statement2 Control Structures, Shimon Schocken IDC Herzliya, 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, slide 8
5 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, 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, slide 10
6 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, 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, slide 12
7 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 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 if if x yy 2 2 = = z 2 2 Such statements can be expressed in computer programs as Boolean expressions. Control Structures, Shimon Schocken IDC Herzliya, 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, ( A Calculus of Logic ) Relational operator Boolean operator Relational operator Control Structures, Shimon Schocken IDC Herzliya, slide 14
8 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 <= <= 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, 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, slide 16
9 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, 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, slide 18
10 Boolean variables Boolean expressions can be assigned to Boolean variables: // // x must must be be between between 0 and and 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, 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, slide 20
11 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, 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, slide 22
12 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, 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, slide 24
13 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, 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, slide 26
14 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, 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, slide 28
15 The SWITCH statement Syntax switch switchexpression { case casevalue1 : statement1 statement1 case casevalue2 : statement2 statement 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, 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, slide 30
16 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, 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, slide 32
17 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, 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, slide 34
18 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, 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, slide 36
19 Example: Multiplication table // // by by 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 <= <= ; j++) j++) { for(int for(int k=1 k=1 ; k <= <= ; k++) k++) System.out.print(j*k); System.out.println(); Control Structures, Shimon Schocken IDC Herzliya, 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, slide 38
20 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, 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, slide 40
21 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, slide 41 Examples count count = total total = count++ count++ // // now now count=31 count=31 and and total=30 total=30 count count = total total = ++count ++count // // now now count=31 count=31 and and total=31 total=31 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 42
22 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, slide 43
Lectures 3-1, 3-2. Control Structures. Control Structures, Shimon Schocken IDC Herzliya, slide 1
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
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 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 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 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 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: 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 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 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 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 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 informationLoops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz
Loops and Files Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Chapter Topics o The Increment and Decrement Operators o The while Loop o Shorthand Assignment Operators o The do-while
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 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 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 informationChapter 3: Operators, Expressions and Type Conversion
101 Chapter 3 Operators, Expressions and Type Conversion Chapter 3: Operators, Expressions and Type Conversion Objectives To use basic arithmetic operators. To use increment and decrement operators. To
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 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 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 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 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 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 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 informationJAVA OPERATORS GENERAL
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 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 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 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 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 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 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 informationObject-Oriented Programming in Java
CSCI/CMPE 3326 Object-Oriented Programming in Java Loop Statements Dongchul Kim Department of Computer Science University of Texas Rio Grande Valley The Increment and Decrement Operators There are numerous
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 informationCONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2
CONTENTS: Compilation Data and Expressions COMP 202 More on Chapter 2 Programming Language Levels There are many programming language levels: machine language assembly language high-level language Java,
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 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 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 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 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 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 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 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 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 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 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 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 informationObject Oriented Programming Lecture (2.1) Supervisor Ebtsam AbdelHakam Department of Computer Science Najran University
Object Oriented Programming Lecture (2.1) Supervisor Ebtsam AbdelHakam ebtsamabd@gmail.com Department of Computer Science Najran University Ebtsam AbdelHakam 1 Outline 2 Operators Arithmetic Operators.
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 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 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 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 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 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 informationIn this chapter, you will:
Java Programming: Guided Learning with Early Objects Chapter 4 Control Structures I: Selection In this chapter, you will: Make decisions with the if and if else structures Use compound statements in an
More informationbitwise inclusive OR Logical logical AND && logical OR Ternary ternary? : Assignment assignment = += -= *= /= %= &= ^= = <<= >>= >>>=
Operators in java Operator in java is a symbol that is used to perform operations. For example: +, -, *, / etc. There are many types of operators in java which are given below: Unary Operator, Arithmetic
More informationCOMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others
COMP-202 Recursion Recursion Recursive Definitions Run-time Stacks Recursive Programming Recursion vs. Iteration Indirect Recursion Lecture Outline 2 Recursive Definitions (1) A recursive definition is
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 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 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 informationProf. Navrati Saxena TA: Rochak Sachan
JAVA Prof. Navrati Saxena TA: Rochak Sachan Operators Operator Arithmetic Relational Logical Bitwise 1. Arithmetic Operators are used in mathematical expressions. S.N. 0 Operator Result 1. + Addition 6.
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 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 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 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 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 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 informationLecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan
Lecture 08-1 Programming in C++ PART 1 By Assistant Professor Dr. Ali Kattan 1 The Conditional Operator The conditional operator is similar to the if..else statement but has a shorter format. This is useful
More informationConditionals and Loops Chapter 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013
Conditionals and Loops Chapter 4 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 2 Scope Flow of control Boolean expressions if and switch statements Comparing data while, do, and for
More informationAlgorithms and Conditionals
Algorithms and Conditionals 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 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 informationData Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87
Data Types Java is a strongly-typed 1 programming language. Every variable has a type. Also, every (mathematical) expression has a type. There are two categories of data types: primitive data types, and
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 informationProgramming Constructs Overview. Method Call System.out.print( hello ); Method Parameters
Programming Constructs Overview Method calls More selection statements More assignment operators Conditional operator Unary increment and decrement operators Iteration statements Defining methods 27 October
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 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 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 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 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 informationObject-Oriented Programming
Object-Oriented Programming Java Syntax Program Structure Variables and basic data types. Industry standard naming conventions. Java syntax and coding conventions If Then Else Case statements Looping (for,
More informationHandout 5 cs180 - Programming Fundamentals Spring 15 Page 1 of 8. Handout 5. Loops.
Handout 5 cs180 - Programming Fundamentals Spring 15 Page 1 of 8 Handout 5 Loops. Loops implement repetitive computation, a k a iteration. Java loop statements: while do-while for 1. Start with the while-loop.
More informationOperators in java Operator operands.
Operators in java Operator in java is a symbol that is used to perform operations and the objects of operation are referred as operands. There are many types of operators in java such as unary operator,
More information1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133
1 class Lecture3 { 2 3 "Selections" 4 5 } 6 7 // Keywords 8 if, else, else if, switch, case, default Zheng-Liang Lu Java Programming 88 / 133 Flow Controls The basic algorithm (and program) is constituted
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 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 informationBjarne Stroustrup. creator of C++
We Continue GEEN163 I have always wished for my computer to be as easy to use as my telephone; my wish has come true because I can no longer figure out how to use my telephone. Bjarne Stroustrup creator
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 informationMore Programming Constructs -- Introduction
More Programming Constructs -- Introduction We can now examine some additional programming concepts and constructs Chapter 5 focuses on: internal data representation conversions between one data type and
More informationJava provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:
Basic Operators 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 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 informationCMPS 11 Introduction to Programming Midterm 1 Review Problems
CMPS 11 Introduction to Programming Midterm 1 Review Problems Note: The necessary material for some of these problems may not have been covered by end of class on Monday, the lecture before the exam. If
More informationSelenium Class 9 - Java Operators
Selenium Class 9 - Java Operators Operators are used to perform Arithmetic, Comparison, and Logical Operations, Operators are used to perform operations on variables and values. public class JavaOperators
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 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 informationLecture 1 Java SE Programming
Lecture 1 Java SE Programming presentation Java Programming Software App Development Assoc. Prof. Cristian Toma Ph.D. D.I.C.E/D.E.I.C Department of Economic Informatics & Cybernetics www.dice.ase.ro cristian.toma@ie.ase.ro
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 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 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 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 information