Top Banner
This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons Attribution 2.5 License. All rights reserved. Based on slides created by Keith Schwarz, Mehran Sahami, Eric Roberts, Stuart Reges, and others. CS 106A, Lecture 6 Control Flow and Parameters suggested reading: Java Ch. 5.1-5.4
106

CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

May 13, 2018

Download

Documents

NguyễnThúy
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.

CS106A,Lecture6ControlFlowandParameters

suggestedreading:JavaCh.5.1-5.4

Page 2: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

2

Plan For Today•Announcements•Recap:IfandWhileinJava•ForLoopsinJava•MethodsinJava•Scope•Parameters

HW2 Cutoff

Page 3: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

3

Plan For Today•Announcements•Recap:IfandWhileinJava•ForLoopsinJava•MethodsinJava•Scope•Parameters

Page 4: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

4

Conditions in Java

while(condition) {body

}

if(condition) {body

}

Theconditionshouldbea“boolean”whichiseithertrue orfalse

Page 5: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

5

Booleans

1<2

true

Page 6: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

6

Relational Operators

Operator Meaning Example Value== equals 1 + 1 == 2 true!= doesnotequal 3.2 != 2.5 true< lessthan 10 < 5 false> greaterthan 10 > 5 true<= lessthanorequalto 126 <= 100 false>= greaterthanorequalto 5.0 >= 5.0 true

* All have equal precedence

Page 7: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

7

Relational Operatorsif (1 < 2) {

println("1 is less than 2!");}

int num = readInt("Enter a number: ");if (num == 0) {

println("That number is 0!");} else {

println("That number is not 0.");}

Page 8: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

8

Practice: Sentinel Loops• sentinel:Avaluethatsignalstheendofuserinput.

– sentinelloop:Repeatsuntilasentinelvalueisseen.

• Example:Writeaprogramthatpromptstheuserfornumbersuntiltheusertypes-1,thenoutputthesumofthenumbers.– Inthiscase,-1isthesentinelvalue.

Type a number: 10Type a number: 20Type a number: 30Type a number: -1Sum is 60

Page 9: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

9

Practice: Sentinel Loops// fencepost problem!// ask for number - post// add number to sum - fence

int sum = 0;int num = readInt("Enter a number: ");while (num != -1) {

sum += num;num = readInt("Enter a number: ");

}println("Sum is " + sum);

Page 10: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

10

Practice: Sentinel Loops// Solution #2 (ok, but #1 is better)

int sum = 0;while (true) {

int num = readInt("Enter a number: ");if (num == -1) {

break; // immediately exits loop}sum += num;

}println("Sum is " + sum);

Page 11: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

11

Compound Expressions

Operator Description Example Result! not !(2 == 3) true&& and (2 == 3) && (-1 < 5) false|| or (2 == 3) || (-1 < 5) true

Cannot "chain" tests as in algebra; use && or || instead

// assume x is 15 // correct version2 <= x <= 10 2 <= x && x <= 10true <= 10 true && falseError! false

In order of precedence:

Page 12: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

12

Boolean Variables// Store expressions that evaluate to true/falseboolean x = 1 < 2; // trueboolean y = 5.0 == 4.0; // false

// Directly set to true/falseboolean isFamilyVisiting = true;boolean isRaining = false;

// Ask the user a true/false (yes/no) questionboolean playAgain = readBoolean("Play again?”, "y", "n");if (playAgain) {...

Page 13: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

13

Practice: GuessMyNumber• WewroteaprogramcalledGuessMyNumber thatpromptstheuserforanumberuntiltheyguessoursecretnumber.

• Ifaguessisincorrect,theprogramprovidesahint;specifically,whethertheguessistoohighortoolow.

Page 14: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

14

If/Else If/Elseif (condition1) {

...} else if (condition2) { // NEW

...} else {

...}

Runsthefirstgroupofstatementsifcondition1 istrue;otherwise,runsthesecondgroupofstatementsifcondition2 istrue;otherwise,runsthethirdgroupofstatements.

Youcanhavemultipleelseifclausestogether.

Page 15: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

15

If/Else If/Elseint num = readInt("Enter a number: ");if (num > 0) {

println("Your number is positive");} else if (num < 0) {

println("Your number is negative");} else {

println("Your number is 0");}

Page 16: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

16

Plan For Today•Announcements•Recap:IfandWhileinJava•ForLoopsinJava•MethodsinJava•Scope•Parameters

Page 17: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

17

For Loops in Java

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

Repeats the loop if this condition

passes

Page 18: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

18

For Loops in Java

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loop Redux

Page 19: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

19

For Loops in Java

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loop Redux

i 0

Page 20: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

20

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loops in Java

For Loop Redux

i 0

Page 21: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

21

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loops in Java

For Loop Redux

i 0

I love CS 106A!

Page 22: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

22

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loops in Java

For Loop Redux

i 0

I love CS 106A!

Page 23: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

23

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loops in Java

For Loop Redux

i 1

I love CS 106A!

Page 24: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

24

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loops in Java

For Loop Redux

i 1

I love CS 106A!

Page 25: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

25

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loops in Java

For Loop Redux

i 1

I love CS 106A!

I love CS 106A!

Page 26: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

26

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loops in Java

For Loop Redux

i 2

I love CS 106A!

I love CS 106A!

Page 27: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

27

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loops in Java

For Loop Redux

i 2

I love CS 106A!

I love CS 106A!

Page 28: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

28

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loops in Java

For Loop Redux

i 2

I love CS 106A!

I love CS 106A!

I love CS 106A!

Page 29: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

29

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loops in Java

For Loop Redux

i 3

I love CS 106A!

I love CS 106A!

I love CS 106A!

Page 30: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

30

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loops in Java

For Loop Redux

i 3

I love CS 106A!

I love CS 106A!

I love CS 106A!

Page 31: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

31

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loops in Java

For Loop Redux

I love CS 106A!

I love CS 106A!

I love CS 106A!

Page 32: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

32

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loops in Java

For Loop Redux

I love CS 106A!

I love CS 106A!

I love CS 106A!

Page 33: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

33

Using the For Loop Variable

// prints the first 100 even numbersfor(int i = 1; i <= 100; i++) {

println(i * 2);}

Page 34: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

34

Using the For Loop Variable// Launch countdownfor(int i = 10; i >= 1; i--) {

println(i);}println("Blast off!");

1098…Blast off!

Output:

Page 35: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

35

Using the For Loop Variable

// Adds up 1 + 2 + ... + 99 + 100int sum = 0;for(int i = 1; i <= 100; i++) {

sum += i;}println("The sum is " + sum);

Page 36: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

36

Nested loops• nestedloop:Aloopplacedinsideanotherloop.

for (int i = 0; i < 5; i++) {for (int j = 0; j < 10; j++) {

print("*");}println(); // to end the line

}

• Output:**************************************************

• Theouterlooprepeats5times;theinnerone10times.

Page 37: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

37

Nested loop question• Q:Whatoutputisproducedbythefollowingcode?

for (int i = 0; i < 5; i++) {for (int j = 0; j < i + 1; j++) {

print("*");}println();

}

A. B. C. D. E.***** ***** * 1 12345***** **** ** 22***** *** *** 333***** ** **** 4444***** * ***** 55555

(Howwouldyoumodifythecodetoproduceeachoutputabove?)

Page 38: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

38

Nested loop question 2• Howwouldweproducethefollowingoutput?

....1

...22

..333

.444455555

Page 39: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

39

Nested loop question 2• Howwouldweproducethefollowingoutput?

....1

...22

..333

.444455555

• Answer:for (int i = 0; i < 5; i++) {

}

Page 40: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

40

Nested loop question 2• Howwouldweproducethefollowingoutput?

....1

...22

..333

.444455555

• Answer:for (int i = 0; i < 5; i++) {

for (int j = 0; j < 5 – i - 1; j++) {print(".");

}

}

Page 41: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

41

Nested loop question 2• Howwouldweproducethefollowingoutput?

....1

...22

..333

.444455555

• Answer:for (int i = 0; i < 5; i++) {

for (int j = 0; j < 5 – i - 1; j++) {print(".");

}for (int j = 0; j <= i; j++) {

print(i + 1);}

}

Page 42: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

42

Nested loop question 2• Howwouldweproducethefollowingoutput?

....1

...22

..333

.444455555

• Answer:for (int i = 0; i < 5; i++) {

for (int j = 0; j < 5 – i - 1; j++) {print(".");

}for (int j = 0; j <= i; j++) {

print(i + 1);}println();

}

Page 43: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

43

Plan For Today•Announcements•Recap:IfandWhileinJava•ForLoopsinJava•MethodsinJava•Scope•Parameters

Page 44: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

44

Defining New Commands in Karel

Wecanmakenewcommands(ormethods)forKarel.Thisletsusdecompose ourprogramintosmallerpiecesthatareeasiertounderstand.

private void turnRight() {turnLeft();turnLeft();turnLeft();

}

private void name() {statement;statement;...

}

Forexample:

Page 45: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

45

Methods in Java

Wecandefinenewmethods inJavajustlikeinKarel:

private void printGreeting() {println("Hello world!");println("I hope you have a great day.");

}

private void name() {statement;statement;...

}

Forexample:

Page 46: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

46

Methods in Javapublic void run() {

int x = 2;printX();

}

private void printX() {// ERROR! "Undefined variable x"println("X has the value " + x);

}

Page 47: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

47

Plan For Today•Announcements•Recap:IfandWhileinJava•ForLoopsinJava•MethodsinJava•Scope•Parameters

Page 48: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

48

By Chris Piech

Page 49: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.

Once upon a time…

Page 50: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

50

…x was looking for love!int x = 5;if(lookingForLove()) {int y = 5;

}println(x + y);

x5

Page 51: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

51

…x was looking for love!int x = 5;if(lookingForLove()) {int y = 5;

}println(x + y);

x5

x was definitelylooking for love

Page 52: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

52

And met y.int x = 5;if(lookingForLove()) {int y = 5;

}println(x + y);

x5

y5

Page 53: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

53

And met y.int x = 5;if(lookingForLove()) {int y = 5;

}println(x + y);

x5

y5 Hi, I’m y

Page 54: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.

“Wow!”

Page 55: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

55

And met y.int x = 5;if(lookingForLove()) {int y = 5;

}println(x + y);

x5

y5Wow

Page 56: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

56

And met y.int x = 5;if(lookingForLove()) {int y = 5;

}println(x + y);

x5

y5 We have so much

in common

Page 57: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

57

And met y.int x = 5;if(lookingForLove()) {int y = 5;

}println(x + y);

x5

y5 We both have

value 5!

Page 58: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

58

And met y.int x = 5;if(lookingForLove()) {int y = 5;

}println(x + y);

x5

y5 Maybe sometime

we can…

Page 59: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

59

And met y.int x = 5;if(lookingForLove()) {int y = 5;

}println(x + y);

x5

y5 println together?

Page 60: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

60

And met y.int x = 5;if(lookingForLove()) {int y = 5;

}println(x + y);

x5

y5

Page 61: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.

It was a beautiful match…

Page 62: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.

…but then tragedy struck.

Page 63: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

63

Tragedy Strikesint x = 5;if(lookingForLove()) {int y = 5;

}println(x + y);

x5

y5

Page 64: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

64

Tragedy Strikesint x = 5;if(lookingForLove()) {int y = 5;

}println(x + y);

x5

Page 65: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.

Noooooooooooooooo!

Page 66: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.

You see…when a program exits a code block,

all variables declared inside that block go away!

Page 67: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

67

Since y is inside the if-block…

int x = 5;if(lookingForLove()) {int y = 5;

}println(x + y);

x5

Page 68: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

68

…it goes away here…

int x = 5;if(lookingForLove()) {int y = 5;

}println(x + y);

x5

Page 69: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

69

…and doesn’t exist here.

int x = 5;if(lookingForLove()) {int y = 5;

}println(x + y);

x5

Error. Undefined variable y.

Page 70: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.

The End

Page 71: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.

Sad times L

Page 72: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

72

Variable ScopeVariables have a lifetime (called scope):

public void run(){double v = 8;if(condition){

v = 4;… some code

}… some other code

}

Page 73: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

73

Variable ScopeVariables have a lifetime (called scope):

public void run(){double v = 8;if(condition){

v = 4;… some code

}… some other code

}

Page 74: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

74

Variable ScopeVariables have a lifetime (called scope):

public void run(){double v = 8;if(condition){

v = 4;… some code

}… some other code

}v

Comes to life here

8

Page 75: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

75

Variable ScopeVariables have a lifetime (called scope):

public void run(){double v = 8;if(condition){

v = 4;… some code

}… some other code

}

This is the inner mostcode block in which it was

declared….

v4

Page 76: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

76

Variable ScopeVariables have a lifetime (called scope):

public void run(){double v = 8;if(condition){

v = 4;… some code

}… some other code

}v4

Still alive here…

Page 77: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

77

Variable ScopeVariables have a lifetime (called scope):

public void run(){double v = 8;if(condition){

v = 4;… some code

}… some other code

}v4

It goes away here (at the end of its code block)

Page 78: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

78

Variable ScopeVariables have a lifetime (called scope):

public void run(){double v = 8;if(condition){

v = 4;… some code

}… some other code

}It goes away here (at the end of its code block)

Page 79: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.

Page 80: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

80

Variable ScopeVariables have a lifetime (called scope):

public void run(){… some codeif(condition){

int w = 4;… some code

}… some other code

}

This is the scope of w

Page 81: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

81

Variable ScopeVariables have a lifetime (called scope):

public void run(){… some codeif(condition){

int w = 4;… some code

}… some other code

}

w goes away here (at the

end of its code block)

w is created here

Page 82: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

82

Variable Scopepublic void run() {

int x = 2;printX();

}

private void printX() {// ERROR! "Undefined variable x"println("X has the value " + x);

}

Page 83: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

83

By ChrisChapter 2

Page 84: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.

The programmer fixed the bug

Page 85: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

85

…x was looking for love!int x = 5;if(lookingForLove()) {int y = 5;println(x + y);

}

x5

Page 86: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

86

…x was looking for love!int x = 5;if(lookingForLove()) {int y = 5;println(x + y);

}

x5

x was definitelylooking for love

Page 87: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

87

And met y.int x = 5;if(lookingForLove()) {int y = 5;println(x + y);

}

x5

y5

Page 88: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

88

Since they were both “in scope”…

int x = 5;if(lookingForLove()) {int y = 5;println(x + y);

}

x5

y5

Page 89: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.

…they lived happily ever after.The end.

Page 90: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

90

Variable Scope• The scope of a variable refers to the section

of code where a variable can be accessed.• Scope starts where the variable is declared.• Scope ends at the termination of the code

block in which the variable was declared.

• A code block is a chunk of code between { } brackets

Page 91: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

91

Variable ScopeYou cannot have two variables with the same name in the same scope.

for (int i = 1; i <= 100 * line; i++) {int i = 2; // ERRORprint("/");

}

Page 92: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

92

Variable ScopeYou can have two variables with the same name in different scopes.

private void run() {int num = 5;cow();println(num);

}

private void cow() {int num = 10;println(num);

}

Page 93: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

93

Variable ScopeYou can have two variables with the same name in different scopes.

private void run() {int num = 5;cow();println(num); // prints 5

}

private void cow() {int num = 10;println(num); // prints 10

}

Page 94: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

94

Variable ScopeYou can have two variables with the same name in different scopes.

private void run() {int num = 5;cow();println(num); // prints 5

}

private void cow() {int num = 10;println(num); // prints 10

}

Page 95: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

95

Revisiting Sentinel Loops// sum must be outside the while loop!// Otherwise it will be redeclared many times.int sum = 0;int num = readInt("Enter a number: ");while (num != -1) {

sum += num;num = readInt("Enter a number: ");

}println("Sum is " + sum);

Page 96: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

96

Plan For Today•Announcements•Recap:IfandWhileinJava•ForLoopsinJava•MethodsinJava•Scope•Parameters

Page 97: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

97

Parameters

Parametersletyouprovideamethodsomeinformationwhenyouarecallingit.

Page 98: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

98

Methods = Toasters

Page 99: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

99

Methods = Toasters

parameter

Page 100: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

100

Methods = Toasters

parameter

Page 101: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

101

Methods = Toasters

parameter

Page 102: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

102

Methods = Toasters

parameter

Page 103: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

103

Methods = Toasters

Invalid parameter

Page 104: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

104

Methods = Toasters

Page 105: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

105

Drawing boxes• Considerthetaskofprintingthefollowingboxes:

*********** ** ***********

******** ** ** ** ********

– Thecodetodraweachboxwillbeverysimilar.•Wouldvariableshelp?Wouldconstantshelp?

Page 106: CS 106A, Lecture 6 - Stanford Universityweb.stanford.edu/.../lectures/Lecture6/Lecture6.pdf8 Practice: Sentinel Loops •sentinel: A value that signals the end of user input. –sentinel

106

Wouldn’t it be nice if…

drawBox(10, 4);

Continued next time…