Source of getFrequencyOf.cpp


  1: //  Created by Frank M. Carrano and Timothy M. Henry.
  2: //  Copyright (c) 2017 Pearson Education, Hoboken, New Jersey.

  4: template<class ItemType>
  5: int ArrayBag<ItemType>::getFrequencyOf(const ItemType& anEntry) const
  6: {
  7:         return countFrequency(anEntry, 0);
  8: }  // end getFrequencyOf

 10: // With multiple return statments
 11: template<class ItemType>
 12: int ArrayBag<ItemType>::countFrequency(const ItemType& target,
 13:                                        int searchIndex) const
 14: {
 15:    if (searchIndex < itemCount)
 16:    {
 17:       if (items[searchIndex] == target)
 18:       {
 19:          return 1 + countFrequency(target, searchIndex + 1);
 20:       }
 21:       else
 22:       {
 23:          return countFrequency(target, searchIndex + 1);
 24:       } // end if
 25:    }
 26:    else
 27:       return 0; // Base case
 28: } // end countFrequency

 30: // With one return statement
 31: template<class ItemType>
 32: int ArrayBag<ItemType>::countFrequency(const ItemType& anEntry, int searchIndex) const
 33: {
 34:    int frequency = 0;
 35:    if (searchIndex < itemCount)
 36:    {
 37:       if (items[searchIndex] == anEntry)
 38:       {
 39:          frequency = 1 + countFrequency(anEntry, searchIndex + 1);
 40:       }
 41:       else
 42:       {
 43:          frequency = countFrequency(anEntry, searchIndex + 1);
 44:       }  // end if
 45:    }  // end if
 46:    
 47:    return frequency;
 48: }  // end countFrequency