49
Repeating Actions Repeating Actions The “while” and “for” The “while” and “for” Controls Controls Sections 4.1 & 4.2 Sections 4.1 & 4.2 (Also: Special Assignment (Also: Special Assignment Operators Operators

Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Embed Size (px)

Citation preview

Page 1: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Repeating ActionsRepeating Actions

The “while” and “for” ControlsThe “while” and “for” ControlsSections 4.1 & 4.2Sections 4.1 & 4.2

(Also: Special Assignment Operators (Also: Special Assignment Operators and Constants)and Constants)

Page 2: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Program FlowProgram Flow

Sequence: do commands in orderSequence: do commands in order the “normal” orderthe “normal” order

Selection: skip over some commandsSelection: skip over some commands ““if”, “if-else”, and “switch” controlsif”, “if-else”, and “switch” controls

Repetition: do some commands over againRepetition: do some commands over again ““while”, “for” and “do-while” controlswhile”, “for” and “do-while” controls

Page 3: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Yes or Whatever!Yes or Whatever!

Recall “Do you want fries with that?”Recall “Do you want fries with that?” accepts “yes” in any case accepts “yes” in any case

» ““yes”, “YES”, “Yes”, …yes”, “YES”, “Yes”, … if (resp.equalsIgnoreCase("Yes"))if (resp.equalsIgnoreCase("Yes"))

{{ order.add("fries"); order.add("fries");}}

……treated anything else as notreated anything else as no» ““sure”, “yeah”, “yup”, “yes, please”, …sure”, “yeah”, “yup”, “yes, please”, …

Page 4: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

What Do We Want?What Do We Want?

Ideally?Ideally? Anything that means yes Anything that means yes yes yes Anything that means no Anything that means no no no Anything else Anything else try again try again

That’s too hard! How aboutThat’s too hard! How about Yes Yes yes yes No No no no Anything else Anything else try again try again

Page 5: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Getting a Yes/No AnswerGetting a Yes/No Answer

System.out.print(“Do you want fries with that? ”);System.out.print(“Do you want fries with that? ”);String resp = kbd.next(); kbd.nextLine();String resp = kbd.next(); kbd.nextLine();if (resp.equalsIgnoreCase(“yes”))if (resp.equalsIgnoreCase(“yes”)){{ order.add(“fries”);order.add(“fries”);}}

Want them to answer “yes” or “no”Want them to answer “yes” or “no” So if they give a different answer?So if they give a different answer?

Ask them againAsk them again

Page 6: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Asking AgainAsking Again

First answer is wrong First answer is wrong ask them again ask them again

Right first time Right first time doesn’t ask again doesn’t ask again

Do you want fries with that? Do you want fries with that? yup

Please say yes or no: Please say yes or no: yes

Do you want fries with that? Do you want fries with that? sure

Please say yes or no: Please say yes or no: yes

Do you want fries with that? Do you want fries with that? nope

Please say yes or no: Please say yes or no: no

Do you want fries with that? Do you want fries with that? yes

AB

AB

AB

A

do the A step; possibly do the B step

Page 7: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Asking AgainAsking Again

// A – done first// A – done firstSystem.out.print(“Do you want fries with that? ”);System.out.print(“Do you want fries with that? ”);resp = kbd.next(); kbd.nextLine();resp = kbd.next(); kbd.nextLine();if (!resp.equalsIgnoreCase(“yes”) if (!resp.equalsIgnoreCase(“yes”) // not yes// not yes

&& !resp.equalsIgnoreCase(“no”)) && !resp.equalsIgnoreCase(“no”)) // and not no// and not no{{ // B – possibly done// B – possibly done System.out.print(“Please say yes or no: ”);System.out.print(“Please say yes or no: ”); resp = kbd.next(); kbd.nextLine();resp = kbd.next(); kbd.nextLine();}}if (resp.equalsIgnoreCase(“yes”))if (resp.equalsIgnoreCase(“yes”)){{ order.add(“fries”);order.add(“fries”);}}

Page 8: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Asking Again AgainAsking Again Again

Second answer is wrong Second answer is wrong ??? ???

uses that wrong answeruses that wrong answer» which is which is notnot equalsIgnoreCase(“yes”), so equalsIgnoreCase(“yes”), so no! no!

Maybe it should ask again againMaybe it should ask again again

Do you want fries with that? Do you want fries with that? yup.

Please say yes or no: Please say yes or no: yes, please.

Do you want fries with that? Do you want fries with that? yup.

Please say yes or no: Please say yes or no: yes, please.

Please say yes or no: Please say yes or no: I did!

Please say yes or no: Please say yes or no: yes

AB

ABBB

do the A step; as necessary do the B step

Page 9: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Getting a Yes/No AnswerGetting a Yes/No Answer

// A – done first// A – done firstSystem.out.print(“Do you want fries with that? ”);System.out.print(“Do you want fries with that? ”);resp = kbd.next(); kbd.nextLine();resp = kbd.next(); kbd.nextLine();while while (!resp.equalsIgnoreCase(“yes”) (!resp.equalsIgnoreCase(“yes”) // not yes// not yes

&& !resp.equalsIgnoreCase(“no”)) && !resp.equalsIgnoreCase(“no”)) // and not no// and not no{{ // B – possibly // B – possibly repeatedrepeated System.out.print(“Please say yes or no: ”);System.out.print(“Please say yes or no: ”); resp = kbd.next(); kbd.nextLine();resp = kbd.next(); kbd.nextLine();}}if (resp.equalsIgnoreCase(“yes”))if (resp.equalsIgnoreCase(“yes”)){{ order.add(“fries”);order.add(“fries”);}}

Just change the “if” to “while”

Page 10: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

The “while” ControlThe “while” Control

Java SyntaxJava Syntax while (while (conditioncondition) )

{{ repeatedAction(s)repeatedAction(s);;

}} if the condition is true, do the repeated action, if the condition is true, do the repeated action,

and keep doing the repeated action until the and keep doing the repeated action until the condition becomes falsecondition becomes false

» if condition if condition starts out starts out false, body gets skippedfalse, body gets skipped

Page 11: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Note: No “else” for “while”Note: No “else” for “while”

You can change an if to a whileYou can change an if to a while if the data is bad, ask againif the data is bad, ask again if the data is if the data is stillstill bad, ask bad, ask againagain ……

You can’t change an if-else to a whileYou can’t change an if-else to a while if the data is bad, ask again, otherwise use itif the data is bad, ask again, otherwise use it if the data’s still bad, ask again, otherwise use itif the data’s still bad, ask again, otherwise use it just do the “use it” part just do the “use it” part after the loopafter the loop

Page 12: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Exercise: Getting a Valid GradeExercise: Getting a Valid Grade

What did you get on the test? What did you get on the test? 1000

Grade must be 0 to 100: Grade must be 0 to 100: 999

Grade must be 0 to 100: Grade must be 0 to 100: 9998

Grade must be 0 to 100: Grade must be 0 to 100: 98

What did you get on the test? What did you get on the test? 100

What did you get on the test? What did you get on the test? 0

What did you get on the test? What did you get on the test? -10

Grade must be 0 to 100: Grade must be 0 to 100: 100

do the A step; as necessary do the B step

ABBB

AB

A

A

Page 13: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Things to NoticeThings to Notice

In both examples:In both examples: needed to get first answer needed to get first answer beforebefore the loop the loop

(I call this the (I call this the loop initializationloop initialization)) test was that the input is test was that the input is notnot what we’re looking what we’re looking

for (“bad” input)for (“bad” input) last command in loop is to last command in loop is to get new inputget new input

(I call this (I call this loop updateloop update)) it’s the it’s the same variablesame variable in initialization, test and in initialization, test and

update (I call it the update (I call it the loop control variableloop control variable))

Page 14: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Parts of a (while) LoopParts of a (while) Loop

System.out.print(“You have a disability? ”);System.out.print(“You have a disability? ”);

resp = kbd.next(); kbd.nextLine();resp = kbd.next(); kbd.nextLine();

InitializationHappens before the “while” command

Gets the first data value(Example: the user’s first answer to the question)

loop control variable: resp

Page 15: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Parts of a (while) LoopParts of a (while) Loop

while (!resp.equalsIgnoreCase(“YES”)while (!resp.equalsIgnoreCase(“YES”)

&& !resp.equalsIgnoreCase(“NO”)) {&& !resp.equalsIgnoreCase(“NO”)) {

TestIn parentheses after the “while”

Is the test to keep goingIs opposite of when to stop

(Example: Stop when is resp is YES or NO;i.e. Keep going if resp is not YES and it’s not NO)

loop control variable: resp

Page 16: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Parts of a (while) LoopParts of a (while) Loop

System.out.print(“Yes or no? ”);System.out.print(“Yes or no? ”);

ProcessThis is the thing we want to do to each data value

(Example: Tell user what we’re looking for.)

Page 17: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Parts of a (while) LoopParts of a (while) Loop

resp = kbd.next(); kbd.nextLine();resp = kbd.next(); kbd.nextLine();

UpdateLast thing to do in the loop!!!

Get the next data value(Example: the user’s next response)

loop control variable: resp

Page 18: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Initialization & UpdateInitialization & Update

System.out.print(“You have a disability? ”);System.out.print(“You have a disability? ”);

resp = kbd.next(); kbd.nextLine();resp = kbd.next(); kbd.nextLine();

resp = kbd.next(); kbd.nextLine();resp = kbd.next(); kbd.nextLine();

Usually the SameEspecially if it’s an input command.(There are often slight variations.)

loop control variable: resp

Page 19: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Loop ExecutionLoop Execution

Initialization is carried outInitialization is carried out Loop condition is testedLoop condition is tested

if test passedif test passed» Body is executedBody is executed» Update command is executedUpdate command is executed» Goes back to loop conditionGoes back to loop condition

Continues until test failsContinues until test fails ““termination condition”termination condition”

Page 20: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

On the Importance of UpdatesOn the Importance of Updates

It’s important that you do it!It’s important that you do it!

Sop(“…isability?”);Sop(“…isability?”);

r = kbd.next();r = kbd.next();

while (!r.equals(“yes”)while (!r.equals(“yes”)&& !r.equals(“no”))&& !r.equals(“no”))

{{Sop(“Yes or no? ”);Sop(“Yes or no? ”);

}}

You have a disability? yupYes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no?

Page 21: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

On the Importance of UpdatesOn the Importance of Updates

It’s important that you do it It’s important that you do it lastlast!!

Sop(“…isability?”);Sop(“…isability?”);

r = kbd.next();r = kbd.next();

while (!r.equals(“yes”)while (!r.equals(“yes”)&& !r.equals(“no”))&& !r.equals(“no”))

{{r = kbd.next();r = kbd.next();Sop(“Yes or no? ”);Sop(“Yes or no? ”);

}}

You have a disability? yuphello?Yes or no? what?Yes or no? yesYes or no? People with disabilities should contact the department of social services at the address below.

Page 22: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Not Just for Bad InputNot Just for Bad Input

Can use while loops for good data, tooCan use while loops for good data, too recall JavaAveragerecall JavaAverage

bad input bad input loop ends loop ends

Enter a number: 10Enter another number or -1 to quit: 20Enter another number or -1 to quit: 30Enter another number or -1 to quit: 40Enter another number or -1 to quit: -1

The average of the positive numbers you entered is 25.0.

ABBBBCD

Page 23: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Exercise: Loop ControlExercise: Loop Control

Write the loop control for that loopWrite the loop control for that loop don’t worry about finding the average!don’t worry about finding the average!

Enter a number: 10Enter another number or -1 to quit: 20Enter another number or -1 to quit: 30Enter another number or -1 to quit: 40Enter another number or -1 to quit: -1

Oops! I forgot to find the average!

ABBBBCD

Page 24: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Loop ProcessingLoop Processing

Extra stuff that needs doing inside loopExtra stuff that needs doing inside loop For For eacheach of the numbers, we must... of the numbers, we must... ...add it to a running sum, and......add it to a running sum, and... ...count it...count it

Remember: inside the loop, you only have Remember: inside the loop, you only have one one piece of datapiece of data add add itit to the running sum (not to the running sum (not themthem)) count count itit (not (not themthem))

Page 25: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Adding and AssigningAdding and Assigning

Recall that we use + to add, = to assignRecall that we use + to add, = to assigntotalTax = provTax + fedTax;totalTax = provTax + fedTax; provTax + fedtax provTax + fedtax just adds the numbersjust adds the numbers totalTax = totalTax = saves the answersaves the answer

We can put the two steps togetherWe can put the two steps togethersum += num;sum += num; +=+= add and assign add and assign add these numbers together and save the answeradd these numbers together and save the answer

» saved in the variable on the leftsaved in the variable on the left» so same as so same as sum = sum + (num);sum = sum + (num);

Page 26: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Special Assignment OperatorsSpecial Assignment Operators

Works for all the math operatorsWorks for all the math operators var var += += exprexpr add expr to varadd expr to var var var --= = exprexpr subtract expr from varsubtract expr from var var var **= = exprexpr multiply var by exprmultiply var by expr var var //= = exprexpr divide var by exprdivide var by expr var var %%= = exprexpr (exercise)(exercise)

» var must be a variablevar must be a variable» expr can be an expressionexpr can be an expressioncourseGrade += LAB_WEIGHT * labPercent;courseGrade += LAB_WEIGHT * labPercent;

Page 27: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

CountingCounting

Adding one to a variable is Adding one to a variable is very commonvery common that’s what counting is!that’s what counting is!

Could use += to add one...Could use += to add one...count += 1;count += 1;

...but that’s five keystrokes...but that’s five keystrokes We can do it in twoWe can do it in two

count++;count++; ++++ add one to this variable add one to this variable called “increment”called “increment”

Page 28: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Increment & DecrementIncrement & Decrement

These operations that are common in loopsThese operations that are common in loops varvar++++ add one to varadd one to var ++++varvar add one to varadd one to var varvar---- subtract one from varsubtract one from var ----varvar subtract one from varsubtract one from var

You will see both You will see both prefixprefix & & suffixsuffix versions versions they are they are slightly slightly differentdifferent the difference doesn’t matter to usthe difference doesn’t matter to us

Page 29: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

JavaAverage ReviewJavaAverage Review

int sum, count, num;int sum, count, num;double ave;double ave;

sum = 0;sum = 0;count = 0;count = 0;num = kbd.nextInt(); kbd.nextLine(); num = kbd.nextInt(); kbd.nextLine(); // LCV init. // LCV init. while (num >= 0) while (num >= 0) // LCV test.// LCV test.{{ sum += num; sum += num; // add num to sum// add num to sum count++; count++; // count num// count num num = kbd.nextInt(); kbd.nextLine(); num = kbd.nextInt(); kbd.nextLine(); // LCV upd.// LCV upd.}}ave = (double)sum / (double)count;ave = (double)sum / (double)count;

Needs S.o.p commands!

Page 30: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

ExerciseExercise

Track the variables’ valuesTrack the variables’ valuesaa bb cc

a = 1;a = 1; 11 ?? ??a++;a++;b = a + 6;b = a + 6;b--;b--;c = b * 5;c = b * 5;c += a;c += a;a *= 10;a *= 10;b /= 2;b /= 2;c %= 4;c %= 4;a *= b + c;a *= b + c;

note: sums b and c note: sums b and c beforebefore it multiplies it multiplies

Page 31: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Definite or IndefiniteDefinite or Indefinite

Repeat unknown number of timesRepeat unknown number of times ABBBBBBCD, ABBBBCD, ACD, ABCD, ...ABBBBBBCD, ABBBBCD, ACD, ABCD, ... ““indefinite iteration” or “data controlled loop”indefinite iteration” or “data controlled loop” usually a while loopusually a while loop

Repeat known number of timesRepeat known number of times ABBBC, ABBBC, ABBBC, ABBBC, ...ABBBC, ABBBC, ABBBC, ABBBC, ... ““definite iteration” or “count controlled loop”definite iteration” or “count controlled loop” not usually a while loopnot usually a while loop

Page 32: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Count-ControlledCount-Controlled

It’s not the data that tells us to stopIt’s not the data that tells us to stop just count how many times it’s donejust count how many times it’s done

Enter your A1 grade: 100Enter your A2 grade: 98Enter your A3 grade: 87Enter your A4 grade: 99Enter your A5 grade: 100Enter your A6 grade: 80

Your average is 94.0.

AAAAAABC

loop control variable: the assignment number!

Page 33: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Count-Controlled while LoopCount-Controlled while Loop

int sum, asgn, grade;int sum, asgn, grade;double ave;double ave;

sum = 0;sum = 0;asgn = 1asgn = 1;; // LCV initialized // LCV initializedwhile (asgn <= 6)while (asgn <= 6) // LCV tested// LCV tested{{ grade = kbd.nextInt(); kbd.nextLine();grade = kbd.nextInt(); kbd.nextLine(); sum += grade;sum += grade; asgn++;asgn++; // LCV updated// LCV updated}}ave = (double)sum / 6;ave = (double)sum / 6;

Needs S.o.p commands!Question: why not divide by asgn instead of 6?

Page 34: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

The for ControlThe for Control

Count-controlled loops very commonCount-controlled loops very common Want a shorter/easier way to make themWant a shorter/easier way to make them All loop control actions in one placeAll loop control actions in one place

initialization (usually initialization (usually = 1= 1)) test (usually test (usually <= something<= something)) update (usually update (usually ++++))

The “for” loop controlThe “for” loop control

Page 35: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Count-Controlled for LoopCount-Controlled for Loop

int sum, asgn, grade;int sum, asgn, grade;double ave;double ave;

sum = 0;sum = 0;for (asgn = 1; asgn <= 6; asgn++)for (asgn = 1; asgn <= 6; asgn++) // LCV i/t/u// LCV i/t/u{{ grade = kbd.nextInt(); kbd.nextLine();grade = kbd.nextInt(); kbd.nextLine(); sum += grade;sum += grade;}}ave = (double)sum / 6;ave = (double)sum / 6;

Needs S.o.p commands!

Page 36: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Easy Mistake to MakeEasy Mistake to Make

Change number of assignments to 10Change number of assignments to 10int sum, asgn, grade;int sum, asgn, grade;double ave;double ave;

sum = 0;sum = 0;for (asgn = 1; asgn <= 10; asgn++)for (asgn = 1; asgn <= 10; asgn++){{ grade = kbd.nextInt(); kbd.nextLine();grade = kbd.nextInt(); kbd.nextLine(); sum += grade;sum += grade;}}ave = (double)sum / 6;ave = (double)sum / 6;

What went wrong?How can we prevent that kind of mistake?

Page 37: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

ConstantsConstants

LiteralsLiterals numbers: 3, 22, 3.14159numbers: 3, 22, 3.14159 characters: ‘a’, ‘A’, ‘&’characters: ‘a’, ‘A’, ‘&’ strings: “Hello, world!”strings: “Hello, world!”

Named / Symbolic constantNamed / Symbolic constant identifieridentifier must be declaredmust be declaredpublic static final public static final int NUM_ASGN = 6;int NUM_ASGN = 6;

Page 38: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

ConstantsConstants

Constant declarations go before the methodsConstant declarations go before the methodspublic class CircleCalculation public class CircleCalculation {{

public static final int NUM_ASGN = 6;public static final int NUM_ASGN = 6;

public static void main(String[] args) public static void main(String[] args) {{

……}}

}}

Page 39: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Why Named ConstantsWhy Named Constants

Easier to read and understandEasier to read and understand Changing value easierChanging value easier

one change instead of manyone change instead of many coincidental equality is not a problemcoincidental equality is not a problem

» is is thisthis 100 the max grade or the max enrolment? 100 the max grade or the max enrolment?

Compiler can catch the mistakeCompiler can catch the mistake Typo: Typo: 3.145193.14519 for for 3.141593.14159 computer: “OK.”computer: “OK.” Typo: Typo: NUM_AGSNNUM_AGSN for for NUM_ASGNNUM_ASGN

computer: computer: “Huh?”“Huh?”

Page 40: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Naming StylesNaming Styles

Use meaningful namesUse meaningful names Use multiple words as appropriateUse multiple words as appropriate Naming conventionsNaming conventions

variableNamevariableName CONSTANT_NAMECONSTANT_NAME

Page 41: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

ExerciseExercise

Declare Java constants forDeclare Java constants for the maximum allowable enrolment for a course the maximum allowable enrolment for a course

(which is 100)(which is 100) the number of feet in a mile (5280)the number of feet in a mile (5280) the number of cm in an inch (2.54)the number of cm in an inch (2.54) the name of a data file (numbers.txt)the name of a data file (numbers.txt)

Page 42: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Loop using ConstantLoop using Constant

public static final int NUM_ASGN = 6;public static final int NUM_ASGN = 6;

public static void main(String[] args) {public static void main(String[] args) { int sum, asgn, grade;int sum, asgn, grade; double ave;double ave;

sum = 0;sum = 0; for (asgn = 1; asgn <= NUM_ASGN; asgn++)for (asgn = 1; asgn <= NUM_ASGN; asgn++) {{ grade = kbd.nextInt(); kbd.nextLine();grade = kbd.nextInt(); kbd.nextLine(); sum += grade;sum += grade; }} ave = (double)sum / NUM_ASGN;ave = (double)sum / NUM_ASGN;}}

Still needs S.o.plns!Exercise: change the number of assignments to 10.

Page 43: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

while while vs.vs. for for

Same four parts of loopSame four parts of loop Initialization, test, processing, updateInitialization, test, processing, update while loops & for loops do while loops & for loops do exactly the sameexactly the same

for (initialize; test; update){

process;}

initialize;while (test) {

process;update;

}

Page 44: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Count Controlled LoopsCount Controlled Loops

The “for” control is used when you know The “for” control is used when you know ahead of time how many iterations you wantahead of time how many iterations you want we wanted six assignment grades: six iterationswe wanted six assignment grades: six iterations count the iterations: count controlled loopcount the iterations: count controlled loop

In general, NUM_ITERATIONS iterationsIn general, NUM_ITERATIONS iterationsfor (for (iteriter = 1; = 1; iteriter <= <= NUM_ITERATIONSNUM_ITERATIONS; ; iteriter++) ++) {{

(loop body = actions to be repeated)(loop body = actions to be repeated)}}

iter is the loop control variable;NUM_ITERATIONS is how many iterations we want.

Page 45: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

ExercisesExercises

Write a loop to print out “Hello” 10 times Write a loop to print out “Hello” 10 times (each “Hello” on its own line)(each “Hello” on its own line)

Write a loop to print out the numbers from Write a loop to print out the numbers from 1 to 20 on a single line1 to 20 on a single line separate the numbers by spacesseparate the numbers by spaces end the line end the line when you’re donewhen you’re done

Page 46: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

Find Maximum of N NumbersFind Maximum of N Numbers

InitializationInitialization initialize maximuminitialize maximum

to something smallto something small

Count the numbersCount the numbers ProcessingProcessing

get the next itemget the next item update the maxupdate the max

» Math.max returns the bigger of the two numbers you give itMath.max returns the bigger of the two numbers you give it

int max, n;int max, n;max = Integer.MIN_VALUE;max = Integer.MIN_VALUE;for(n = 1; n <= N; n++) for(n = 1; n <= N; n++) {{ num = kbd.nextInt();num = kbd.nextInt(); max = Math.max(max, num);max = Math.max(max, num);}}

Integer.MIN_VALUE is the smallest integer Java knows

Page 47: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

ExerciseExercise

Change this loop Change this loop into a loop to find into a loop to find the the minimumminimum value value

int max, n;int max, n;max = Integer.MIN_VALUE;max = Integer.MIN_VALUE;for(n = 1; n <= N; n++) for(n = 1; n <= N; n++) {{ num = kbd.nextInt();num = kbd.nextInt(); max = Math.max(max, num);max = Math.max(max, num);}}

What’s the name of the largest integer Java knows?(What do you think’s the name of the largest double Java knows?)

What’s the name of the function that finds the smaller of two numbers?

Page 48: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

ExerciseExercise

Change this loop to Change this loop to be data-controlledbe data-controlled stop when negativestop when negative

number is enterednumber is entered

int max, n;int max, n;max = Integer.MIN_VALUE;max = Integer.MIN_VALUE;for(n = 1; n <= N; n++) for(n = 1; n <= N; n++) {{ num = kbd.nextInt();num = kbd.nextInt(); max = Math.max(max, num);max = Math.max(max, num);}}

Enter positive integers below. Enter -1 to end.10 20 30 40 11 12 13 5 -1The largest positive number you entered was 40.

Page 49: Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)

QuestionsQuestions