1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA...

Post on 04-Jan-2016

219 views 1 download

Transcript of 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA...

1

Statements

2

Java Program Structure Revisited

A Java program consists of a class definition

A class contains method definitionsEach method contains statements

bounded by { }What kinds of statements are

allowed?

3

Statements in Java

DeclarationsExample: double distance = 3.5;

Expression-statementsExamples:

x = 5;area = PI * radius * radius;++count;a = b = c = 0;result = Math.pow(2.0,0.5)/3;

4

Statements continued

Input and output statements are in fact expression-statementsExamples

x = Input.readInt();System.out.println(answer);

contain function callsOther statements

5

Other Statements

Decision Statementschapter 4 of textif-statement and switch-statement

Loopschapter 6 of textwhile-statement, for-statement, do-

while-statement

6

Decisions in Java

7

Conditional Execution

Sometimes we want a statement executed only when a condition is met

Use a decision statementIn Java

if-statementswitch-statement

8

The if-statement

Syntaxif (condition) statement

Notesparentheses are required around the

conditionstatement means any valid statement in

Java (including if-statements)

9

Example 1

int num;

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

unconditionally

10

White spaces and Indentation

In Java, spaces, tabs, and extra lines don’t affect the meaning of the program

A program could be written in diff ways; e.g.,all in one linesuch that each word/symbol is in one linesuch that words/symbols are separated by 5

spaces eachSpaces (indentation) help to clarify intent

11

Example 2

Suppose two statements need to be conditionally executed

Incorrect attemptif (num > 100) System.out.print(“The number” ); System.out.println(“ is large”);

Second print statement will be executed unconditionally

12

Block of Statements

A block allows us to group several statements into oneplace the statements in sequence and

surround them with { }Correct code

if (num > 100) { System.out.print(“The number ”); System.out.println(“is large.”);}

13

The Optional else Clause

If-statement syntax revisitedif (condition) statementelse statement

Use whenever an alternative statement should be executed when the condition is not met

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

Example 4:nested if-statements

// given 3 integers (a,b,c), print them out in sorted orderif (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

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

Dangling Else, continued

Rule in Java: an else clause matches the nearest enclosing if

Use { } to match the outer ifif (num > 10) { if (num > 100) System.out.println(“Large”);}else System.out.println(“Small”);

18

If-else Chain

Common occurrencetesting whether one of a series of

conditions is metconsequence: series of if statements

nested on the else clausesExample

computing a letter grade

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

If-else Chain continued

Orderorder of conditions is sometimes importantconsider letter grade example

Indentationif 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

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

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

Switch, continued

Use a switch statement wheneverthe conditions in an if-else chain are designed

to match values to variables (or expressions)Switch-statement

just a block of statements with “entry-point” labels

break;statement that causes control to exit the

block

24

The boolean Data Type

Only two possible valuesTRUE and FALSE

Literalstrue, falselowercase (reserved words in Java)

Operationsrelational operatorslogical operators

25

Relational Operators

Compares two (usually numeric) operands

>, >=, <, <=, == (equal), != (not equal)Example: >=

binary operationreturns a boolean result

true if left operand is greater than or equal to right operand

false otherwise

26

Logical Operators

Boolean operands&& (and), || (or), ! (unary not)Example

((x>=0) && (x<=9))

Truth table depicts semantics of the operationsimilar to a multiplication/addition table

27

&& (AND)

Returns a boolean resulttrue whenever both operands are truefalse otherwise

Example:testing whether a number is between 0

and 9 if ((num >= 0) && (num <= 9)) ... // inclusive

Truth Table?

28

|| (OR)

Returns a boolean resulttrue when at least one operand is truefalse otherwise

Example 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

Truth Table?

29

! (NOT)

Unary operationReturns a boolean result

true when the operand is falsefalse when the operand is true

Examplealternative to !=(a != 5) same as !(a == 5)

30

Boolean Variables

It is possible to have variables of type boolean

Convenient for long conditionsExample

boolean withinRange;…withinRange = (num >=0) && (num <=9)if (withinRange) ...

31

Loops in Java

32

Loops

while-statementfor-statementdo-while-statement

33

Factorial

Given an integer n, compute n!We want: result = 1*2*3*…*n;Repetitive operation(s)

multiply a number i to resultincrement the number i

Do n times starting with i = 1, result = 1:

result = result * i;i = i + 1;

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

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

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

Components of a Loop

InitializationTerminating/continuing conditionIncrementing stepLoop body

38

Deciding which statement to use

Statement choice is often a matter of style

For statementappears most appropriate when the number

of iterations is known (example: factorial)Difference 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

Problems

List all even numbers (>= 0) less than 100approach 1: an if statement nested

inside a for statementapproach 2: for statement with

incrementing step i = i + 2List all numbers that are either

multiples of 2 or multiples of 3

40

Problems, continued

Compute the sum of all positive even numbers less than 100

Compute 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

Nested Loops

It is possible to have a loop within a loop

Exampleint 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

Problems using nested loops

List all pairs of numbers from the set{0, 1, 2, 3, 4}

Given n, print an n by n block of asterisks

Given n, print an upright triangle of asterisks with height n

Given n, print an upside down triangle of asterisks with height n

43

Introduction to Arrays

44

Programming Problem:Reversing Input

Problem: Read in three numbers and then print out the numbers in reverse order

Straightforward Java applicationdeclare three variables of type doubleread them in using Input.readDouble()print them out starting with the last

variable read in

45

Generalizing a Program

Suppose we wanted the same program but wanted 10 instead of 3 numbers?

Suppose we wanted to read in 1000 numbers?More than 2000 lines of code if we used

the same approach!Solution: arrays

46

Arrays

Definitioncollection of elements of the same typeeach element is accessed through an index

In Java,declaration: double nums[];creation: nums = new double[8];use: nums[3] = 6.6;

* Note: starting index is 0 (0 to 7, above)

47

Visualizing an Array

6.6

nums

double nums[];

nums = new double[8];

nums[3] = 6.6;

48

Generalized Solution

Include a constant called MAX that represents the count of numbers to be read in

Use arrays (and loops)double nums[]; // declarationnums = new double[MAX]; // creationone for-statement to read in the numbersanother for-statement to print them out in

reverse