This article was inspired by a problem I met while buying credits for my electricity meter in Lagos, Nigeria.
The printout for the credits comes in 20 characters as shown below:
When you want to enter the figure above into the meter, the meter will ask you for PIN 1, 2, 3, 4, 5. As a result of this, the above number has to be broken down into 5 PINs.
To enter the PINs into my meter, I had to manually separate the printout at every 4 numbers and that was when the idea hit me that this was a good candidate for automation.
In why we program, I go over the fact that we program to automate the solution to a problem. So rather than have a human being carry out a task, a program can be written for a computer to do it.
If we had to write a computer program, we would need to first consider how we would perform the above operation by hand and then breakdown the operation into a series of steps.
The series of steps describing how to carry out the task is called an algorithm.
Algorithms are a sequence of steps which when followed exactly in order will produce the same result.
One area where this is found is in cooking. You can create an infinite variety of meals by altering the ingredients and the order in which they are added while preparing a meal.
So for our problem above, how would we solve the problem? To do this by hand, I counted from the left-hand side and at every 4th number, I placed a comma after it.
So the above printout will now be:
But how would we create an algorithm for this? The steps below will create a generic algorithm for separating at every fourth position.
- Ask the user to input a string
- Find the length of the string
- Loop from 0 to 1 less than the length of the string
- At every 4th position, print out the string on a new line
- When the loop gets to the end, print out the remaining part of the string
Using the algorithm above, can you create a program which when given:
Let me know how you fared in the comments below.