For Loop
 

Step 1 - Build the Project

The 'for' loop iterates ,or counts through, one or more commands. The loop will repeat an exact numbers of times; you tell the loop how many times to run before it 'breaks'. 

Note: If you're uploading this project directly from the website, first click Run on Arduino, complete the upload, then scroll down and click the Connect button in the Serial Monitor. This allows the data to be sent from the Maker Board to the Serial Monitor.

Step 2 - Upload the Code

/* * Learning concept: For * * A sequence of loops which print out, respectively: * numbers from 0 - 9, counting up by one each time, * numbers from 5 to 50 when counting up by 3, and * numbers between 1 and 100 when doubling each time. */ void setup() { Serial.begin(9600); //Start the Serial port //After upload, click the magnifying glass (top right) // to see the serial monitor Serial.println("i from 0 to 10, counting by 1"); //Create variable i; give it a condition; give it a command for (int i = 0; i < 10; i++){ //For loop Serial.println(i); //Print out the value of i delay(500); //Delay for visibility } //Variable i exists only until the for loop is finished // in the next loop, you create a new variable i Serial.println("-----"); Serial.println("i from 5 to 50, counting by 3"); //Create variable i; give it a condition; give it a command for (int i = 5; i < 50; i=i+3){ //For loop Serial.println(i); //Print i delay(500); //Delay for visibility } Serial.println("-----"); Serial.println("i from 1 to 100, doubling each time"); //Create variable i; give it a condition; give it a command for (int i = 1; i < 100; i=i*2){ //For loop Serial.println(i); //Print i delay(500); //Delay for visibility } } void loop() { //For loops run once each in setup, then nothing happens. } // (c) 2016 Let's Start Coding. License: www.letsstartcoding.com/bsdlicense
 

Step 3 - Read the Walkthrough

The “for” loop completes a task a set number of times, then completes and exits.

The first part of the loop is the initializer. Usually, that means you create a variable called “i” that will be thrown away after the “for” loop is complete.

The next part of the loop is the condition, where you determine how long you want the “for” loop to run. This is usually a comparator between your variable and a number.

The last part of the “for” loop creation is the way you want the variable to be modified each time the “for” loop runs. Most of the time, you want the variable to count up by one (i++) or count down by one (i –) each time the “for” loop iterates.

The code between the curly braces is what will run while the “for” loop is iterating.