680 likes | 1.14k Views
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.
E N D
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
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.
if(condition) { do stuff…; } else { do other stuff…; }
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.
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; }
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; }
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; }
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
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;
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
Boolean (True & False): • This code is the same as: boolean over21; If (age > 21) over21 = true; else over21 = false;
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 }
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" ); }
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 ?
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
//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 ?
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
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
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
if(x > y) max = x; else max = y;
Remember that == means “is equal to” while = means assignment
if(gender != ‘M’) { System.out.print(“Dear Ms.”); } else { System.out.print(“Dear Mr.”); }
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
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
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”
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”
Logical Operators: • Binary operators: and && or || • Unary operators: not !
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
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
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
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
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" );
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" );
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" );
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
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
Example: If (!cond1 && cond2) Means If ((!cond1) && cond2) And NOT If (! (cond1 && cond2))
Order of operators: • Relational operators < > == are lower than binary operators so they are applied AFTER arithmetic operators + -
So the order is… • Parenthesis () • Unary operators ! • Arithmetic (* / % ) • Arithmetic (+ -) • Relational operators <, >, == • Binary operator && • Binary operator ||
Order of operators... If(a + b >= 2 * n); • WHAT IS THE ORDER ???
Order of operators... If(a + b >= 2 * n); • 2 * n is done 1st • a + b is done second • then these 2 values are evaluated >=
Order of operators... If((a + b) >= (2 * n)) • is MUCH more readable !!!
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
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
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 !!!
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.
Nested ifs... If(a<0) dostuff…; else { if(a==0) dostuff…; else dootherstuff…; dostuffiffirststufffailsevenifsecondiffails; }
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’;
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; }
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