CPSC 111. October 15 th, Based on slides by Eiselt, Carter, Murphy, Pottinger

Full text

(1)

CPSC 111

Introduction to Computation Introduction to Computation

October 15

th

, 2009

Based on slides by Eiselt, Carter, Murphy, Pottinger

(2)

The good news from the exam The good news from the exam...

45 ********

44 ********

43 ***************** A+

30 **

29 *

28 *** C

15 14 13 **

42 ***********

41 ********

40 *******

39 *

38 **** A

27 * 26 **

25 ***

24 D 23 *

12 * 11 10 *

9 * 8 38 **** A

37 **

36 **

35 ******

34 *******

23 * 22 ***

21 **

20 * 19 ** F

8 7 6 5 4 **

33 **** B 32 ****

31 *

18 17 **

16

3 2

1

Average = 79.2%

(3)

And now the bad news

And now the bad news…

The second midterm exam will be much more h ll i th th fi t

challenging than the first exam.

There will be more material.

The material will be more complex.

We'll expect that you'll know the material we've covered so far much better than you know it now.

If your mark on the first midterm exam was 23 or

lower, you should come meet with me in office hours.

(4)

Administrative stuff Administrative stuff

You'll get your exams back in your labs next week.

If you think your exam should be re-evaluated, don't take your exam from the lab. You must return the exam to your TA before you leave. We will not re-evaluate any exam that was not returned to the TA in the lab.

(5)

H1N1-related absences

If (you missed the exam because you were sick

&&

&&

you submitted the H1N1 report or a doctor note) The weight of this midterm (10%) will be shifted to the second midterm (which will then have a weight of 20%)

(6)

Administrative Stuff

Administrative Stuff

(7)

Administrative Stuff Administrative Stuff

Big reading in Big Java (2nd or 3rd edition):

Chapter 1.1 through 1.8 Chapter 2 1 through 2 10 Chapter 2.1 through 2.10

Chapter 4.1, 4.7 before your next lab Chapter 3.1 through 3.8p g

Chapter 4

Chapter 5 (3rd ed.) or 6 (2nd ed.)

Chapter 6.1-6.5 (3rd ed.) or 7.1-7.5 (2nd ed.)

(8)

Review of last class Review of last class

1 C diti l i D th 1. Conditionals in Depth

(9)

To summarize To summarize

• We’d been discussing conditionals We d been discussing conditionals

• In particular, we discussed the if‐then statement:

If (condition) If (condition) {

//things done }

else {{

//do something else }

(10)

What does a condition look like?

What does a condition look like?

• Relational operators (e g a < b b>=a a != b) Relational operators (e.g., a < b, b>=a, a != b)

• Possibly combined by logical operators:

&& b ( AND b) – a && b (a AND b) – a || b (a OR b) – !a

(11)

Today’s plan

1 C i D t d M D t

1. Comparing Data and More on Data Conversion

2 Introduction to loops: the While statement 2. Introduction to loops: the While statement

(12)

Comparing data Comparing data

Is 0.3 the same thing as 1.0/10.0 + 1.0/10.0 + 1.0/10 ???

Let’s try it out...

(13)

Comparing data Comparing data

Is 0.3 the same thing as 1.0/10.0 + 1.0/10.0 + 1.0/10 ???

No. Math with floating point numbers often gives results that are very close to what you’d expect but not exactly the same. The

calculation of 1 0/10 0 + 1 0/10 0 + 1 0/10 yields 0 30000000000000004 calculation of 1.0/10.0 + 1.0/10.0 + 1.0/10 yields 0.30000000000000004 So beware. And write tests for “darn near equal” that look like this:

if (Math.abs(f1 - f2) < TOLERANCE)

System.out.println (“Essentially equal.”);

where TOLERANCE is a small number appropriate to the problem like 0.00000001

(14)

Comparing data Comparing data

Is 0.3 the same thing as 1.0/10.0 + 1.0/10.0 + 1.0/10 ???

No. Math with floating point numbers often gives results that are very close to what you’d expect but not exactly the same. The calculation of 1 0/10 0 + 1 0/10 0 + 1 0/10 yields

calculation of 1.0/10.0 + 1.0/10.0 + 1.0/10 yields 0.30000000000000004

The details of why this happens are beyond the scope of this course The details of why this happens are beyond the scope of this course, but the anomaly basically due to the fact that 0.1 cannot be exactly represented in the standard binary floating point notation

It is approximated by the closest 23 bit binary fraction 0.000110011001100110011...

The approximation comes up in funny ways during mathematical operations, as we have seen.

(15)

import java.util.Scanner;

public class ComparingFloats {

public static void main(String[] args) {

double result;

result = (1.0/10.0+1.0/10.0);

System.out.println(result);

if (0.2 == result)

System.out.println(result + " is equal to 0.2");

else System.out.println("FALSE");

}}

(16)

Comparing data

You can compare character types:

'a' < 'b' 'a' == 'b' 'a' < 'A'

with your relational operators. Why?

(17)

Comparing data

You can compare character types:

'a' < 'b' 'a' == 'b' 'a' < 'A'

with your relational operators. Why?

Because each character is associated with a number by the Java coding Because each character is associated with a number by the Java coding System (Unicode).

(18)

Comparing data

But don’t use relational operators to compare character strings.

Strings are objects, so you need to call on the equals method from the String class.

"abc" == "abc"

won’t blow up it just tests to see if these two strings have the same won t blow up, it just tests to see if these two strings have the same address or location in memory. They usually don’t. (remember?)

(19)

Back to Data Conversion Back to Data Conversion

The arithmetic we do in our head isn’t the same as the math that’s done b Ja a For e ample e think of 1 / 3 as

that’s done by Java. For example, we think of 1 / 3 as 0.3333333333333333333333333333333333...

But what happens when we tell Java to do the same thing?

Well, it depends...

int a = 1 / 3; // a is 0 double b = 1 / 3; // b is 0.0

int c = 1.0 / 3.0; // Java’s not happy

d bl d / // d i

double d = 1.0 / 3.0; // d is 0.3333333333333333

(20)

Data conversion Data conversion

Let’s look at them one at a time:

int a = 1 / 3; // a is 0

The literals 1 and 3 are integers The literals 1 and 3 are integers.

Arithmetic with integers results in an integer.

The fractional part is discarded or truncated.

So the value 0 is assigned to a.

(21)

Data conversion Data conversion

double b = 1 / 3; // b is 0.0

The literals 1 and 3 are still integers. Arithmetic with integers still results in an integer.

But we declared variable b of type double -- a floating point number.

So Java takes the result of 0 that comes from the right hand side of the assignment statement and converts it to hand side of the assignment statement and converts it to its floating point equivalent, 0.0, and assigns that

converted value to b.

(22)

Data conversion Data conversion

int c 1 0 / 3 0 // Java’s not happy int c = 1.0 / 3.0; // Java’s not happy

The operands on the right hand side are now floating point numbers so the result of the division is a floating point

numbers, so the result of the division is a floating point representation of 0.3333....

But we’ve declared c to be of type int. To convert the result to an integer, Java would have to drop the .3333....

.3333....

Java doesn’t want to do this unless it’s really sure you want it to happen More on this in a moment

want it to happen. More on this in a moment.

(23)

Data conversion

double d = 1.0 / 3.0; // d is 0.3333333333333333

Th d th i ht h d id i fl ti

The operands on the right hand side are again floating point numbers, so the result of the division is again a floating point representation of 0.3333.... g p p

That’s compatible with the type of the variable d, which is double -- the biggest of the floating point types Java is double -- the biggest of the floating point types. Java is happy, we’re happy, except…

h t h d t th i fi it l ti i f 3’ ?

… what happened to the infinitely repeating series of 3’s?

A finite number of bits have been allocated to represent p The value, so Java has to round off at some point.

(24)

Data conversion Data conversion

There are two categories of data conversions:

Widening conversions go from one data type to another type that uses and equal or greater amount of space to store the value.

Widening conversions are safer because they usually don’t lose information (though there can be some roundoff).

Narrowing conversions typically go from one type to another type that uses less space to store the value.

another type that uses less space to store the value.

Important information may be lost; avoid narrowing conversions.

(25)

Data conversion Data conversion

Which of these is a widening conversion? Which is a narro ing con ersion?

narrowing conversion?

int a = 1 / 3; // a is 0 double b = 1 / 3; // b is 0.0

int c = 1 0 / 3 0; // Java’s not happy int c = 1.0 / 3.0; // Java s not happy

double d = 1.0 / 3.0; // d is 0.3333333333333333

(26)

Data conversion Data conversion

Which of these is a widening conversion? Which is a narro ing con ersion?

narrowing conversion?

int a = 1 / 3;

double b = 1 / 3; // b is 0.0 - widening int c = 1 0 / 3 0; // narrowing

int c = 1.0 / 3.0; // narrowing double d = 1.0 / 3.0;

(27)

Data conversion Data conversion

Data conversion can happen in three different ways.

1. Assignment conversion happens when a value of one type is assigned to a variable of another type and the value must be converted to the new type.

As we’ve just seen Java will not allow a narrowing As we ve just seen, Java will not allow a narrowing

conversion to happen through assignment, but it’s happy to do widening conversions through assignment.

(28)

Data conversion Data conversion

Data conversion can happen in three different ways.

2. Promotion can happen when an expression contains mixed data types. Consider this code snippet:

int hours_worked = 40;

double pay rate = 5.25;

double pay rate 5.25;

double total_pay = hours_worked * pay_rate;

To perform the multiplication Java promotes the value To perform the multiplication, Java promotes the value assigned to hours_worked to a floating point value to produce a floating point result

(29)

Data conversion Data conversion

What would happen in this case?

int hours_worked = 40;

double pay rate = 5.25;

double pay rate 5.25;

int total_pay = hours_worked * pay_rate;

Would the value in t be “demoted” to an integer?

Would the value in pay rate be demoted to an integer?

Error: Bad types in assignment

>

(30)

Data conversion Data conversion

Data conversion can happen in three different ways.

3. You can force data conversion through casting, if the conversion is possible. A cast is a Java operator that is specified by a type name in parentheses placed in front of the value to be converted. For example:

double foo = 3.14159;

int bar = foo; // doesn’t work

i t b (i t) f // thi k

int bar = (int) foo; // this works

What’s the value in bar when it’s all done? Hint: it's an integer.

(31)

So where are we?

So where are we?

• We learned We learned

– programming language basics about classes

– about classes

– about conditionals (if statements)

Th t’ l t l t’ if d thi

• That’s a lot, let’s see if we can do something 

useful, like…

(32)

…Washing dishes (when the 

d h h b k )

dishwasher is broken)

(33)

Exercise Exercise

• Using Using only constructs that we have learned so  only constructs that we have learned so far , write a procedure (in english, not in java)  to wash a huge pile of dishes by hand

to wash a huge pile of dishes by hand

(34)

Exercise Exercise

• Hard no? Hard no?

d hi h ll j

• We need something that allows java to go 

around in circles

(35)

Today’s plan

1 C i D t d M D t

1. Comparing Data and More on Data Conversion

2 Introduction to loops: the While statement 2. Introduction to loops: the While statement

(36)

Repetition iteration and loops Repetition, iteration, and loops

One of the most important attributes of a computer is its

ability to perform the same task many many times We give ability to perform the same task many many times. We give computer programs this ability through the use of iteration statements, also called repetition statements, but more

l j t ll d l

commonly just called loops.

We see repetitive operations -- loops -- in real life all the time.

For example...

(37)

How do I get up the stairs?

How do I get up the stairs?

Am I at the top of the stairs?

No.

Climb up one step.

Am I at the top of the stairs?

No No.

Climb up one step.

Am I at the top of the stairs?

No.

Climb up one step.

Am I at the top of the stairs?

No.

Climb up one step Climb up one step.

Am I at the top of the stairs?

No.

Climb up one step.

...and so on...

(38)

The while statement The while statement

The simplest form of a loop in Java is the while statement.

A while statement evaluates a Boolean expression, just like the ifp , j statement, and executes a statement (or block of statements) if the expression is true.

while ( <some Boolean expression goes here> ) {

<one or more statements go here> // the body }

}

After the statement or statements (called the loop body) are

executed the Boolean expression is evaluated again If the expression executed, the Boolean expression is evaluated again. If the expression is still true, the body is executed again. This repetition continues until the expression is false, when processing continues with the statement after the body of the while loop

after the body of the while loop.

(39)

if versus while statement if versus while statement

boolean expression

true false

statement

how the if statement works

(40)

if versus while statement if versus while statement

boolean expression

boolean expression

true false true false

statement statement

how the if statement works how the while statement works

(41)

if versus while statement if versus while statement

boolean expression

boolean expression

true false true false

statement statement

What can make this boolean expression false if it was previously true?

(42)

if versus while statement if versus while statement

boolean expression

boolean expression

true false true false

statement statement

Oh, by the way, diagrams like these are called flowcharts.

(43)

Using the while statement

public class WhileDemo {

public static void main (String[] args)

Using the while statement

p ( g[] g )

{

int limit = 3;

int counter = 1;

while (counter <= limit) {

System.out.println("The square of " + counter +

" is " + (counter * counter));; counter = counter + 1;

}

System.out.println("End of demonstration");

} } }

Here's the while statement

(44)

Using the while statement

public class WhileDemo {

public static void main (String[] args)

Using the while statement

p ( g[] g )

{

int limit = 3;

int counter = 1;

while (counter <= limit) {

System.out.println("The square of " + counter +

" is " + (counter * counter));; counter = counter + 1;

}

System.out.println("End of demonstration");

} } }

Here's the boolean expression

(45)

Using the while statement

public class WhileDemo {

public static void main (String[] args)

Using the while statement

p ( g[] g )

{

int limit = 3;

int counter = 1;

while (counter <= limit) {

System.out.println("The square of " + counter +

" is " + (counter * counter));; counter = counter + 1;

}

System.out.println("End of demonstration");

} } }

Here's the body of the while statement

(46)

Using the while statement

public class WhileDemo {

public static void main (String[] args)

Using the while statement

p ( g[] g )

{

int limit = 3;

int counter = 1;

while (counter <= limit) {

System.out.println("The square of " + counter +

" is " + (counter * counter));; counter = counter + 1;

}

System.out.println("End of demonstration");

} } }

Here's the first statement following the while statement. Flow of control resumes here when the boolean expression is false.

(47)

Using the while statement

public class WhileDemo {

public static void main (String[] args)

Using the while statement

p ( g[] g )

{

int limit = 3;

int counter = 1;

while (counter <= limit) {

System.out.println("The square of " + counter +

" is " + (counter * counter));; counter = counter + 1;

}

System.out.println("End of demonstration");

} } }

So what happens when we execute this?

(48)

Using the while statement

public class WhileDemo {

public static void main (String[] args)

Using the while statement

p ( g[] g )

{

int limit = 3;

int counter = 1;

while (counter <= limit) {

System.out.println("The square of " + counter +

" is " + (counter * counter));; counter = counter + 1;

}

System.out.println("End of demonstration");

} } }

limit 3

(49)

Using the while statement

public class WhileDemo {

public static void main (String[] args)

Using the while statement

p ( g[] g )

{

int limit = 3;

int counter = 1;

while (counter <= limit) {

System.out.println("The square of " + counter +

" is " + (counter * counter));; counter = counter + 1;

}

System.out.println("End of demonstration");

} } }

limit counter3 1

(50)

Using the while statement

public class WhileDemo {

public static void main (String[] args)

Using the while statement

p ( g[] g )

{

int limit = 3;

int counter = 1;

while (counter <= limit) {

System.out.println("The square of " + counter +

" is " + (counter * counter));; counter = counter + 1;

}

System.out.println("End of demonstration");

} } }

limit counter3 1 Is counter <= limit? yes

(51)

Using the while statement

public class WhileDemo {

public static void main (String[] args)

Using the while statement

p ( g[] g )

{

int limit = 3;

int counter = 1;

while (counter <= limit) {

System.out.println("The square of " + counter +

" is " + (counter * counter));; counter = counter + 1;

}

System.out.println("End of demonstration");

} } }

limit counter3 1

"The square of 1 is 1" printed on monitor

(52)

Using the while statement

public class WhileDemo {

public static void main (String[] args)

Using the while statement

p ( g[] g )

{

int limit = 3;

int counter = 1;

while (counter <= limit) {

System.out.println("The square of " + counter +

" is " + (counter * counter));; counter = counter + 1;

}

System.out.println("End of demonstration");

} } }

limit counter3 2

(53)

Using the while statement

public class WhileDemo {

public static void main (String[] args)

Using the while statement

p ( g[] g )

{

int limit = 3;

int counter = 1;

while (counter <= limit) {

System.out.println("The square of " + counter +

" is " + (counter * counter));; counter = counter + 1;

}

System.out.println("End of demonstration");

} } }

limit counter3 2 Is counter <= limit? yes

(54)

Using the while statement

public class WhileDemo {

public static void main (String[] args)

Using the while statement

p ( g[] g )

{

int limit = 3;

int counter = 1;

while (counter <= limit) {

System.out.println("The square of " + counter +

" is " + (counter * counter));; counter = counter + 1;

}

System.out.println("End of demonstration");

} } }

limit counter3 2

"The square of 2 is 4" printed on monitor

(55)

Using the while statement

public class WhileDemo {

public static void main (String[] args)

Using the while statement

p ( g[] g )

{

int limit = 3;

int counter = 1;

while (counter <= limit) {

System.out.println("The square of " + counter +

" is " + (counter * counter));; counter = counter + 1;

}

System.out.println("End of demonstration");

} } }

limit counter3 3

(56)

Using the while statement

public class WhileDemo {

public static void main (String[] args)

Using the while statement

p ( g[] g )

{

int limit = 3;

int counter = 1;

while (counter <= limit) {

System.out.println("The square of " + counter +

" is " + (counter * counter));; counter = counter + 1;

}

System.out.println("End of demonstration");

} } }

limit counter3 3 Is counter <= limit? yes

(57)

Using the while statement

public class WhileDemo {

public static void main (String[] args)

Using the while statement

p ( g[] g )

{

int limit = 3;

int counter = 1;

while (counter <= limit) {

System.out.println("The square of " + counter +

" is " + (counter * counter));; counter = counter + 1;

}

System.out.println("End of demonstration");

} } }

limit counter3 3

"The square of 3 is 9" printed on monitor

(58)

Using the while statement

public class WhileDemo {

public static void main (String[] args)

Using the while statement

p ( g[] g )

{

int limit = 3;

int counter = 1;

while (counter <= limit) {

System.out.println("The square of " + counter +

" is " + (counter * counter));; counter = counter + 1;

}

System.out.println("End of demonstration");

} } }

limit counter3 4

(59)

Using the while statement

public class WhileDemo {

public static void main (String[] args)

Using the while statement

p ( g[] g )

{

int limit = 3;

int counter = 1;

while (counter <= limit) {

System.out.println("The square of " + counter +

" is " + (counter * counter));; counter = counter + 1;

}

System.out.println("End of demonstration");

} } }

limit counter3 4 Is counter <= limit? Nooooooo!

(60)

Using the while statement

public class WhileDemo {

public static void main (String[] args)

Using the while statement

p ( g[] g )

{

int limit = 3;

int counter = 1;

while (counter <= limit) {

System.out.println("The square of " + counter +

" is " + (counter * counter));; counter = counter + 1;

}

System.out.println("End of demonstration");

} } }

limit counter3 4

"End of demonstration" printed on monitor

(61)

How do I get up the stairs again?

How do I get up the stairs again?

Am I at the top of the stairs?

No.

Climb up one step.

Am I at the top of the stairs?

No No.

Climb up one step.

Am I at the top of the stairs?

No.

Climb up one step.

Am I at the top of the stairs?

No.

Climb up one step Climb up one step.

Am I at the top of the stairs?

No.

Climb up one step.

...and so on...

(62)

How do I get up the stairs again?

How do I get up the stairs again?

while (I'm not at top of stairs) {

Climb up one step.

}

Going upstairs is a while loop!

(63)

Using the while statement

public class WhileDemo {

public static void main (String[] args)

p g g

{

int limit = 3;

int counter = 1;

while (counter >= limit) {

System.out.println("The square of " + counter +

" is " + (counter * counter));

counter = counter + 1;

}

System.out.println("End of demonstration");

} }

How will this change the program's behavior?

The body of the loop is never executed.

(64)

Using the while statement

public class WhileDemo {

public static void main (String[] args)

p g g

{

int limit = 3;

int counter = 1;

while (counter >= counter) {

System.out.println("The square of " + counter +

" is " + (counter * counter));

counter = counter + 1;

}

System.out.println("End of demonstration");

} }

What will this do now?

(65)

The infinite loop

public class WhileDemo {

public static void main (String[] args)

p g g

{

int limit = 3;

int counter = 1;

while (counter >= counter) {

System.out.println("The square of " + counter +

" is " + (counter * counter));

counter = counter + 1;

}

System.out.println("End of demonstration");

} }

If the boolean expression never evaluates to false, the loop will never end.

This is commonly referred to as an infinite loop -- it goes forever.

(66)

The infinite loop

public class WhileDemo {

public static void main (String[] args)

The infinite loop

p g g

{

int limit = 3;

int counter = 1;

while (counter <= limit) {

System.out.println("The square of " + counter +

" is " + (counter * counter));

counter = counter - 1;

}

System.out.println("End of demonstration");

} }

And now what happens?

(67)

The infinite loop

public class WhileDemo {

public static void main (String[] args)

The infinite loop

p g g

{

int limit = 3;

int counter = 1;

while (counter <= limit) {

System.out.println("The square of " + counter +

" is " + (counter * counter));

counter = counter - 1;

}

System.out.println("End of demonstration");

} }

Here the termination condition is good, but the process never gets closer to that termination condition. Another way to get the infinite loop.

(68)

The infinite loop

public class WhileDemo2 {

public static void main (String[] args)

The infinite loop

p g g

{

int limit = 0;

int counter = 9;

while (counter != limit) {

System.out.println("The square of " + counter +

" is " + (counter * counter));

counter = counter - 2;

}

System.out.println("End of demonstration");

} }

This one can be a little bit more tricky.

(69)

The infinite loop

public class WhileDemo2 {

public static void main (String[] args)

The infinite loop

p g g

{

int limit = 0;

int counter = 9;

while (counter != limit) {

System.out.println("The square of " + counter +

" is " + (counter * counter));

counter = counter - 2;

}

System.out.println("End of demonstration");

} }

Here the process gets closer to the termination condition, but never actually satisfies the termination condition and goes past it.

(70)

Another while statement example

public class PrintFactorials {

public static void main (String[] args)

Another while statement example

p g g

{

int limit = 10;

int counter = 1;

int product = 1;p

while (counter <= limit) {

System.out.println("The factorial of " + counter +

" is " + product);

counter = counter + 1;

product = product * counter;

}

System.out.println("End of demonstration");

} }

This statement accumulates an ever-growing product obtained by multiplying the integers from 1 through the current value of counter.

Figure

Updating...

References

Updating...

Related subjects :