+ All Categories
Home > Documents > 1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1...

1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1...

Date post: 27-Dec-2015
Category:
Upload: abraham-phillips
View: 213 times
Download: 0 times
Share this document with a friend
27
1 CS 177 Week 5 Recitation Slides Loops
Transcript
Page 1: 1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams.

1

CS 177 Week 5 Recitation Slides

Loops

Page 2: 1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams.

2

Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not

covered) Old exams posted

Page 3: 1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams.

3

QUESTIONS???

Page 4: 1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams.

While Loops

Uses repetition to perform a lot of work very fast They look a lot like if statements:

4

int x = 0;if(x < 5){ /*do work using statements*/}

int x = 0;while(x < 5){ /*do work using statements*/ }

When here, finishedWhen here, loop back upAnd test again…

x += 1;

Need to assurea statement isin place to cause the expressionto eventuallyevaluate to false

Page 5: 1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams.

While

Braces are optional for a single statementwhile (i < 10)

sum += i++;

As with ifs, only when the expression is true will the statements within the while block be executed.

The big difference is that when the last statement of a while is executed (if the expression was first true), the expression will be re-evaluated.

5

MUST BE CAREFUL that the condition will depend on a value that changes as the loop progresses or a “break” will be needed (to be discussed).

Page 6: 1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams.

Small contrived exampleboolean value = true;

//program statements…

while (value)

{

System.out.println(“If here, value is true!”);

value = false;

System.out.println(“value can change…”)

System.out.println(“But ONLY matters at the end”);

value = true;

}

6

With value set to true in the endit will loop forever

Page 7: 1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams.

boolean value = true;

//program statements…

int count = 0;

while (value)

{

System.out.println(“If here, value is true!”);

value = false;

//… lots of work

value = true;

count++;

}

7

if (count > 10)

value = false;

This causes the loop to stop…

After how many iterations???i.e. how many times willIf here, value is true!print?

Page 8: 1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams.

Keep multiplying input numbers until a sentinel reached

8

int i = 1;int product = 1;

while( i != 0 ){product *= i;System.out.print(“Enter number: “);i = StdIn.readInt();

}System.out.println(“Product: “ + product);

What is the sentinel here?

Why is i initialized to 1?

So that the while expression will evaluate to true to first enter the loop but also once inside the loop, multiplying by 1 does not affect the final value (as opposed to i = 2).

Page 9: 1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams.

From lecture:

9

int i = 0;double sum = 0;int count = 0;

while( i >= 0 ){sum += i;count++;System.out.print(“Enter number: “);i = StdIn.readInt();

}count--; //fixes extra count for sentinelSystem.out.println(“Average: “ + (sum/count));

Getting the sentinel valuecounted as1 input, so, just calculate with (count-1) to calculate with just the actual values

+(sum/(count-1)));

Page 10: 1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams.

Infinite Loops

int i = 0;

int sum = 0;

while(i <= 10)

{

sum += i;

}

10

This loop will run

forever!

WHY???

How do we fix this?

i++;

This run-time error is a little harderto make when using for loops…

Page 11: 1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams.

for loops

for(init; condition; inc)

{

//statements

}

11

init; //statement

while(condition)

{

//statements

inc; //statement

}

Without increment statements, loops can run forever (unless there is a break… to-be-discussed)but with for loops, you add it right at the beginning.

Page 12: 1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams.

Side by Side

12

int i = 0;

int sum = 0;

while(i <= 10)

{

sum += i;

i++;

}

int sum = 0;

for(int i = 0; i <= 10; i++)

{

sum += i;

}

Page 13: 1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams.

for loops cont.

13

int sum = 0;

for(int i = 0; i <= 10; i++)

{

sum += i;

}

init performed once onlyat beginning of loop.

condition is checked at the beginning and beforeeach next loop iteration

inc is performed at the endof every loop iteration just before condition is rechecked

Page 14: 1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams.

Another Painful Error for Both while and for Loops

int i = 0;

int sum = 0;

while(i <= 10);

{

sum += i;

i++;

}

14

int sum = 0;

for(int i = 0; i <= 10; i++);

{

sum += i;

}

Semicolons placed here will give you a not-so-expected result!!What will happen in the two cases and why???Will be different for each. For loop will have a compilation error since i is declared inside the loop and i is used “outside” of loop…

Page 15: 1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams.

What about

15

int sum = 0;

int i;

for(i = 0; i <= 10; i++);

{

sum += i;

}

What will sum and i be here (no error this time…)?

Page 16: 1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams.

When do we use whiles and when do we use fors?

The answer is not EXACTLY clear cut, BUT there is a general use for each that seems natural:

16

for loops are great for “count controlled” loops; i.e. loops that have a count with them.

Loops from 1 to 100 for instance

while loops are great for “event controlled” loops; i.e. loops that keep iterating until some event has occurred

Loop until program gets correct input for instance

Page 17: 1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams.

From lecture…

The following code will tell you if a number isn’t prime

What’s the problem?

17

int number = StdIn.readInt();

for( int i = 2; i < number; i++){if( number % i == 0 ){

System.out.println(number + “ is not prime.”);

}}

Page 18: 1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams.

cont. By adding a boolean, we can keep track of whether or

not the number is prime

18

int number = StdIn.readInt();boolean prime = true; for( int i = 2; i < number && prime; i++){if( number % i == 0 )

prime = false;}

18

break;

Some might think this would work? (and in a way it does…)

BUT What about when the loop is finished and we want to know LATER if the number is actually prime withoutdoing the loop again??

; i++)

Page 19: 1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams.

do-while

Work just like while loops, only execute statements once before ever checking the condition…

do

{

//statements…

} while(condition);

19

Note here the semicolon, because it is at the endNOT at the beginning, it denotes the end of the statement.

Page 20: 1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams.

Get a password/combination

String combinationForDruidea; //anyone name the movie?

do

{

System.out.println(“Please enter password:”);

combinationForDruidea = StdIn.readString();

} while( !(combinationForDruidea.equals(“1234”) );

//”Amazing, now I’m going to have to change the

//combination on my luggage!”

20

If you know the loop will have to execute the statements AT LEASTonce, then you can use a do-while loop.

Page 21: 1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams.

Side by Side for product

int product = 1;

System.out.print(prompt);

int x = StdIn.getInt()

while(x != 0)

{

product *= x;

System.out.print(prompt);

x = StdIn.getInt();

}21

int product = 1;

int x;

do

{

System.out.print(prompt);

x = StdIn.getInt();

product *= x;

} while(x != 0)

String prompt = “Please enter a number to multiply to the productEnter 0 to quit\n”);

Page 22: 1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams.

import lejos.nxt.*;

public class BasicRobotTest

{

public static void main(String[] args)

{

TouchSensor tSensor = new TouchSensor(SensorPort.S1);

int x = 3;

LCD.drawInt(x, 0, 0);

Sound.beep();

pause(1000);

LCD.drawString("Touch me to", 0, 0);

LCD.drawString("shut me up!", 0, 1);

while (!tSensor.isPressed())

{

Sound.buzz();

}

Motor.A.setSpeed(720);

Motor.C.setSpeed(720);

Motor.A.forward();

Motor.C.forward();

pause(1000);

Motor.A.stop();

Motor.C.stop();

}

}22

int x = 3; LCD.drawInt(x, 0, 0); Sound.beep(); pause(1000); LCD.drawString("Touch me to", 0, 0); LCD.drawString("shut me up!", 0, 1);

while (!tSensor.isPressed()) { Sound.buzz(); } Motor.A.setSpeed(720); Motor.C.setSpeed(720); Motor.A.forward(); Motor.C.forward(); pause(1000); Motor.A.stop(); Motor.C.stop();

Displays a 3 and beeps for a second

Displays “Touch me to shutme up!”

Loop to buzz forever UNTILthe sensor is pressed

Sets the speed of the motorsTells the motors to move forwardat that speed for a secondthen to stop.

Next week’s Lego Lab Starter

Page 23: 1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams.

Last Bit on Loop Errors

BE CAREFUL!! When using loops, you have to follow the syntax and the logic

you want EXACTLY or a lot can go wrong.

23

If you have a loop and the program just seems to sit there, you may have an infinite loop. Infinite Loops can be caused for various reasons…

In cases, your value can be off by 1 if you’re not careful.

Sometimes, a condition can look right but is actually wrong, a loop may never execute…

And the misplaced semicolon can make life miserable!

Page 24: 1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams.

Infinite Loops

int x = 0;

do

{

System.out.println(x);

}while(x < 10)

24

for(int x = 0; x < 10; x++)

{

System.out.println(x);

/*code that make you feel you’ve accomplished something */

x--;

//even more code

}How would we fix either?

What about?

x--

Page 25: 1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams.

Off by 1

int ranThrough = 0;

for(int i = 1; i < 40; i++)

{

System.out.println(i);

ranThrough++;

}

System.out.println(“The loop ran through “ + ranThrough

+ “ times”);

25

What will print here?

What will be the printed value of i on theLAST print statement?

ranThrough is 39!

Page 26: 1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams.

Problems?

for(int i = 1; i >= 40; i++)

System.out.println(i);

26

This will never print anything…. WHY?

Looks right but a logic problem with expression…

int i;

for(i = 1; i <= 40; i++);

System.out.println(i);

What is the problem? What will actually print and how many times?

for(int i = 1; i <= 40; i++);

System.out.println(i);

//gives compilation error!

//i used “outside” loop

//where it was declared.

Page 27: 1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams.

27

Final QUESTIONS???


Recommended