Chapter 7 - Basic Programming construct - (iii) Loops

Basic Programing Construct (iii): Loops

Loops are yet another programming construct found in all forms of programming. In Arduino, we inherited For, While & do...While loops.

They allow our program to repeat a similar task repetitively 

Loop Types Description
For Loops for loop executes statements a predetermined number of times. The control expression for the loop is initialized, tested and manipulated entirely within the for loop parentheses.
While Loops while loops will loop continuously, and infinitely, until the expression inside the parenthesis, () becomes false.
Something must change the tested variable, or the while loop will never exit known as a run-away loop.
do...while Loops The do…while loop is similar to the while loop. In the while loop, the loop-continuation condition is tested at the beginning of the loop before performed the body of the loop.

   
While loop construct looks almost identical to a if construct, it evaluate the condition before executing the line of codes found within the block.

while (condition) {

     Statements;
}



A For loop executes statements a predetermined number of times. The control expression for the loop is initialized, tested and altered within the for loop construct (cool). It is easy to debug the looping behavior of the structure as it is independent of the activity inside the loop.

for (initialize; condition; manipulate) {

     Statements;
}


Visually, a For loop could be illustrated as such.


Array type variable :

An array is a special type of variable where a consecutive group of memory locations of the same type are bundled together. To refer to a particular location or element in the array, we specify the name of the array and the position number of the particular element in the array.

In C (unlike some other programming language), you can only have a similar variable type in an array collection. The first element has an index of 0 (zero) and is sometimes called the zero index array

type ArrayName[ArraySize];
ArrayName[index] = X;

 Why did we suddenly bring up Array?



 Meet the FlintStone?
The Flintstones is an American Stone-age themed cartoon produced by Hanna-Barbera back in the 1960s. The show follows the lives of Fred, Wilma and Pebbles Flintstone and their pets Dino. 

Wiki: https://en.wikipedia.org/wiki/The_Flintstones

In the Example code, we are going to practice using Loops & also demonstrate the use of loops with traversing an array.

 Todo:

  • Loops is useful when there is a need to generate a series of numbers in a sequence.
    Generate the 1st 30 prime number in the number system.

     Learn to seek for hint yourself (online)
  • What the 26th Prime number in your series? Does your answer match up with everyone else?