简体   繁体   中英

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

只需创建一个计数器变量,然后循环检查数组中的每个元素,则每当一个元素等于12时就递增计数器变量。

如果您有一个普通的C数组,则必须遍历循环中的所有元素并使用变量来计数。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM