Lesson 4: Recap and algorithm examples

In this lesson I’ll make a recap of the unit. You will see two algorithm examples of everything we studied in this unit together. I will focus on how to use algorithms, with conditionals and repetitions, to solve problems.

Also, at the end of the lesson I will give a problem for you to solve it on your own. That way you will be able to verify if you learn the basics of algorithms. In case you cannot solve it, you must not worry, you can post a comment and will definitely come back to you with guidance.

The approximate time to complete this lesson is 15 minutes.

Welcome back!

In this lesson, we will continue studying algorithms. So far, we studied algorithms definitions and examples, what are conditionals and how to use them and, we studied what are loops and how can we use them.

Always remember that we use algorithms to solve problems. Any time that you want to create an algorithm you must have the end in mind from the beginning. In other words, what problem you are trying to solve.

Now we are going to see two more examples on how we can use algorithms to solve specific problems.

As a first example, we have to create an algorithm to calculate the factorial of a given number.

The factorial of a number n is equal to 1*2*3*…*n.

So, let’s start creating our algorithm. First, we will represent the algorithm using a flow diagram.

As we studied before, we can create an algorithm using a flow diagram or a pseudo-code.

We will use both in this lesson and we are going to start by the flow diagram.

algorithm examples: using loops to calculate the factorial of a number

First, we have the start symbol.

Then we have to input a number. This is the number we will use to calculate the factorial. We also will use 2 extra variables. In this case, i=1 as a loop control variable. Another variable is fact=1, we will use it to store the multiplication of the numbers from 1 to number. Remember factorial(n)= 1*2*3*…*n.

The variable i will have the values 1,2,3,…,n. Those are the values we have to multiply to calculate the factorial.