Tag Archives: #For

#Mastery20

“For” loop is really useful to execute a part of code a specific number of times, this loop works like “while” loop, and it has a very simple structure that basicaly has init, condition, increment and the statement that will be executed the number of times that the user wants.

Here you can see some pictures about how this conditional works:

In the following link you will find a pp that was made by me to teach how to use this loop:

https://drive.google.com/file/d/0B-NM4ghaDXBvOGplRlNTTFlYVjQ/view?usp=sharing

And in this link you will find my c++ code:

https://drive.google.com/file/d/0B-NM4ghaDXBvd0NlMGFUVGhwQk0/view?usp=sharing

Finally, I share with you this link where I found useful information about this loop:

http://www.tutorialspoint.com/cplusplus/cpp_for_loop.htm

Factorial of a number (for loops)

In this case I have uploaded the code to Github here.

What this program does is ask the user for an integer, and then we do what we call sanitizing the entry, or handling exceptions.

The factorial of a number is the result of multiplying the integer numbers before it until we reach 1. This algorithm can’t be done to a negative number, and the factorial of 0 is 1. 

The way that we handled the exception is to be prepared to recieve an input that would make the program fail, so that when it happens our program knows what to do and not only crashes. In this case an if is implemented so that it verifies the given input. If the number is negative, then the program ignores it value and it takes the negative part from it and calculates the factorial of the given number.

After we have prepared for the human error, we now calculate the factorial of the number. For this we implemented a for loop. This loops are used when we know that we must apply a task a certain number of times, or when we want a variable that keeps track of the numberof times a section of code has executed. 

Basically the for loops needs a varaible that we use as counter, and we help ourselves with the range() function. This function returns the value of a series of succesive numbers between the given values, without including the upper limit.

range(0,10) gives us a list of numbers like this:

0 1 2 3 4 5 6 7 8 9

This is used to specify the values that our control variable will take inside the for loop.

This is for my of my