0

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.

3
  • 2
    Your 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? Commented 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.... Commented 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). Commented Nov 6, 2009 at 21:44

4 Answers 4

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for showing a generalized version. But please change int pSize to size_t pSize.
2

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.

Comments

0

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

Comments

0
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

The terminating condition in the for loop should be i < sizeof(arr) / sizeof(int)
I don't think he will get his master thesis by my answer, but maybe he learns something of it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.