4 Replies - 9360 Views - Last Post: 19 March 2010 - 08:23 AM Rate Topic: -----

#1 Nukeman  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 19-March 10

Count Occurrence of a Value in an Array

Posted 19 March 2010 - 06:41 AM

I am trying to read input into an Array and then count the number of occurrences per input value.

For example, if I entered the value '7' three times how would I check for occurrence.
Is This A Good Question/Topic? 0
  • +

Replies To: Count Occurrence of a Value in an Array

#2 Core  Icon User is offline

  • using System.Linq;
  • member icon

Reputation: 774
  • View blog
  • Posts: 5,097
  • Joined: 08-December 08

Re: Count Occurrence of a Value in an Array

Posted 19 March 2010 - 07:12 AM

Here is a piece of sample code that might help you:

int[] myArray = new int[] {1,2,3,4,5,6,2,2};
int counter = 0;
foreach (int i in myArray)
{
      if (i == 2)
      {
          counter++;
      }
}



You can change the array, as well as the verified value to meet your needs.
Was This Post Helpful? 0
  • +
  • -

#3 Nukeman  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 19-March 10

Re: Count Occurrence of a Value in an Array

Posted 19 March 2010 - 07:33 AM

View PostCore, on 19 March 2010 - 06:12 AM, said:

Here is a piece of sample code that might help you:

int[] myArray = new int[] {1,2,3,4,5,6,2,2};
int counter = 0;
foreach (int i in myArray)
{
      if (i == 2)
      {
          counter++;
      }
}



You can change the array, as well as the verified value to meet your needs.


if i changed the "2" in the conditional statement in the foreach loop to myArray.Length would that count each value's occurrence
Was This Post Helpful? 0
  • +
  • -

#4 reaper4334  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 16
  • View blog
  • Posts: 107
  • Joined: 01-November 09

Re: Count Occurrence of a Value in an Array

Posted 19 March 2010 - 07:42 AM

View PostNukeman, on 19 March 2010 - 06:33 AM, said:

if i changed the "2" in the conditional statement in the foreach loop to myArray.Length would that count each value's occurrence


That would just tell you how many times the number that is the length of the array occurds in it

e.g if there are 5 values in your array, it will count how many times the number 5 appears in your array.
Was This Post Helpful? 0
  • +
  • -

#5 MentalFloss  Icon User is offline

  • "ADDICTED"[2:5]
  • member icon

Reputation: 526
  • View blog
  • Posts: 1,397
  • Joined: 02-September 09

Re: Count Occurrence of a Value in an Array

Posted 19 March 2010 - 08:23 AM

You might want to make a method (probably static) that accepts an array parameter and the int parameter to search against.

public static int CountCharacterFrequency(int[] numbers, int search)
{
    // You do this part.
}


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1