开发者

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.


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);


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜