DOC PREVIEW
Penn CIT 591 - Simple Control Structures

This preview shows page 1-2-20-21 out of 21 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 21 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 21 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 21 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 21 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 21 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

Simple Control StructuresWhat are control structures?For C and C++ programmers onlybooleanDeclaring boolean variablesNumeric comparisonsThe if statementCompound statementsThe if statement againFlowchart for the if statementThe if-else statementExample if-else statementsFlowchart for the if-else statementAside: the “mod” operatorNesting if (or if-then) statementsOperations on booleansSimpler testsThe while loopFlowchart for the while loopCountdown exampleThe EndJan 14, 2019Simple Control Structuresbooleans, the if statement, and the while loop2What are control structures?You can’t do very much if your program consists of just a list of commands to be done in orderThe program cannot choose whether or not to perform a commandThe program cannot perform the same command more than onceSuch programs are extremely limited!Control structures allow a program to base its behavior on the values of variables3For C and C++ programmers onlyStatement types are almost identical to those in C and C++Main difference: true/false conditions must be boolean, not numeric!Some unusual uses of the comma in for statements are not permitted in JavaThere are two new statement types (try and assert) which we won’t talk about today4booleanboolean is one of the eight primitive types booleans are used to make yes/no decisionsAll control structures use booleansThere are exactly two boolean values, true (“yes”) and false (“no”)boolean, true, and false are all lowercasebooleans are named after George Boole, the founder of Boolean logic5Declaring boolean variablesboolean variables are declared like any other kind of variable: boolean hungry; boolean passingGrade; boolean taskCompleted = false;boolean values can be assigned to boolean variables: taskCompleted = true;6Numeric comparisonsThe following numeric comparisons each give a boolean result: x < y // is x less than y? x <= y// is x less than or equal to y? x == y// is x equal to y? (do not use =) x != y // is x unequal to y? x >= y// is x greater than or equal to y? x > y // is x greater than y?Reminder: Don’t use == or != for floating-point numbers7The if statementThe if statement has the form: if (boolean-expression) statementExamples: if (passingGrade) System.out.println("Whew!"); if (x > largest) largest = x; if (citBook.price < 40.00) citBook.purchase();The if statement controls one other statementOften this isn’t enough; we want to control a group of statements8Compound statementsWe can use braces to group together several statements into one “compound” statement: { statement; statement; ...; statement; }Braces can group any number of statements: { } // OK--this is an “empty” statement { x = 0; } // OK--braces don’t hurt { temp = x; x = y; y = temp; } //typical useThe compound statement is the only kind of statement that does not end with a semicolon9The if statement againThe if statement controls one other statement, but it can be a compound statementExample: if (cost < amountInPocket) { System.out.println("Spending $" + cost); amountInPocket = amountInPocket - cost;}It’s good style to use braces even if the if statement controls only a single statement: if (cost > amountInPocket) { System.out.println("You can't afford it!");}•I personally make an exception to this style rule when the controlled statement fits easily on the same line with the if: if (x < 0) x = -x; // use absolute value of x10Flowchart for the if statementcondition?statementtruefalse11The if-else statementThe if-else statement chooses which of two statements to executeThe if-else statement has the form: if (condition) statement-to-execute-if-true ;else statement-to-execute-if-false ;Either statement (or both) may be a compound statementNotice the semicolon after each controlled statement12Example if-else statementsif (x >= 0) absX = x;else absX = -x;if (itemCost <= bankBalance) { writeCheck(itemCost); bankBalance = bankBalance - itemCost;}else { callHome(); askForMoreMoney(2 * itemCost);}13Flowchart for the if-else statementcondition?truestatement-1 statement-2false14Aside: the “mod” operatorThe modulo, or “mod,” operator returns the remainder of an integer divisionThe symbol for this operation is %Examples: 57 % 10 gives 7 20 % 6 gives 2Useful rule: x is divisible by y if x % y == 0If the left operand is negative, the result is negative (or zero)Examples: -20 % 3 = -2, 20 % -3 = 2, -20 % -3 = -215Nesting if (or if-then) statementsA year is a leap year if it is divisible by 4 but not by 100, unless it is also divisible by 400 if (year % 4 == 0) { if (year % 100 == 0) { if (year % 400 == 0) leapYear = true; else leapYear = false; } else leapYear = true;}else leapYear = false;16Operations on booleansAssume p and q are booleansThere are four basic operations on booleans:Negation (“not”): !p is true if p is false (and false otherwise)Conjunction (“and”): p && q is true if both p and q are trueDisjunction (“or”): p || q is true if either of p and q is trueExclusive or (“xor”): p ^ q is true if just one of p and q is true17Simpler testsA simpler leap-year test: if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) leapYear = true;else leapYear = false;An even simpler leap-year test: leapYear = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);18The while loopThis is the form of the while loop:while (condition) statement ;If the condition is true, the statement is executed, then the whole thing is done againThe statement is executed repeatedly until the condition becomes falseIf the condition starts out false, the statement is never executed at all19Flowchart for the while loopcondition?statementtruefalse20Countdown example seconds = 5;while (seconds > 0) { System.out.print(seconds + "..."); seconds = seconds - 1;}System.out.println("Blast off!"); Result: 5...4...3...2...1...Blast off!21The


View Full Document

Penn CIT 591 - Simple Control Structures

Documents in this Course
Stacks

Stacks

11 pages

Arrays

Arrays

30 pages

Arrays

Arrays

29 pages

Applets

Applets

24 pages

Style

Style

33 pages

JUnit

JUnit

23 pages

Java

Java

32 pages

Access

Access

18 pages

Methods

Methods

29 pages

Arrays

Arrays

32 pages

Methods

Methods

9 pages

Methods

Methods

29 pages

Vectors

Vectors

14 pages

Eclipse

Eclipse

23 pages

Vectors

Vectors

14 pages

Recursion

Recursion

24 pages

Animation

Animation

18 pages

Animation

Animation

18 pages

Static

Static

12 pages

Eclipse

Eclipse

23 pages

JAVA

JAVA

24 pages

Arrays

Arrays

29 pages

Animation

Animation

18 pages

Numbers

Numbers

21 pages

JUnit

JUnit

23 pages

Access

Access

18 pages

Applets

Applets

24 pages

Methods

Methods

30 pages

Buttons

Buttons

20 pages

Java

Java

31 pages

Style

Style

28 pages

Style

Style

28 pages

Load more
Download Simple Control Structures
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Simple Control Structures and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Simple Control Structures 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?