I am making a function that lists an array and says how many times each element appears.
What I have thought of on my own so far is i should loop through the array and t
Code example has been simplified, and has more comments
Here are some suggested steps:
1) assuming int a[]
is sorted (for ease of counting) (ascending or descending, it does not matter).
2) Create separate arrays to keep found results where
first one, num[]
stores the unique value, and
second cnt[]
stores the number of that value found.
3) loop through sorted array.
4) in loop, store unique value, and count of occurrence in keep array.
The sorting routine qsort()
is a concept you will learn later if you are just getting started, (don't get distracted with it for now) but do observe the part of this example addressing your question, look for the comment "Look Here". As described above, it loops through the array, and stores information about when numbers change, and how many of each there are.
Here is a small code example:
Look at the comments to know where to focus attention on setting counters etc.
#include
#define sizea 100 //to make variable declarations easier and consistent
int num[sizea];//unless array has all unique numbers, will never use this many
int cnt[sizea];//same comment
int cmpfunc (const void * a, const void * b);//DISREGARD for now (it just works)
int main(void)
{ //a[] is created here as an unsorted array...
int a[sizea]={1,3,6,8,3,6,7,4,6,9,0,3,5,12,65,3,76,5,3,54,
1,3,6,89,3,6,7,4,6,9,0,4,5,12,65,3,76,5,3,54,
1,9,6,8,3,45,7,4,6,9,0,89,5,12,65,3,76,5,3,54,
6,3,6,8,3,6,7,4,6,9,0,23,5,12,65,3,76,5,3,54,
1,3,6,90,3,6,7,4,6,9,0,5,5,12,65,3,76,5,3,54};
int i, j, ncount;
for(i=0;i
For the array example included, here are the results using this code: