Hard Procedures and lists

Count with a procedure

Write a procedure countOf (aList, target) that RETURNs how many elements of aList are equal to target.

The program reads how many numbers follow, the numbers, and then a target, and DISPLAYs countOf (nums, target).

Input (one value per INPUT ())Expected output
6 1 2 1 3 1 2 13
3 5 6 7 40

Check runs all 3 tests. Press Run to try the program yourself: a box asks for each INPUT ().

Output


        
        
      

Variables

Show a solution
PROCEDURE countOf (aList, target)
{
   total ← 0
   FOR EACH item IN aList
   {
      IF (item = target)
      {
         total ← total + 1
      }
   }
   RETURN (total)
}

count ← INPUT ()
nums ← []
REPEAT count TIMES
{
   APPEND (nums, INPUT ())
}
DISPLAY (countOf (nums, INPUT ()))

Teachers: sign in as a teacher to add this exercise to a class, graded automatically.

Frequently asked questions

How do I solve this exercise?

Complete the starter code in the editor, press Run to try it (type values when INPUT () asks), then press Check to run every test. Step shows the program line by line with its variables.

Where is the solution?

Under the editor, in Show a solution. Try the exercise first: comparing your code with the solution afterwards is a good way to learn another approach.

AP is a trademark registered by the College Board, which is not affiliated with, and does not endorse, this site.