Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains.

Similar presentations


Presentation on theme: "1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains."— Presentation transcript:

1 1 Statements

2 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains statements bounded by { } zWhat kinds of statements are allowed?

3 3 Statements in Java zDeclarations ÕExample: double distance = 3.5; zExpression-statements ÕExamples: xx = 5; xarea = PI * radius * radius; x++count; xa = b = c = 0; xresult = Math.pow(2.0,0.5)/3;

4 4 Statements continued zInput and output statements are in fact expression-statements ÕExamples xx = Input.readInt(); xSystem.out.println(answer); Õcontain function calls zOther statements

5 5 Other Statements zDecision Statements Õchapter 4 of text Õif-statement and switch-statement zLoops Õchapter 6 of text Õwhile-statement, for-statement, do-while- statement

6 6 Decisions in Java

7 7 Conditional Execution zSometimes we want a statement executed only when a condition is met zUse a decision statement zIn Java Õif-statement Õswitch-statement

8 8 The if-statement zSyntax if (condition) statement zNotes Õparentheses are required around the condition Õstatement means any valid statement in Java (including if-statements)

9 9 Example 1 int num; num = Input.readInt(); if (num > 100) System.out.println(“Number is large”); System.out.println(“Thanks”); // executed unconditionally

10 10 White spaces and Indentation zIn Java, spaces, tabs, and extra lines don’t affect the meaning of the program zA program could be written in diff ways; e.g., Õall in one line Õsuch that each word/symbol is in one line Õsuch that words/symbols are separated by 5 spaces each zSpaces (indentation) help to clarify intent

11 11 Example 2 zSuppose two statements need to be conditionally executed zIncorrect attempt if (num > 100) System.out.print(“The number” ); System.out.println(“ is large”); zSecond print statement will be executed unconditionally

12 12 Block of Statements zA block allows us to group several statements into one Õplace the statements in sequence and surround them with { } zCorrect code if (num > 100) { System.out.print(“The number ”); System.out.println(“is large.”); }

13 13 The Optional else Clause zIf-statement syntax revisited if (condition) statement else statement zUse whenever an alternative statement should be executed when the condition is not met

14 14 Example 3 int num; num = Input.readInt(); if (num > 100) System.out.println(“Number is large”); else System.out.println(“Number is small”);

15 15 Example 4: nested if-statements // given 3 integers (a,b,c), print them out in sorted order if (a<b) if (b<c) System.out.println(a+”,”+b+”,”+c); else if (a<c) System.out.println(a+”,”+c+”,”+b); else System.out.println(c+”,”+a+”,”+b); else...

16 16 Dangling Else if (num > 10) if (num > 100) System.out.println(“Large”); else System.out.println(“Small”); // what gets printed out when n = 150? when n = 80? when n = 5? // which if does the else clause match?

17 17 Dangling Else, continued zRule in Java: an else clause matches the nearest enclosing if zUse { } to match the outer if if (num > 10) { if (num > 100) System.out.println(“Large”); } else System.out.println(“Small”);

18 18 If-else Chain zCommon occurrence Õtesting whether one of a series of conditions is met Õconsequence: series of if statements nested on the else clauses zExample Õcomputing a letter grade

19 19 Example 5 if (score >= 90) System.out.println(“A”); else if (score >= 80) System.out.println(“B”); else if (score >= 70) System.out.println(“C”); else if (score >= 60) System.out.println(“D”); else System.out.println(“F”);

20 20 If-else Chain continued zOrder Õorder of conditions is sometimes important Õconsider letter grade example zIndentation Õif you indent at every nested level, you may need to indent excessively to the right at the later levels Õmore practical to indent at one level and adopt an if, else if, else if, … “statement”

21 21 Example 6 int num; num = Input.readInt(); if (num == 1) System.out.println(“One”); else if (num == 2) System.out.println(“Two”); else if (num == 3) System.out.println(“Three”); else System.out.println(“Other number”);

22 22 The Switch Statement switch(num) { case 1: System.out.println(“One”); break; case 2: System.out.println(“Two”); break; case 3: System.out.println(“Three”); break; default: System.out.println(“Other number”); }

23 23 Switch, continued zUse a switch statement whenever Õthe conditions in an if-else chain are designed to match values to variables (or expressions) zSwitch-statement Õjust a block of statements with “entry-point” labels zbreak; Õstatement that causes control to exit the block

24 24 The boolean Data Type zOnly two possible values ÕTRUE and FALSE zLiterals Õtrue, false Õlowercase (reserved words in Java) zOperations Õrelational operators Õlogical operators

25 25 Relational Operators zCompares two (usually numeric) operands z>, >=, <, <=, == (equal), != (not equal) zExample: >= Õbinary operation Õreturns a boolean result xtrue if left operand is greater than or equal to right operand xfalse otherwise

26 26 Logical Operators zBoolean operands z&& (and), || (or), ! (unary not) zExample ((x>=0) && (x<=9)) zTruth table depicts semantics of the operation Õsimilar to a multiplication/addition table

27 27 && (AND) zReturns a boolean result Õtrue whenever both operands are true Õfalse otherwise zExample: Õtesting whether a number is between 0 and 9 Õif ((num >= 0) && (num <= 9))... // inclusive zTruth Table?

28 28 || (OR) zReturns a boolean result Õtrue when at least one operand is true Õfalse otherwise zExample Õif ((num % 2 == 0) || (num % 3 == 0)) … Õcondition will evaluate to true if the number is a even or if it is a multiple of 3 zTruth Table?

29 29 ! (NOT) zUnary operation zReturns a boolean result Õtrue when the operand is false Õfalse when the operand is true zExample Õalternative to != Õ(a != 5) same as !(a == 5)

30 30 Boolean Variables zIt is possible to have variables of type boolean zConvenient for long conditions zExample boolean withinRange; … withinRange = (num >=0) && (num <=9) if (withinRange)...

31 31 Loops in Java

32 32 Loops zwhile-statement zfor-statement zdo-while-statement

33 33 Factorial zGiven an integer n, compute n! zWe want: result = 1*2*3*…*n; zRepetitive operation(s) Õmultiply a number i to result Õincrement the number i zDo n times starting with i = 1, result = 1: result = result * i; i = i + 1;

34 34 While statement int n, i, result; n = Input.readInt(); i = 1; result = 1; while (i <= n) { result = result * i; i = i + 1; } System.out.println(result);

35 35 For statement int n, i, result; n = Input.readInt(); result = 1; for (i = 1; i <= n; i++) result = result * i; System.out.println(result);

36 36 Do-while Statement int n, i, result; n = Input.readInt(); i = 1; result = 1; do { result = result * i; i = i + 1; } while (i <= n); System.out.println(result);

37 37 Components of a Loop zInitialization zTerminating/continuing condition zIncrementing step zLoop body

38 38 Deciding which statement to use zStatement choice is often a matter of style zFor statement Õappears most appropriate when the number of iterations is known (example: factorial) zDifference between while and do-while Õloop condition is performed at the top or at the bottom of the loop Õbody is executed at least once (for do-while)

39 39 Problems zList all even numbers (>= 0) less than 100 Õapproach 1: an if statement nested inside a for statement Õapproach 2: for statement with incrementing step i = i + 2 zList all numbers that are either multiples of 2 or multiples of 3

40 40 Problems, continued zCompute the sum of all positive even numbers less than 100 zCompute the sum of all numbers from input (stop when the number read is a zero) Õfor statement inappropriate in this case since number of iterations depends on input sequence

41 41 Nested Loops zIt is possible to have a loop within a loop zExample int i, j; // what gets printed out? for (i = 0; i < 5; i++) { System.out.println(i); for (j = 0; j < 5; j++) System.out.println(j); }

42 42 Problems using nested loops zList all pairs of numbers from the set {0, 1, 2, 3, 4} zGiven n, print an n by n block of asterisks zGiven n, print an upright triangle of asterisks with height n zGiven n, print an upside down triangle of asterisks with height n

43 43 Introduction to Arrays

44 44 Programming Problem: Reversing Input zProblem: Read in three numbers and then print out the numbers in reverse order zStraightforward Java application Õdeclare three variables of type double Õread them in using Input.readDouble() Õprint them out starting with the last variable read in

45 45 Generalizing a Program zSuppose we wanted the same program but wanted 10 instead of 3 numbers? zSuppose we wanted to read in 1000 numbers? ÕMore than 2000 lines of code if we used the same approach! zSolution: arrays

46 46 Arrays zDefinition Õcollection of elements of the same type Õeach element is accessed through an index zIn Java, Õdeclaration: double nums[]; Õcreation:nums = new double[8]; Õuse:nums[3] = 6.6; * Note: starting index is 0 (0 to 7, above)

47 47 Visualizing an Array 6.6 nums double nums[]; nums = new double[8]; nums[3] = 6.6;

48 48 Generalized Solution zInclude a constant called MAX that represents the count of numbers to be read in zUse arrays (and loops) Õdouble nums[]; // declaration Õnums = new double[MAX]; // creation Õone for-statement to read in the numbers Õanother for-statement to print them out in reverse


Download ppt "1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains."

Similar presentations


Ads by Google