Lesson 9: For / While loop

[spoiler title=”Lesson Video”]
Direct Download of Video (For mobile / offline viewing)(right click > save target as)


[/spoiler]

[spoiler title=”Lesson Source Code”]

[/spoiler]

Homework: https://beginnerscpp.com/forums/index.php/topic,62.0.html



Loops
The over-arching theory of loops is that sometimes you’re going to have a set of data, which will need to be iterated through and have actions performed on each member. You can use if statements to qualify what happens to each item, but the loop itself ensures that every item in a set is able to be iterated through.


While
While loops are the simplest of the loops that we’re going to be discussing. The syntax is exactly the same as an if statement.

One of the catches of using an while statement is that there needs to be some kind of a control in place or the loop will run endlessly. The most common way to see a while loop implemented for beginners is by incrementing a number. Here’s an example of how someone would do that:


Do_While loops
These loops weren’t actually covered in the videos, as I don’t feel that they are as important in theory as other loops. The purpose of a do_while loop is to ensure that something happens at least once. Typically, in programs you might see a do_while used to make a user enter a number within a certain range. For example:

As you can see, the above code took 3 lines, instead of 5. Let’s break down what exactly happened in this for loop. For loops are often broken into 4 basic parts:

  1. for statement –the literal use of the word “for” at the start of the line
  2. Initialization –This part allows you to create a variable or assign an existing variable a new value. An example of this is int counter = 0; as above.
  3. Conditional –This is the statement that must remain true (like a while) for the loop to continue running.
  4. Increment –This statement typically (although it doesn’t have to) brings your initialized variable closer to satisfying the conditional.

Here is one more example of for loops

It is strongly recommended that you review this lesson and familiarize yourself with loops in some depth, as the next lesson will be VERY challenging as it deals with nested loops.