Zach Smith
Zach Smith

Reputation: 5674

How to find a certain number in an Array C Programming?

If I have an array and I need to display how many times the number '12' is created. I'm using a function to go about this. What resources should I look into to find how to exactly tease out this one number and display how many times it is in the array/list? Any help would be greatly appreciated.

Upvotes: 0

Views: 1804

Answers (4)

GManNickG
GManNickG

Reputation: 503865

You can do it by walking through the array, while keeping a tally.

The tally starts at 0, and every time you reach the number you want to track, add one to it. When you're done, the tally contains the number of times the number appeared.

Your function definition would probably look something like this:

int count_elements(int pElement, int pArray[], size_t pSize);

Upvotes: 3

Roalt
Roalt

Reputation: 8440

int arr[20];
int twelves = 0;
int i;

/* fill here your array */


/* I assume your array is fully filled, otherwise change the sizeof to the real length */
for(i = 0; i < sizeof(arr)/sizeof(int);++i) {
  if(arr[i] == 12) ++twelves;
}

After this, the variable twelves will contain the number of twelves in the array.

Upvotes: 0

Charles Salvia
Charles Salvia

Reputation: 53289

Simply create a counter variable, and examine each element in the array in a loop, incrementing the counter variable every time an element is equal to 12.

Upvotes: 2

dwo
dwo

Reputation: 3636

If you have a plain C-array, you have to iterate over all elements in a loop and count yourself with a variable.

Upvotes: 0

Related Questions