Pre-Lecture Prep and Pre-Quiz

Please read up to "in class work" complete the pre-quiz before attending lecture.

Announcements

Learning Objectives and Outcomes

In this lecture, you will...

By the end of this lecture, you should be able to...

For Loops

A for loop is a special type of while loop with a different syntax. The syntax is most easily explained by an example. Compare these two pieces of code:

// 1 - initialize
byte count = 0; 

// 2 - check condition
while (count < 4){

	//execute code
	Serial.println(count);
	//3 - increment
	count++;
}
// 1 - initialize; 2 - check; 3 - increment
for (byte count = 0; count < 4; count++){
	Serial.println(count);
}

In the while loop case, the variable count is set to 0 (step 1 - initialize). Then the condition count < 4 is checked (step 2 - check condition), and the loop counts 0, 1, 2, 3, incrementing by one each time (step 3 - increment). The for loop implementation is just a condensed version of the code on the left; the initialization step, the check condition step, and the increment step are all on a single line at the top. The initialization step always happens first, the condition is always checked each iteration of the loop, and the variable is always incremented at the end of the loop.

We can use whichever values we want to the initialization, check, and increment stages. We can potentially even leave some of them blank! For example, to count down from 10 to 0:

for (int count = 10; count >= 0; count--){
	Serial.println(count);
}
// how to do this as a byte?
// ideas:
// - use an extra condition (check when we get to zero to make sure we don't dec)
// - count >= 255 (not quite)
// - count < 255 (also works, use equivalent of -1 for number of bits)
// - for (byte count = 11; count >=1; count--) {Serial.println(count-1)} <- easiest
for (int count = 10; count >= 0; count--){
	Serial.println(count);
}

<aside> ❓ Why did we need to switch to using an int? How could this be implemented using a byte?

</aside>