I am having trouble with this algorithm. I was wondering if anyone could offer assistance and also an explanation.
Describe an algorithm that, upon input of n real numbers, a1,a2,...,an, and another number, x, determines how many ai are equal to x.
I am totally lost. From reading my book, I am thinking that this is the answer.
Step 1. Set C=0
Step 2. For i=1 to n, if ai=x replace C by C+1
Step 3. Output C
Any help is appreciated.
Your algorithm is correct.
I don't know why you are totally lost, though. Programming a computer is not really different from being able to solve problems in real life.
A long time ago I had a programmable calculator. Writing programs in it was really easy. I would first do some calculation myself ("by hands"), on some particular input. Then I had to remember the sequence of keys I pressed; that sequence was in fact the program. After I recorded the program, I could run it on any input.
So, for me the first step in writing an algorithm is to imagine myself in place of the computer. Or, rather, I imagine computer objects (variables, lists, pointers) using some visual imagery. For example, I may think of variables as physical boxes where numbers are stored. Or, in the case of your problem, I could imagine that there is a sequence of boxes in a storehouse, with every box having a label that says what's inside. The manager asks me to count the number of boxes with Wii's. Let's forget for a moment about the computer; could I do this task? Could I do it repeatedly, without guessing, as opposed to having good luck one time and possibly bad luck next time? Could I explain how to do this to another person? If I think I could do it, I would record the sequence of steps that I perform. What is left is only to make a translation from physical objects to computer concepts. Then I would get the same algorithm as you wrote.
Thank you very much for that explanation. That is a very helpful way of looking at it.
Originally Posted by emakarov