Download Download Presentation Lesson 3: Conditions and Loops

# Lesson 3: Conditions and Loops

Download Presentation ## Lesson 3: Conditions and Loops

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
##### Presentation Transcript

1. Lesson 3: Conditions and Loops Unit 1: The if Statement

2. The if Statement • The Java if statement has the following syntax: if (boolean-condition) statement; • If the Boolean condition is true, the statement is executed; if it is false, the statement is skipped • This provides basic decision making capabilities

3. Tempreture class Temperature { static final int THRESHOLD = 65; public static void main(String[] args) { InputRequestor input = new InputRequestor(); int temperature = input.requestInt(“Enter the temperature:”); System.out.println(“Current temperature “+ temperature); if (temperature < THRESHOLD) System.out.println(“It’s cold in here!”); } }

4. If statement flow diagram if (condition) statement; condition true statement

5. Boolean Expressions • The condition of anifstatement must evaluate to a true or false result • Java has several equality and relational operators: • More complex Boolean expressions are also possible

6. Block Statements • Several statements can be grouped together into a block statement • Blocks are delimited by braces • A block statement can be used wherever a statement is called for in the Java syntax if (boolean-condition){ statement1; statement2; … }

7. Example - Temperature2 class Temperature2 { static final int THRESHOLD = 65; public static void main(String[] args) { InputRequestor input = new InputRequestor(); int temperature = input.requestInt(“Enter the temperature:”); System.out.println(“Current temperature “+ temperature); if (temperature < THRESHOLD) { System.out.println(“It’s cold in here!”); System.out.println(“But we’ll survive.”); } } }

8. If .. Else Statement • Anelseclause can be added to anifstatement to make it an if-else statement: if (condition) statement1; else statement2; • If the condition is true, statement1 is executed; if the condition is false, statement2 is executed

9. Example - Temperature3 class Temperature3 { static final int FREEZING_POINT = 32; public static void main(String[] args) { InputRequestor input = new InputRequestor(); int temperature = input.requestInt(“Enter temperature:”); if (temperature <= FREEZING_POINT) System.out.println(“It’s freezing!”); else System.out.println(“Above freezing.”); } }

10. If/else flow diagram if (condition) statement1; else statement2; condition true statement1 statement2

11. Nested If statements • Since an “If” statement is a statement, it can appear inside another if statement. if (condition1) if (condition2) statement; • It can also appear in an “else” clause if (condition1) statement1; else if (condition2) statement2;

12. Nested If Example // Reads 2 integers and compares them class CompareExample { public static void main(String[] args) { InputRequestor input = new InputRequestor(); int a = input.requestInt(“First number:”); int b = input.requestInt(“Second number:”); if (a != b){ if (a > b) System.out.println(a+” is greater”); else System.out.println(b+” is greater”); }else System.out.println(“the numbers are equal”); } }

13. Checking your Input • When requesting input from the user, keep in mind that the input may be invalid. • It is good practice to check the validity of user input int numberOfItems = input.requestInt(“Enter number of items:”); if (numberOfItems < 0) { System.out.println( “Number of items must be positive!”); } else { double price = numberOfItems * ITEM_PRICE; System.out.println(“The total price is:“ +price); }

14. Lesson 3: Conditions and Loops Unit 2: Boolean Expressions

15. Logical Operators • Boolean expressions may be combined using logical operators • There are three logical operators in Java: • They all take Boolean operands and produce Boolean results • Logical NOT is unary (one operand), but logical AND and OR are binary (two operands)

16. Logical NOT • The logical NOT is also called logical negation or logical complement • If a is true, !a is false; if a is false, then !a is true • Logical expressions can be shown using truth tables

17. Logical AND • The expression a && b is true if both a and b are true, and false otherwise • Truth tables show all possible combinations of all terms

18. Logical OR • The expression a || b is true if a or b or both are true, and false otherwise

19. Logical Operators • Logical operators are used to form more complex logical expressions • Logical operators have precedence relationships between themselves and other operators if (a<1 || a%2!=0) System.out.println( “The input should be an even even number!”);

20. Logical Operators • Full expressions can be evaluated using truth tables

21. Boolean variables • Boolean expressions can be assigned to Boolean variables • Boolean variables are Boolean expressions boolean b, c; b = (x > 17); c = (x>17) && (x<60); boolean b, c; b = (x > 17); c = b && (x<60); if (c) System.out.println(“x is in range”);

22. Example - RightTriangle // Receives the length of the edges of a triangle // and determine if this is a right triangle class RightTriangle { public static void main(String[] args) { InputRequestor input = new InputRequestor(); float a = input.requestInt(“Edge1:”); float b = input.requestInt(“Edge2:”); float c = input.requestInt(“Hypotenuse:”); boolean test = a*a+b*b == c*c; if (test) System.out.println(“It’s a right triangle”); else System.out.println(“It’s not a right triangle”); } }

23. Lesson 3: conditions and loops Unit C3: The while Statement

24. The while statement • A while statement has the following syntax: while (condition) statement; • If the condition is true, the statement is executed; then the condition is evaluated again • The statement is executed over and over until the condition becomes false • If the condition of awhilestatement is false initially, the statement is never executed • Therefore, we say that awhilestatement executes zero or more times

25. While statement flow diagram while (condition) statement; condition true statement

26. Example - Counter // Counts from 1 to 5 class Counter { static final int LIMIT = 5; public static void main(String[] args) { int count = 1; while (count <= LIMIT) { System.out.println(count); count = count + 1; } System.out.println(“done”); } }

27. Examples - Factors // Gets an integer and prints its factors class FactorsExample { public static void main(String[] args) { InputRequestor input = new InputRequestor(); int a = input.requestInt(“Enter a number:”); int i = 1; System.out.println(“The divisors of “+a+” are:”); while (i <= a) { if (a%i == 0) { System.out.println(i); } i = i + 1; } } }

28. Infinite Loops • The body of awhileloop must eventually make the condition false • If not, it is an infinite loop, which will execute until the user interrupts the program • This is a common type of logical error -- always double check that your loops will terminate normally

29. Example - Forever // This program contains an infinite loop class Forever { static final int LIMIT = 25; public static void main(String[] args) { int count = 1; while (count <= LIMIT) { System.out.println(count); count = count - 1; } } }

30. Lesson 3: conditions and loops Unit 4: More conditionals

31. The Conditional Operator • Java has a conditional operator that evaluates a Boolean condition that determines which of two expressions is evaluated • The result of the chosen expression is the result of the entire conditional operator • Its syntax is: condition ? expression1 : expression2 • If the condition is true, expression1 is evaluated; if it is false, expression2 is evaluated

32. The Conditional Operator • It is similar to an if-else statement, except that it is an expression that returns a value • For example: • If a is greater that b, then a is assigned to max; otherwise, b is assigned to max • The conditional operator is ternary, meaning it requires three operands int max = (a > b) ? a : b;

33. The Conditional Operator • Another example: • If count equals 1, "Dime" is printed, otherwise "Dimes" is printed System.out.println ("Your change is " + count + ((count == 1) ? "Dime" : "Dimes”));

34. Another Selection Statement • The if and the if-else statements are selection statements, allowing us to select which statement to perform next based on some Boolean condition • Another selection construct, called the switch statement, provides another way to choose the next action • The switch statement evaluates an expression, then attempts to match the result to one of a series of values • Execution transfers to statement list associated with the first value that matches

35. Theswitch Statement • The syntax of the switch statement is: switch (expression) { case value1: statement-list1 case value2: statement-list2 case … }

36. The switch Statement • The expression must evaluate to an integral value, such as an integer or character • The break statement is usually used to terminate the statement list of each case, which causes control to jump to the end of the switch statement • A default case can be added to the end of the list of cases, and will execute if no other case matches

37. The switch Statement /** * A client that enables you to connect to the * bank server and make remote banking operations... */ public class BankClient { public static final int VIEW_BALANCE = 1; public static final int VIEW_SAVINGS = 2; public static final int CASH_TRANSFER = 3; public static final int VIEW_LAST_OPERATIONS = 4; // ...

38. The switch Statement // Inside the main loop of the client: int option = InputRequestor.requentInt(“Enter your choice:”); switch(option) { case VIEW_BALANCE: showBalance(); break; case VIEW_SAVINGS: showSavings(); break; default: output.showMessage(“No such option!”); }

39. Lesson 3: conditions and loops Unit 5: Shorthand Operators

40. Shorthand Operators • Many operations are very commonly used • Java has shorthand notations for these • increment and decrement operators • assignment operators x = x + 1; sum = sum + x;

41. The Increment and Decrement Operators • The increment operator (++) adds one to its integer or floating point operand • The decrement operator (--) subtracts one • The statement is essentially equivalent to count++; count = count + 1;

42. The Increment and Decrement Operators • The increment and decrement operators can be applied in prefix (before the variable) or postfix (after the variable) form • When used alone in a statement, the prefix and postfix forms are basically equivalent. That is, is equivalent to count++; ++count;

43. The Increment and Decrement Operators • When used in a larger expression, the prefix and postfix forms have a different effect • In both cases the variable is incremented (decremented) • But the value used in the larger expression depends on the form

44. The Increment and Decrement Operators • If count currently contains 45, then assigns 45 to total and 46 to count • If count currently contains 45, then assigns the value 46 to both total and count total = count++; total = ++count;

45. The Increment and Decrement Operators • If sum contains 25, what does this statement print? • Prints the following result: 25 27 27 27 • sum contains 26 after the line is complete System.out.println (sum++ + " " + ++sum + " " + sum + " " + sum--);

46. Assignment Operators • Often we perform an operation on a variable, then store the result back into that variable • Java provides assignment operators that simplify that process • For example, the statement is equivalent to sum += value; sum = sum + value;

47. Assignment Operators • There are many such assignment operators, always written as op= , such as:

48. Assignment Operators • The right hand side of an assignment operator can be a complete expression • The entire right-hand expression is evaluated first, then combined with the additional operation • Therefore result /= total-MIN; is equivalent to result /= total-MIN; result = result / (total-MIN);

49. Lesson 3: conditions and loops Unit C6: More Repetition

50. More Repetition Constructs • In addition towhileloops, Java has two other constructs used to perform repetition: • the do statement • the for statement • Each loop type has its own unique characteristics • You must choose which loop type to use in each situation
{"ft_lang_label":"__label__en","ft_lang_prob":0.7229094,"math_prob":0.96957403,"size":11921,"snap":"2021-21-2021-25","text_gpt3_token_len":2680,"char_repetition_ratio":0.1747084,"word_repetition_ratio":0.11111111,"special_character_ratio":0.24477813,"punctuation_ratio":0.13499026,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9771476,"pos_list":[0,1,2,3,4,5,6,7,8],"im_url_duplicate_count":[null,null,null,null,null,1,null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-06-22T04:10:31Z\",\"WARC-Record-ID\":\"<urn:uuid:7bae949d-2fad-48b4-a1ae-ed11b64ac9af>\",\"Content-Length\":\"106275\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:5ae3a946-85fb-4803-ab61-c757f4313def>\",\"WARC-Concurrent-To\":\"<urn:uuid:4a3e2e63-82ce-408f-b6b6-ffc75e1823b4>\",\"WARC-IP-Address\":\"44.233.66.57\",\"WARC-Target-URI\":\"https://fr.slideserve.com/otto/lesson-3-conditions-and-loops-powerpoint-ppt-presentation\",\"WARC-Payload-Digest\":\"sha1:K5PNES4SNCFGQFM4K24YJAKSTQQRVL2P\",\"WARC-Block-Digest\":\"sha1:732EF4LPRRCJ5XRU3KDBMGT5DMOP45CS\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-25/CC-MAIN-2021-25_segments_1623488507640.82_warc_CC-MAIN-20210622033023-20210622063023-00312.warc.gz\"}"}