Example of an algorithm with repeating statements

In the previous tutorials you learnt about simple algorithms and conditional algorithms. In this tutorial you will learn how to write algorithms for problems which involve repetitive actions. Repetitive actions are called Loops in programming. Using these repetitive actions you can do the same thing over and over again depending on some condition. Let’s take a very simple example to understand how to write algorithms for repeating statements or loops

Problem definition

Write an algorithm to print numbers from 1 to 1000 separate by commas ( , )

Let’s understand this problem

It’s important to understand what the above single line problem definition says. It says that you need to print the numbers from 1 to 1000. Additionally it says that you need to print a comma after each number. Can you see some repeating statements in this problem? If not then think for a moment how will you write the algorithm to do this task. First way is that you will simply print 1,2,3,4,5,6,7,… 1000 in a single step? But will this be correct? No. This is not the correct way to do this.

Second way you can think of writing this algorithm is by writing one line each to print the numbers and the commas and create the algorithm. Do you think this is the correct way of doing this task? You will have to write about 1000 to 2000 lines just for your algorithm. And if you end up writing these many lines then it will not be called an algorithm. It will be called garbage because it will be giving a very silly solution for this problem. Therefore this also does not seem to be a good option.

What you have to do is understand how you can write an algorithm for this problem in very less number of lines by using the power of loops. Using the loop or repeating statements will help you do more with very less code.

Let’s look at the algorithm below

Step 1: Take a variable A
Step 2: Set A = 1
Step 3: If A > 1000 then Goto Stop
Step 4: Print value of A
Step 5: Print “ , “
Step 6: Set A = A + 1
Step 7: Goto Step 3

Notice how the lines between Step 3 and Step 7 are being repeated over and over again. The condition for repeating these lines is whether the value of A is less than 1000 or not. If not then we keep increasing the value of A and print it. These step will repeat themselves till the value of A becomes 1000. In Step 3 you can see that when the value of A becomes greater than 1000 we ask the algorithm to stop. Otherwise it will keep repeating these steps.

Learning to write repeating statements or loops in programming will help you in writing programs in less number of lines.

Quick Links



Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..


Login to Open ESchool OR Create your account    Login   SignUp