1 / 58

Conditional Expressions “If-Else”

Conditional Expressions “If-Else”. You can alter the sequential control of flow from 1 statement to the next by: Calling a function Iterative Statements(loops) Conditional Expressions (if-else) Switch Statements.

hank
Télécharger la présentation

Conditional Expressions “If-Else”

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Conditional Expressions“If-Else” • You can alter the sequential control of flow from 1 statement to the next by: • Calling a function • Iterative Statements(loops) • Conditional Expressions (if-else) • Switch Statements

  2. if-else statements tell the program to choose and execute 1 or another code fragment • Conditional jump instructions test a certain condition and tells the CPU to “jump” to a specified instruction, based on the results of the test.

  3. if(condition) { do stuff…; } else { do other stuff…; }

  4. The if condition is evaluated and if true , do stuff executes, otherwise do other stuff executes. • You only need the brackets {} if there are multiple instructions in the if or else conditional expression.

  5. int a= 10, b=12, c; if(a>b) { System.out.print( "var a contains a higher value " + a ); c = a; } else { System.out.print( "var b contains a higher value " + b ); c = b; }

  6. int abs(int x) { // absolute value of an integer int ax; if(x>=0) // if x is greater or equal to 0 { ax = x; //do this } else //otherwise { ax = -x //do this } return ax; }

  7. Or, more concisely... int abs(int x) { // absolute value of an integer if(x<0) // if x is less than 0 { x = -x; //negate x } return x; }

  8. void bubblesort(int v[ ] v) { int c1, c2, leng, temp; leng = v.length(); for (c1 = 0; c1 < (leng - 1); c1++) { for (c2 = (c1 +1); c2 < leng; c2++) { if (v[c1] > v[c2]) { temp = v[c1]; v[c1] = v[c2]; v[c2] = temp; } // code continues, but not shown

  9. Boolean (True & False): • In C & C++ True was any non zero value and False was a zero value • Java has a boolean Data Type that contains only 2 states TRUE or FALSE Boolean aVar;

  10. Boolean (True & False): • You can assign a boolan the resulting value of any Boolean expression • Example: Boolean over21 = age > 21; • Over21 is set to true if age is greater than 21 otherwise it is set to false

  11. Boolean (True & False): • This code is the same as: boolean over21; If (age > 21) over21 = true; else over21 = false;

  12. boolean lbool = true; if(lbool) // if lbool is true { System.out.print( "the condition is true" ); } lbool = false; if(!lbool) // if lbool is false { System.out.print( "the condition is false" ); //executes }

  13. Evaluate a function call in an if statement // the withdoifs function is on next slide if( withdoifs() ) // fx returns a boolean value { System.out.println( "function returned a TRUE value" ); } else { System.out.println( "function returned a FALSE value" ); }

  14. boolean withdoifs() { int x = 12; if(x%2 == 0) // TRUE when x is EVEN // FALSE when x is ODD return true; else return false; } // WHAT IS RETURNED TO MAIN ?

  15. if(TRUE) // fx evaluates to TRUE as 12%2 has //no remainder so 0 == 0 { System.out.print( "function returned a FALSE value" ); } • The out statement is executed

  16. //WHAT IF WE CHANGED “x” ? boolean withdoifs() { int x = 11; if(x%2 == 0) // TRUE when x is EVEN // FALSE when x is ODD return true; else return false; } // WHAT IS RETURNED TO MAIN ?

  17. if(false) // fx evaluates to false as 9%2 has a //remainder so 1 != 0 { System.out.println("function returned a TRUE value" ); } • The out statement is NOT executed

  18. Relational Operators: > greater than < less than >= greater than or equal to <= less than or equal to == is equal != not equal • The result of a relational operation is a boolean type • True if the comparison is true & False if the comparison is false

  19. int a=3, b=4, c=5; if(a!=b) // a is not equal to b // since 3 is not = to 4, the expression // returns a TRUE condition

  20. if(x > y) max = x; else max = y;

  21. Remember that == means “is equal to” while = means assignment

  22. if(gender != ‘M’) { System.out.print(“Dear Ms.”); } else { System.out.print(“Dear Mr.”); }

  23. NOTE: the brackets around the statement blocks • NOTE: avoid using == and != on floats and doubles because these variables are imprecise • Example: 15.0 / 3.0 == 5.0 these numbers may not be exact due to rounding

  24. MAJOR NOTE: if you apply == or != operators against OBJECTS then, instead of comparing the VALUES of two objects you will be comparing two REFERENCES to them (their memory addresses) • This can lead to logic errors that are VERY hard to identify • WE will deal with comparing OBJECTS in a later lecture when we discuss Java’s Number class

  25. Example: String fileName = “applet.html”; If(fileName == “applet.html”) • Compares the address of the string object fileName against the address of the literal string “applet.html”

  26. Example: String fileName = “applet.html”; If(fileName.equals( “applet.html”)) • Now this Compares the actual value of the string object fileName against the value of the literal string “applet.html”

  27. Logical Operators: • Binary operators: and && or || • Unary operators: not !

  28. Logical Operators... • True only if both are true: Condition1 && condition2 • True only if either is true: Condition1 || condition2 • True only if condition1 is false: ! Condition1 • logical operators return an boolean data type true OR false

  29. De Morgan’s Laws: Boolean has the same boolean Expression:value as: not (p and q) not p or not q not (p or q) not p and not q

  30. De Morgan’s Laws: • “not (fun and games)” is the same as “not fun or not games” • ! (p && q ) is the same as !p || !q • ! (p || q ) is the same as !p && !q

  31. THE FOLLOWING 3 SLIDES HIGHLIGHT A MAJOR DIFFERENCE BETWEEN JAVA AND C, C++ • JAVA only recognizes boolean (true or false) for expressions whereas C/C++ recognized true as NON ZERO and false as ZERO

  32. Can’t do in JAVA int a= 3, b=4, c=5; if(b>a && c) // TRUE, c is non //zero System.out.print(" b>a && c" );

  33. Can’t do in JAVA int a= 3, b=4, c=5; if(b>a && 0) //false, 0 is zero System.out.print( b>a && 0" );

  34. Can’t do in JAVA int a= 3, b=4, c=5; if(b>a && 1) //true, 1 is non zero System.out.print(“ b>a && 1" );

  35. CAN DO IN JAVA int a= 3, b=4, c=5; if(a==b || c>a)//true System.out.print( “a==b || c>a" ); ** a is not equal b, but c is > a

  36. Order of operators: • Unary operators have HIGHER precedence than Binary operators • So ! would be applied first before && or || and && is before || • You must use ( ) if the ! applies to the entire expression

  37. Example: If (!cond1 && cond2) Means If ((!cond1) && cond2) And NOT If (! (cond1 && cond2))

  38. Order of operators: • Relational operators < > == are lower than binary operators so they are applied AFTER arithmetic operators + -

  39. So the order is… • Parenthesis () • Unary operators ! • Arithmetic (* / % ) • Arithmetic (+ -) • Relational operators <, >, == • Binary operator && • Binary operator ||

  40. Order of operators... If(a + b >= 2 * n); • WHAT IS THE ORDER ???

  41. Order of operators... If(a + b >= 2 * n); • 2 * n is done 1st • a + b is done second • then these 2 values are evaluated >=

  42. Order of operators... If((a + b) >= (2 * n)) • is MUCH more readable !!!

  43. Short Circuit Evaluation: • with && and || the left operand is evaluated first • if it’s value negates the condition, the remaining conditions are not evaluated • conditions are evaluated LEFT to RIGHT

  44. int a= 3, b=4, c=5; if(a==b && c>a) System.out.print(“ a==b && c>a" ); c>a is NEVER evaluated, because a is not equal b

  45. int a= 3, b=4, c=5; if(a==b && c>a++) System.out.print(“ a==b && c>a++" ); c>a++ is NEVER evaluated, because a is not equal b, so if you expect a to be incremented, you have a logic error !!!

  46. Nested ifs: • compiler associates an else with the nearest if • if you see you are writing multiple ifs, then consider using a switch statement instead.

  47. Nested ifs... If(a<0) dostuff…; else { if(a==0) dostuff…; else dootherstuff…; dostuffiffirststufffailsevenifsecondiffails; }

  48. Example: If (points >= 90) Grade = ‘A’; Else if (points >= 80) Grade = ‘B’; Else if (points >= 70) Grade = ‘C’; Else if (points >= 60) Grade = ‘D’; Else Grade = ‘F’;

  49. Example: // surcharge calculation if (age < 25) { if (accidents) // a boolean surcharge = 1.4; else surcharge = 1.2; } else { // if age > 25 if (accidents) surcharge = 1.1; else surcharge = .9; }

  50. Common Errors: • adding the semi colon ; to the if expression • forget the semi colon ; in the body of the if • omit he braces in multiple statements in if body

More Related