69
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 5 Booleans, Control Flow and Scope suggested reading: Java Ch. 3.4-4.6

CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

Embed Size (px)

Citation preview

Page 1: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

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

CS106A,Lecture5Booleans,ControlFlowandScope

suggestedreading:JavaCh.3.4-4.6

Page 2: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

2

Plan For Today•Announcements•Recap:Java,VariablesandExpressions•Aside:ShorthandOperators+Constants•RevisitingControlFlow–IfandWhile–For

Page 3: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

3

Plan For Today•Announcements•Recap:Java,VariablesandExpressions•Aside:ShorthandOperators+Constants•RevisitingControlFlow–IfandWhile–For

Page 4: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

4

Plan For Today•Announcements•Recap:Java,VariablesandExpressions•Aside:ShorthandOperators+Constants•RevisitingControlFlow–IfandWhile–For

Page 5: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

5

Java

Karel Program Graphics ProgramConsole Program

SuperKarel Program

Program

Page 6: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

6

Console Programsimport acm.program.*;

public class Name extends ConsoleProgram {public void run() {

statements;}

}

• UnlikeKarel,manyprogramsproducetheirbehavior astext.• console:Textboxintowhichthebehavior isdisplayed.

– output: Messagesdisplayedbytheprogram.– input: Datareadbytheprogramthattheusertypes.

Page 7: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

7

println• Astatementthatprintsalineofoutputontheconsole,andgoestothenextline.– pronounced"print-linn"

• Twowaystouseprintln :

• println("text");• Printsthegivenmessageasoutput,andgoestothenextline.• Amessageiscalledastring;itstarts/endswitha" quotecharacter.• Thequotesdonotappearintheoutput.• Astringmaynotcontaina" character.

• println();Printsablanklineofoutput.

Page 8: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

8

printpublic class HelloWorld extends ConsoleProgram {

public void run() {print("Hello, ");print("world!");

}}

Same as println, but does not go to the next line.

Page 9: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

9

Expressions• Youcancombineliteralsorvariablestogetherintoexpressionsusingbinaryoperators:

AdditionSubtraction

*/ Division% Remainder

+–

Multiplication

Page 10: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

10

Precedence• precedence:Orderinwhichoperatorsareevaluated.

– Generallyoperatorsevaluateleft-to-right.1 - 2 - 3 is(1 - 2) - 3 whichis-4

– But* / % haveahigherlevelofprecedencethan+ -1 + 3 * 4 is13

6 + 8 / 2 * 36 + 4 * 36 + 12 is18

– Parenthesescanalterorderofevaluation,butspacingdoesnot:(1 + 3) * 4 is161+3 * 4-2 is11

Page 11: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

11

Type Interactions

int and int results in an intdouble and double results in a double

int and double results in a double

* The general rule is: operations always return the most expressive type

String and int results in a String

etc.

Page 12: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

12

Integer division• Whenwedivideintegers,thequotientisalsoaninteger.

14 / 4 is3,not3.5 .(JavaALWAYSroundsdown.)

3 4 524 ) 14 10 ) 45 27 ) 1425

12 40 1352 5 75

5421

• Moreexamples:– 32 / 5 is6– 84 / 10 is8– 156 / 100 is1

– Dividingby0 causesanerrorwhenyourprogramruns.

Page 13: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

13

Practice

•1/2 0 •1.0/2 0.5•1+2/3 1•"abc"+(4+2) "abc6"•"abc"+4 +2"abc42"

Page 14: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

14

Making a new Variable

int myVariable;

type name

Page 15: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

15

Variable Types

int – an integer number

double – a decimal number

Page 16: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

16

Assignment

myVariable = 2;

Existing variable name value

Page 17: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

17

Assignment• assignment:Storesavalueintoavariable.

– Thevaluecanbeanexpression;thevariablestoresitsresult.

• Syntax:

name = expression;

int zipcode;zipcode = 90210;

double myGPA;myGPA = 1.0 + 2.25;

zipcode 90210

myGPA 3.25

Page 18: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

18

Declare / initialize• Avariablecanbedeclared/initializedinonestatement.

– Thisisprobablythemostcommonlyuseddeclarationsyntax.

• Syntax:

type name = expression;

double tempF = 98.6;

int x = (12 / 2) + 3;x 9

tempF 98.6

Page 19: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

19

Using Variables

// Asks the user for an integer by// displaying the given message// and stores it in the variable ’a’int a = readInt(message);

// Asks the user for a double by// displaying the given message and// stores it in the variable ’b’double b = readDouble(message);

Page 20: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

20

Practice: Receipt Program• WewroteaConsoleProgram calledReceipt thatcalculatesthetax,tipandtotalbillforusatarestaurant.

• Theprogramaskstheuserforthesubtotal,andthencalculateandprintoutthetax,tipandtotal.

Page 21: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

21

Plan For Today•Announcements•Recap:VariablesandExpressions•Aside:ShorthandOperators+Constants•RevisitingControlFlow–IfandWhile–For

Page 22: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

22

Shorthand OperatorsShorthand Equivalentlongerversionvariable += value; variable = variable + value;variable -= value; variable = variable - value;variable *= value; variable = variable * value;variable /= value; variable = variable / value;variable %= value; variable = variable % value;

variable++; variable = variable + 1;variable--; variable = variable – 1;

x += 3; // x = x + 3;number *= 2; // number = number * 2;x++; // x = x + 1;

Page 23: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

23

Constants• constant:Avariablethatcannotbechangedafteritisinitialized.Declaredatthetopofyourclass,outsideoftherun()method.Canbeusedanywhereinthatclass.

• Betterstyle– caneasilychangetheirvaluesinyourcode,andtheyareeasiertoreadinyourcode.

• Syntax:private static final type name = value;

– nameisusuallyinALL_UPPER_CASE

– Examples:private static final int DAYS_IN_WEEK = 7;private static final double INTEREST_RATE = 3.5;private static final int SSN = 658234569;

Page 24: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

24

Receipt Program - Beforepublic class Receipt extends ConsoleProgram {public void run() {double subtotal = readDouble(”Meal cost? $”);double tax = subtotal * 0.08;double tip = subtotal * 0.20;double total = subtotal + tax + tip;

println("Tax : $” + tax);println("Tip: $” + tip);println(”Total: $" + total);

}}

Page 25: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

25

Receipt Program – Afterpublic class Receipt extends ConsoleProgram {private static final double TAX_RATE = 0.08;private static final double TIP_RATE = 0.2;

public void run() {double subtotal = readDouble(”Meal cost? $”);double tax = subtotal * TAX_RATE;double tip = subtotal * TIP_RATE;double total = subtotal + tax + tip;

println("Tax : $” + tax);println("Tip: $” + tip);println(”Total: $" + total);

}}

Page 26: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

26

Plan For Today•Announcements•Recap:VariablesandExpressions•Aside:ShorthandOperators+Constants•RevisitingControlFlow–IfandWhile–For

Page 27: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

27

If/Else in Karelif (condition) {

statement;statement;...

} else {statement;statement;...

}

Runsthefirstgroupofstatementsifcondition istrue;otherwise,runsthesecondgroupofstatements.

Page 28: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

28

While Loops in Karelwhile (condition) {

statement;statement;...

}

Repeatsthestatementsinthebodyuntilcondition isnolongertrue.Eachtime,Karelexecutesallstatements,andthen checksthecondition.

Page 29: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

29

Conditions in Karel

while(frontIsClear()) {body

}

if(beepersPresent()) {body

}

Page 30: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

30

Conditions in Java

while(condition) {body

}

if(condition) {body

}

Theconditionshouldbea“boolean”whichiseithertrue orfalse

Page 31: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

31

Booleans

1<2

Page 32: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

32

Booleans

1<2

true

Page 33: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

33

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 34: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

34

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 35: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

35

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 36: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

36

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 37: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

37

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 38: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

38

Practice: Sentinel Loops// Solution #2 (ok, but #1 is better)// harder to see loop end condition here

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 39: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

39

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 40: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

40

Precedence MadnessPrecedence:arithmetic>relational>logical

5 * 7 >= 3 + 5 * (7 – 1) && 7 <= 115 * 7 >= 3 + 5 * 6 && 7 <= 1135 >= 3 + 30 && 7 <= 1135 >= 33 && 7 <= 11true && truetrue

Page 41: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

41

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

Page 42: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

42

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;

Page 43: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

43

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 44: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

44

Practice: GuessMyNumber• Let’swriteaprogramcalledGuessMyNumber thatpromptstheuserforanumberuntiltheyguessoursecretnumber.

• Ifaguessisincorrect,theprogramshouldprovideahint;specifically,whethertheguessistoohighortoolow.

Page 45: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

45

Summary: Conditions

while(condition) {body

}

if(condition) {body

}

Theconditionshouldbeaboolean whichiseithertrue orfalse

Page 46: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

46

If/Else If/Elseif (condition1) {

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

...} else {

...}

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

Youcanhavemultipleelseifclausestogether.

Page 47: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

47

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 48: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

48

Plan For Today•Announcements•Recap:VariablesandExpressions•Aside:ShorthandOperators+Constants•RevisitingControlFlow–IfandWhile–For

Page 49: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

49

For Loops in Karelfor (int i = 0; i < max; i++) {

statement;statement;...

}

Repeatsthestatementsinthebodymax times.

Page 50: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

50

For Loops in Java

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

}

Repeats the loop if this condition

passes

Page 51: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

51

For Loops in Java

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

}

For Loop Redux

Page 52: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

52

For Loops in Java

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

}

For Loop Redux

i 0

Page 53: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

53

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

}

For Loops in Java

For Loop Redux

i 0

Page 54: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

54

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 55: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

55

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 56: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

56

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 57: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

57

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 58: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

58

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 59: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

59

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 60: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

60

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 61: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

61

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 62: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

62

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 63: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

63

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 64: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

64

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 65: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

65

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 66: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

66

Using the For Loop Variable

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

println(i * 2);}

Page 67: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

67

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

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

1098…Blast off!

Output:

Page 68: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

68

Using the For Loop Variable

// Adds up the first 100 numbersint sum = 0;for(int i = 0; i < 100; i++) {

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

Page 69: CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true

69

Recap•Announcements•Recap:VariablesandExpressions•Aside:ShorthandOperators+Constants•RevisitingControlFlow–IfandWhile–For

Nexttime:Morecontrolflow,methodsinJava