Let's take a look at several algorithm examples, while solving various problems.
The procedure is:
1. Enter the two numbers in the variables N and M.
2. Sum them and save the result in the variable sum.
3. Output the result.
A number is even if it can be divided by 2 without remainder. Such numbers are 2, 4, 6, 8.. and so on. The numbers that leave a remainder are called odd. They are 1, 3, 5, 7.. and so on.
In programming we find the remainder of a division with the operator %. Also we use the double equals “==” to compare values for equality. You can read more about operators in the math operators lesson.
Summing two numbers was easy – the calculation was one block from the flow chart. But how about 50? Do you have to write 50 blocks to solve this task? Happily – no.
You can automatize this process by repeatedly incrementing the value of a variable and checking it every time if it exceeds the last value – 50. Then sum that number every step and... there you go! This construction is called loop. Learn more about loops in the lesson from the beginners programming tutorial.
A very common algorithm example from mathematics is the long division. Rather than a programming algorithm, this is a sequence that you can follow to perform the long division. For this example we will divide 52 by 3.
The result from
3. is 20. The next digit in 52 is 2. So.. 20 + 2 = 22
1. 22 / 3 = 7
2. 17. Since this is the last digit 17 is the final answer. If you continue the division you will find the fractional part.
Let's go a step higher and continue with some more complex algorithm examples.
Given is the array prices with 100 elements(prices). The problem consists of
1. Find the highest price in the array
2. Reduce that price
For part 1 we iterate through the whole array, starting with index 0. We compare the first value with the next prices and when a greater price is found, we remember the new value in the variable “max” and its location in “maxIndex”.
Once we compared all elements of the array we have to reduce the max price with 10%. This is the same as multiplying it by 0.9, so that is what you see in the algorithm.
The last note here – we use short version of the multiply-assign
prices[maxIndex] *= 0.9 is the same as
prices[maxIndex] = prices[maxIndex] * 0.9
The last of the algorithm examples will be more branched. As you will see, we will need to do several consecutive examinations and this will spread our flow chart a bit.
- Algorithm definition – definition and explanation