CSE 1020:Control Structure Mark Shtern
Selection
Flow of Control Flow of control refers to order in which statements are executed Sequence flow S1 S2 S3
Flow of Control Selection flow S2 S2.1 S4 S1 S3 S3.1
Flow of Control Selection flow True S2 S2.1 S4 S1 S3 S3.1 False
Flow of Control Selection flow If (condition) { statement-S2 } else statement-S3 statement-S3.1 True S2 S2.1 S4 S1 S3 S3.1 False
If statement If (count > maximum) { count--; output.println(“Maximum exceeded.”); }
Example 5.1 Write a fragment that prompts for and reads an integer from the user and outputs its absolute value without using Math.abs
Answer output.print(“Enter an integer...”); int entry = input.nextInt(); int absValue = entry; If (entry < 0 ) { absValue = - entry; } output.println(absValue);
Example 5.2 Rewrite solution of previous Example such that no defaults are used.
Answer output.print(“Enter an integer...”); int entry = input.nextInt(); int absValue; if (entry < 0) { absValue = -entry; } else absValue = entry; output.println(absValue);
Building the Condition Relational Expression Boolean Variable Boolean-Returning Method Boolean Expression Operator Syntax true if ! !x x is false && x && y x and y are both true || x|| y either x or y or both are true
deMorgan law !(A && B) is equivalent to (!A) || (!B) !(A || B) is equivalent to (!A) && (!B)
Examples if (x >= a && x <b) If (!(x >= a && x <b) ) If (x.equals(y)) vs if (x!=null && x.equals(y))
Example 5.3 Write a fragment that determine whether a given integer y is a multiple of a given integer x, and output message accordingly. Note that no integer is a multiple of zero.
Answer If ( x == 0 || y % x !=0) { output.println(“”Not a multiple.”); } else ouput.println(“Yes, it is a multiple”);
Multiway if Statement-S If (condition-1) { Statements-A } else if (condition-2) Statements-B } else if (condition-3) Statements-C } Statements-X
Example 5.5 Write a program that prompts for and reads an year (an int) from a user. If the entry is not positive, the program crash. Otherwise, it should output a messages that indicates whether the year entered is a leap year
Nested IF if ( x<=a && y >d) if ( x<=a) { if (y >d) }
Switch If (gender == ‘M’) { male++; } else if (gender == ‘F’) female++; } else other++; } switch (gender) { case ‘M’: male++ break; case ‘F’: female++; default: other++; }
Predict results (Ex505) int x =1; boolean b1 = (x > 0); boolean b2 = false; boolean b3 = b1 && !b2; If (b3 || x == 1) { x++; }
Predict results (Ex506) int x =1; int y = -1; If (x >=y && y > 0) { x++; y = x; } else if (x == y || y < 1) { x--; } else { y = 0; }