1 of 51

While Loops & Lists

CSCI 185: Repeating Code

1

2 of 51

Announcements

  1. Tutorial 8 (Drawing program): Submit by tonight
  2. Project Proposal due tonight at midnight. Looking forward to reading them!
  3. Tutorial 9 on Friday (11/10) on looping, art, and animation. Will post it by Wednesday.
  4. Homework 6 due next Monday (11/13) at midnight. We’ll take a look at that in class on Wednesday.

2

3 of 51

Announcements: Your Grade

  • 15% Participation (attendance)
  • 15% Tutorials (drop your lowest grade)
  • 50% Homework & Projects
  • 10% Quizzes (final exam score can replace one quiz score)
  • 10% Final Exam

The final exam is optional:

  • If you don’t take it, your final exam score will become an average of your 3 quiz scores.
  • If you do take it:
    • Your final exam score can replace your lowest quiz score
    • Your final exam score will be whichever is higher: your quiz score or your final exam score

3

4 of 51

Outline

  • Intro to while loops
  • Exercises: While loops
  • Intro to arrays (also called lists) & objects
  • Aside: using random numbers

4

5 of 51

Outline

  • Intro to while loops
  • Exercises: While loops
  • Intro to arrays (also called lists) & objects
  • Aside: using random numbers

5

6 of 51

Repeating Tasks

Once you teach your computer to do something once, it is easy to get it to do the same thing many times. Repeating tasks is one of the things a computer does really well.

  • What are some examples of tasks you repeat over and over?

6

7 of 51

While Loops Metaphors

if (there is a pringle in the can) {

// eat a pringle

}

7

8 of 51

While Loops Metaphors

if (there is a pringle in the can) {

// eat a pringle

}

8

9 of 51

While Loops Metaphors

But do you really want to eat just one?

if (there is a pringle in the can) {

// eat a pringle

}

9

10 of 51

While Loops Metaphors

if (there is a pringle in the can) {

// eat a pringle

}

if (there is a pringle in the can) {

// eat a pringle

}

if (there is a pringle in the can) {

// eat a pringle

}

if (there is a pringle in the can) {

// eat a pringle

}

But what if you don’t know how many pringles are in the can?

10

11 of 51

While Loops Metaphors

if (there is a pringle in the can) {

// eat a pringle

}

// because no one can eat just one

while (there is a pringle in the can) {

// eat a pringle

}

11

12 of 51

While Loops Metaphors

if (there is a pringle in the can) {

// eat a pringle

}

// because no one can eat just one

while (there is a pringle in the can) {

// eat a pringle

}

12

13 of 51

While Loops Metaphors

if (there is a pringle in the can) {

// eat a pringle

}

// because no one can eat just one

while (there is a pringle in the can) {

// eat a pringle

}

13

14 of 51

While Loops Metaphors

if (there is a pringle in the can) {

// eat a pringle

}

// because no one can eat just one

while (there is a pringle in the can) {

// eat a pringle

}

14

15 of 51

While Loops Metaphors

if (there is a pringle in the can) {

// eat a pringle

}

// because no one can eat just one

while (there is a pringle in the can) {

// eat a pringle

}

15

16 of 51

While Loops Metaphors

if (there is a pringle in the can) {

// eat a pringle

}

// because no one can eat just one

while (there is a pringle in the can) {

// eat a pringle

}

16

17 of 51

While Loops Metaphors

if (there is a pringle in the can) {

// eat a pringle

}

// because no one can eat just one

while (there is a pringle in the can) {

// eat a pringle

}

17

18 of 51

...until they’re gone :(

18

19 of 51

19

20 of 51

20

  1. What do you want to repeat?
  2. How long to you want to repeat it?
  3. What do you want to change each time?

21 of 51

21

4

6

3

6

22 of 51

Repeating Tasks

We are going to examine several ways of repeating code:

  • While Loops
  • For Loops

22

23 of 51

Some common scenarios

How do I...

  1. Keep playing the beat over and over again?
  2. Animate my creature?
  3. Search through the data for keywords?
  4. Render all of the photos in a list?
  5. Draw 1,000 creatures?
  6. Play all the notes in a list?
  7. Find the biggest number in a list?

23

24 of 51

While Loops

24

while (some condition is true) {

// execute code block

}

Pseudocode

25 of 51

Print the Statement

How do print this sentence over and over again?

console.log('Hello world!!');

25

00-while-loop-intro

26 of 51

Print the Statement

Solution: How do print this sentence over and over again?

// using the node.js interpreter:

while (true) { // the condition is always true

console.log('Hello world!')

}

26

00-while-loop-intro

27 of 51

How do I make it print 10 times and then stop?

To do this, you have to answer two questions:

  1. How do we figure out how many times the sample has printed?
  2. How do we tell the interpreter to break out of the loop when it’s printed 10 times?

27

28 of 51

How would you do it?

I’m going to run the program again, and you’re going to figure out when it’s printed the sentence 10 times...

...how did you do it?

28

29 of 51

Using variables to track state

  • In computer science, the “state” of a program refers to its current values or contents
  • If we want to know how many times something has happened, we have to use a variable to track the state of the program
  • Each time the loop block executes, we can increment the variable so that we know how long it’s been iterating

29

30 of 51

Using variables to track state

What needs to change to get it to only print 10 times?

while (true) { // the condition is always true

console.log('Hey there! Hope you\'re doing OK!')

}

30

00-while-loop-intro

31 of 51

Using variables to track state

What needs to change to get it to stop after 10 beats?

let counter = 0;

while (counter < 10) {

console.log('Hey there! Hope you\'re doing OK!');counter += 1;

}

31

Initialize iteration variable

Specify halt condition

00-while-loop-intro

32 of 51

Recall: If Statement Syntax

32

if (condition) {

statement 1

statement 2

}

CONDITION�Boolean expression that evaluates to True or False.

BLOCK�If the condition evaluates to True, the block executes. Otherwise, the block is skipped.

33 of 51

While Loop Syntax

33

while (condition) {

statement 1

statement 2

}

CONDITION�Boolean expression that evaluates to True or False.

BLOCK�While the condition evaluates to True, the block will continue to execute over and over. Otherwise, the block is skipped.

34 of 51

Recall: Comparison Operators Evaluate to Either true or false

Comparison operators compare two operands according to a comparison rule and evaluate to either True or False (boolean)�

34

Operator

Description

==

===

If the values of two operands are equal, then the condition becomes true.

!=

If values of two operands are not equal, then condition becomes true.

>

If the value of left operand is greater than the value of right operand, then condition becomes true.

<

If the value of left operand is less than the value of right operand, then condition becomes true.

>=

If the value of left operand is greater than or equal to the value of right operand, then condition becomes true.

<=

If the value of left operand is less than or equal to the value of right operand, then condition becomes true.

35 of 51

Recall: Logical Operators Also Evaluate to Either True or False

Logical operators provide additional ways to determine whether something is true or false:

35

Operator

Description

&&

If both operands are true then the expression evaluates to true. Otherwise, the expression evaluates to false

||

If either or both operands are true then the expression evaluates to true. If both operands are false, the expression evaluates to false

!

If the operand is false than the expression evaluates to true (and vice versa)

36 of 51

Outline

  • Intro to while loops
  • Exercises: While loops
  • Intro to arrays (also called lists) & objects
  • Aside: using random numbers

36

37 of 51

While Loop Exercise: Circles

01-circles

  1. Open circles
  2. See if you can use a while loop to recreate this functionality, where there is only one makeCircle function call that is repeated within a while loop.
  3. Enhancements
    1. Make the column span the entire screen
    2. Make multiple columns
    3. Change the size and the position of the circles

37

38 of 51

Animations are also loops!

  • Animation involves drawing slightly different pictures at regular intervals
  • In p5.js, any statement written inside the draw() function will be put inside a continuous animation loop (02-animation-simple)
  • “Under the hood,” p5.js is probably doing something like this:��while(true) {

draw();

sleep(20);

}�03-animation-while-loop

38

39 of 51

Outline

  • Intro to while loops
  • Exercises: While loops
  • Intro to arrays (also called lists) & objects
  • Aside: using random numbers

39

40 of 51

Lists (AKA “Arrays”)

const myList = ["charlie", "freddie", "lucy"]

//access individual items: �console.log(myList[0]);�console.log(myList[1]);�console.log(myList[2]);

console.log(myList.length); //get length of list

myList.push("jimena"); // append item to bottom

myList.pop(); // remove item from bottom

40

"charlie"

"freddie"

"lucy"

0

1

2

41 of 51

Examples of Lists

  1. A list of image urls (list of strings)
  2. A list of names (list of strings)
  3. A list of Tweets (list of objects)
  4. A list of Songs (list of objects)

41

42 of 51

Objects: Syntax

What is an object?

Objects are a way to group variables and functions into a convenient package.

  • Objects have “keys” (variables) and associated values.
  • You can access the values stored in “keys” using “dot” notation.
  • You can also assign object “keys” to new values using the assignment operator (=).

Example:

const ball1 = {

x: 300,

y: 150,

size: 130

}

42

key

value

43 of 51

Objects: Example

const ball1 = {

x: 300,

y: 150,

size: 130

}

const ball2 = {

x: 40,

y: 3450,

size: 50

}

console.log(ball1.x);

console.log(ball2.x);

console.log(ball2.size);

ball2.size += 0.5;

console.log(ball2.size);

43

44 of 51

Lists of Objects

It is also common to store data in lists of objects. In the following example, what do you think will be printed to the screen?:

const circleData = [

{x: 500, y: 50, d: 100, speedX: 3, speedY: 3},

{x: 300, y: 150, d: 50, speedX: 2, speedY: 0},

{x: 400, y: 400, d: 25, speedX: 0, speedY: 1},

{x: 40, y: 520, d: 80, speedX: 2, speedY: 0},

{x: 140, y: 120, d: 150, speedX: 0, speedY: -0.5},

{x: 350, y: 350, d: 70, speedX: 1, speedY: 1}

];

console.log(circleData[0]);

console.log(circleData[0].speedX);

console.log(circleData[2].d);

console.log(circleData[4].x);

44

45 of 51

Exercises

List of Strings

  • Open the 04-list-of-strings folder in VS Code
  • How could you print all of the names using a while loop?

List of Images

  • Open the 05-photos folder in VS Code
  • How can you output all of the images?

List of Cards

  • Open the 07-list-of-objects folder in VS Code
  • How can you output a card for each game player?

45

46 of 51

Introduction to Homework 6

Creating a Photo Carousel

  • Download the starter files
  • Discuss:
    • how would you implement the forward() function?
    • How would you attach the event handler?
    • How would you implement the showImage() function

46

47 of 51

Outline

  • Intro to while loops
  • Exercises: While loops
  • Intro to arrays (also called lists) & objects
  • Aside: using random numbers

47

48 of 51

The Built-In Random Function

One important concept in computer science is the notion of randomness, which allows a programmer to simulate a number of different possible inputs quickly. Some applications:

  • Position a bunch of shapes randomly on a screen
  • Pick a note out of scale to simulate a jazz riff
  • Simulate a probability distribution
  • Make leaves on a tree have slightly different sizes, shapes, and angles to simulate the randomness of nature

48

49 of 51

Random Function Examples

Q: How do I generate a random number between 0 and 10?

const myNum = Math.floor(Math.random() * 11);

Q: How do I generate a random number between 5 and 15?

const myNum = Math.floor(Math.random() * 10) + 6;

Q: Can’t I just make a function to do this?

function randomInt(min, max) { � // min and max includedreturn Math.floor(Math.random() * (max - min + 1) + min);�}

49

50 of 51

Exercise 08-randomness

Open 08-randomness and take a look at sketch.js (ignore p5.js and utilities.js). Then, see if you can modify the code as follows:

  1. Instead of always using the same fill color, randomly select a color from the colors array above.
  2. Use a loop to draw many random circles.
  3. Consider animating the drawing by putting your logic in the draw() function instead of the setup() function.
  4. Experiment with drawing other shapes (squares, lines, triangles, etc.).

50

51 of 51

Exercise 09-circle-animation: Working with data

  1. Study the circle animation. How does it work?
  2. Convert the 5 variables that control the state of the circle (x, y, d, xSpeed, and ySpeed) into a “circle” object.
    1. This enables us to more conveniently organize our variables if we have lots of variables.
  3. Use a while loop to animate multiple circles by reading the circleData array.
  4. Implement a click event handler that adds new circles to the animation.

51

09-circle-animation