Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSE 1020:Control Structure

Similar presentations


Presentation on theme: "CSE 1020:Control Structure"— Presentation transcript:

1 CSE 1020:Control Structure
Mark Shtern

2 Selection

3 Flow of Control Flow of control refers to order in which statements are executed Sequence flow S1 S2 S3

4 Flow of Control Selection flow S2 S2.1 S4 S1 S3 S3.1

5 Flow of Control Selection flow True S2 S2.1 S4 S1 S3 S3.1 False

6 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

7 If statement If (count > maximum) { count--; output.println(“Maximum exceeded.”); }

8 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

9 Answer output.print(“Enter an integer...”); int entry = input.nextInt(); int absValue = entry; If (entry < 0 ) { absValue = - entry; } output.println(absValue);

10 Example 5.2 Rewrite solution of previous Example such that no defaults are used.

11 Answer output.print(“Enter an integer...”); int entry = input.nextInt(); int absValue; if (entry < 0) { absValue = -entry; } else absValue = entry; output.println(absValue);

12 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

13 deMorgan law !(A && B) is equivalent to (!A) || (!B) !(A || B) is equivalent to (!A) && (!B)

14 Examples if (x >= a && x <b) If (!(x >= a && x <b) )
If (x.equals(y)) vs if (x!=null && x.equals(y))

15 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.

16 Answer If ( x == 0 || y % x !=0) { output.println(“”Not a multiple.”); } else ouput.println(“Yes, it is a multiple”);

17 Multiway if Statement-S If (condition-1) { Statements-A } else if (condition-2) Statements-B } else if (condition-3) Statements-C } Statements-X

18 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

19 Nested IF if ( x<=a && y >d) if ( x<=a) { if (y >d) }

20 Switch If (gender == ‘M’) { male++; } else if (gender == ‘F’) female++; } else other++; } switch (gender) { case ‘M’: male++ break; case ‘F’: female++; default: other++; }

21 Predict results (Ex505) int x =1; boolean b1 = (x > 0); boolean b2 = false; boolean b3 = b1 && !b2; If (b3 || x == 1) { x++; }

22 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; }


Download ppt "CSE 1020:Control Structure"

Similar presentations


Ads by Google