Algorithm

Another pattern which can go unnoticed is the simple statement. Simple statements like ‘pic up an item’, or ‘eat it’ are simply called statements. As stated earlier, we have decided to use a period between two separate statements.


Example 6.2
You will be given a sample of five edible items. Write an algorithm (a procedure, a program) to find if an item can be a sweet dish.


Start algorithm.

for five times execute statements within brackets
{

pic up an item.
eat it.
if the item was sweet execute next statement
mark it as a sweet dish.

}

End algorithm.

This time we knew that there are only five items. So we looped only five times. The statement used is called a ‘for statement’. It is used to loop a specific number of times, the number we know at the start. It has the following format:


for number of times do
steps to be done.


next instruction



Here, ‘steps to be done’ are executed ‘number of times’ specified. number of times, can thus be considered as a condition that specifies number of iterations of the loop. As we will see later this condition can also be complex sometimes.

Also note that we can use the algorithm of example 6.1, for our current example. This leads us to a property of for and while iterative statements. We can convert a for statement into a while statement. (And vice-versa if the number of iterations are known).


Example 6.3
You have been given an urn full of balls of three different colours, say red, blue, and green. You have to segregate these balls according to their colours. You have been given three additional urns R, B, G. Write an algorithm for it.

0 Response to "Algorithm"

Post a Comment