Use of loops with “while” Use of loops with “for”
Mastery 19. Use of loops with “while”… Mastery 20. Use of loops with “for”… And here my video:
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:
- Create two variables, x which will be the user input and another one called factorial which equals to 1.
- Ask the user for the variable.
- 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.
- 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!
Hi again there! Here is my video for #Mastery19 & #Mastery20:
Hello everybody, this post is to explain the basic use of while loops and for loops. While is a loop that will be performed if the conditions inside its definition is true. Yes, you are right… again boolean value. If the condition inside the while returns the value true then the code under the while […]