On this mastery I will show you what a FOR loop in C++ is and how to use it.

A FOR loop is a type of loop which allows you to give specific conditions to it, and then repeat when this conditions are true. 
A for loop consists of four parts: an initializer (declaration of what happens first to the variable; it only happens once), a condition (evaluates and proceeds with the code if its true, if not it will stop), an incremet (this updates the variable after the code is completed and increments the variable), and the statement (what will happen when the conditions are true). In a flow chart, for loops look something like this:

Now, let’s create a program which displays the factorial of a given number. Factorial is the result of the multiplication of all numbers starting from 1 to the number you want to know its factorial. For example, 5 factorial is 1 x 2 x 3 x 4 x 5 which = 120. 

Let’s make that program using a for loop, so do as follows:

  1. Create two variables, x which will be the user input and another one called factorial which equals to 1. 
  2. Ask the user for the variable.
  3. Make the for loop. The for loop has to have the four parts in order to be complete. Initialize your variable a in 1, then condition it with a less or equal to the user input (this is where the loop will know when to stop), mark the increment, and write the statement, which is factorial equals to factorial multiplied by a.
  4. Print the result.

Your code should look something like this:

Now lets test the program with factorial 5, which should be equal to 120.

That’s it, you now know how to use a for loop, congrats!

CC BY 4.0 Mastery 20 by Omar Peza is licensed under a Creative Commons Attribution 4.0 International License.