For Loops in C++

For Loops in C++

For Loops

Basic Syntax

for (initialization; condition; update){
	statement(s);
}
  • Useful for code that repeats a set number of times
  • Uses a counter to control the loop

Basic Syntax

for (initialization; condition; update)
Initialization
  • Create and initialize variables only at the beginning of loop (ofter a counter)

Basic Syntax

for (initialization; condition; update)
Condition
  • Boolean expression that is checked at the end of each loop iteration.
  • Continue looping as long as this is true

Basic Syntax

for (initialization; condition; update)
Update
  • Increment (or decrement) your loop variables at the end of each loop iteration.

Example

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

__if (i % 2 == 0) {

____Serial.println(i);

Initialize variables

Example

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

__if (i % 2 == 0) {

____Serial.println(i);

Iteration #1: Check condition (even the first time)

  • If true, run loop
  • If false, exit loop

Example

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

__if (i % 2 == 0) {

____Serial.println(i);

Iteration #1: Run loop body (all the code in the loop)

Example

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

__if (i % 2 == 0) {

____Serial.println(i);

Iteration #1: Update the variable

Example

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

__if (i % 2 == 0) {

____Serial.println(i);

Iteration #2: Check condition again

  • If true, run loop
  • If false, exit loop

Updated: