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.
-
2Your other question gave you the way to iterate through the array, examining numbers. Surely you can think a little bit about how to modify that logic to answer this question?Ken White– Ken White2009-11-06 21:39:34 +00:00Commented Nov 6, 2009 at 21:39
-
yeah, i guess i need to create a variable which equals 12. then have my counter work with the variable to record how many times it was created....Zach Smith– Zach Smith2009-11-06 21:41:46 +00:00Commented Nov 6, 2009 at 21:41
-
By not trying to figure it out yourself, you're only hurting yourself. You won't learn how to do things on your own, and will keep your skills very limited. (Actually, you're hurting more than yourself; if you don't learn any skills but get a job anyway, you're going to write really bad code that someone else will get stuck trying to maintain.) Please try to figure things out first, and then post a question if you can't (including what you've already tried so we know you did so).Ken White– Ken White2009-11-06 21:44:55 +00:00Commented Nov 6, 2009 at 21:44
Add a comment
|
4 Answers
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);
1 Comment
Chris Lutz
+1 for showing a generalized version. But please change
int pSize to size_t pSize.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.
2 Comments
Charles Salvia
The terminating condition in the for loop should be
i < sizeof(arr) / sizeof(int)Roalt
I don't think he will get his master thesis by my answer, but maybe he learns something of it.