•

Check out our Community Blogs

Register and join over 40,000 other developers!

### Recent Blog Entries

• phi

I love this community !

• JackJames

hi i am jack i am seo expert jack james would love you to read new post

# Frequency of numbers in an Array

array

7 replies to this topic

### #1 halo2ring

halo2ring

CC Lurker

• New Member
• 8 posts

Posted 28 March 2012 - 01:09 PM

I am trying to write a program where a user enters 10 numbers. Those numbers get stored in an array and accordingly at the end of program, it displays the frequency of a number that was entered . i.e if a user enters
1,2,3,4,1,5,5,6,5,2

it would display the result as:

1 occurs 2 times
2 occurs 2 times
3 occurs 1'nce
4 '' '' '' '' '' ''
5 occurs 3 times

etc etc

this is my code so far

```
#include<stdio.h>
#include <stdlib.h>

int main()
{
int num;
num=0;
int num2;
int arry[50];
int arry2[50];
int count=0;

for(num = 1; num <= 10; num++)
{
printf("Enter the number:(%i) ",num);
scanf("%i", &num2);
arry[num] = num2;
arry2[arry[num]]++;

if (arry2[num]== arry[num])
{
count++;
}

}

for(num=1;num<11;num++)
{
printf("\n%ioccurs %i\n",arry[num],count);

}

system("PAUSE");
return 0;
}

```

I can't seem to figure out the whole counter aspect of it to create the frequency of each number entered. Any suggestions?
• 0

### #2 gregwarner

gregwarner

Obi Wan of Programming

• Expert Member
• 1586 posts
• Location:Arkansas
• Programming Language:C, Java, C++, C#, PHP, Transact-SQL

Posted 28 March 2012 - 01:45 PM

The idea is you build 2 arrays: One to store the actual numbers inputted by the user, and another to store the frequency counts of each number. In fact, unless you need to somehow reproduce the sequence of numbers entered by the user, you don't really even need to store the actual numbers entered, just the frequencies.

Since arrays use integers as indices, you can simply store the frequency of 0's appearing on the input in array index 0. The number of 1's the user typed would be stored in index 1, number of 2's in index 2, and so on. At the end, simply loop through this array and print out the counts.

Like this: (In pseudocode)
```declare an integer array of size 10 called "count".

for i from 0 to 9:
get a number from the input. call this variable "num".
increment count[num].
next i

for i from 0 to 9:
print (i + 1) appeared count[num] times.
next i
```

Of course, I left out a whole lot of range checking, which you will need to do. The line "get a number from the input" should not continue, and should continue prompting for input while this number is less than 0 or greater than 9. (Hint: that sentence tells you how to perform this check.)

That is, assuming of course, that you're only storing the occurrences of the numbers 0 through 9. If you want to allow larger numbers, simply change the bounds of your range checking, and change the size of the array to match.
• 0

Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.
– Douglas Hofstadter, Gödel, Escher, Bach: An Eternal Golden Braid

### #3 halo2ring

halo2ring

CC Lurker

• New Member
• 8 posts

Posted 28 March 2012 - 02:57 PM

I tried this :
```#include<stdio.h>
#include <stdlib.h>

int main()
{
int num;
num=0;
int i=0;
int count[10];

for(i =0; i <= 9; i++)
{
printf("Enter the number:(%i) ",i);
scanf("%i", &num);

count[num]++;
}

for(i=0;i<9;i++)
{
printf("\n%ioccurs %i times\n",i+1,count[num]);
}

system("PAUSE");
return 0;
}

```

but it resulted in: [ATTACH=CONFIG]4668[/ATTACH]

I still have to implement the array for just the numbers themselves but the array for the count itself isn't coming thru.
• 0

### #4 gregwarner

gregwarner

Obi Wan of Programming

• Expert Member
• 1586 posts
• Location:Arkansas
• Programming Language:C, Java, C++, C#, PHP, Transact-SQL

Posted 29 March 2012 - 05:27 AM

I don't see the attachment because it's being moderated. Can you copy and paste the text of the output?

Your 2nd loop uses the wrong comparison operator on the conditional check. It won't run for the last index of the array. Here's a hint: When looping over an array, use this structure:
```for (i = 0; i < [I]array_length[/I]; i++)
```
That way, if your array is of length 10, put a 10 there. It will continue looping from 0 through 9, and fail on 10 since you used the < instead of the <= operator. That's a total of 10 iterations, one for each valid index of the array.

Also, you have an error in this statement:
```printf("\n%ioccurs %i times\n",i+1,count[num]);
```
By specifying i+1, you're skipping over the 1st array element (index 0), so the number of 0's won't be printed. Also, "num" is useless here. You should be using "i" as the array index when accessing the members of 'count'. Remember, when you're inside a loop, you're going to be using the loop iterator variable ('i' in this case) to access your array members.

Keep in mind, you didn't do any range checking like I mentioned. If you type any numbers below 0 or above 9, this will crash due to your program trying to access invalid memory.

If you need to store the sequence of numbers entered by the user, simply make a 2nd array like I mentioned before.
• 0

Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.
– Douglas Hofstadter, Gödel, Escher, Bach: An Eternal Golden Braid

### #5 halo2ring

halo2ring

CC Lurker

• New Member
• 8 posts

Posted 29 March 2012 - 07:17 AM

So as you metioned I used a second array to use the sequence of numbers that would display with the frequency counter.

Also I adjusted the count[num] to the count[i] to access the array numbers. Here is the edited code

```#include<stdio.h>
#include <stdlib.h>

int main()
{
int num;
num=0;
int i=0;
int count[10];
int arry[50];

for(i =0; i < 10; i++)
{
printf("Enter the number:(%i) ",i);
scanf("%i", &num);
arry[i]= num;
count[num]++;
}

for(i=0;i<10;i++)
{
printf("\n%ioccurs %i times\n",arry[i],count[i]);
}

system("PAUSE");
return 0;
}
```

I entered the sequence of 1,2,3,4,5,6,1,1,8,2
Resulting in

1 occurs -195223514 times
2 occurs 1 time
3 occurs 1974966492
4 occurs 1975034107
5 occurs 8687489
6 " " " " 8687313
1 " " " " 2293561
1 " " " " 2293561
1 " " " " 1975033629
8 occurs 1 time
2 occurs 0 times
• 0

### #6 gregwarner

gregwarner

Obi Wan of Programming

• Expert Member
• 1586 posts
• Location:Arkansas
• Programming Language:C, Java, C++, C#, PHP, Transact-SQL

Posted 29 March 2012 - 10:15 AM

First of all, you're not initializing your array elements to zero.
```int count[10] = {0};
```

```    for(i=0;i<10;i++)
{
printf("\n%ioccurs %i times\n",arry[i],count[i]);
}
```

Ok, you're misunderstanding something about what the indices of 'arry' and 'count' actually represent.

arry: sequence of numbers entered. Max 50, according to your declaration: int arry[50]
count: occurrence of the digits entered in the sequence. Range: 0-9, according to your declaration: int count[10]

What this means is that you will allow 50 different numbers to be entered by the user. Each one of these must fall within the range of 0-9.

You only prompt for 10 numbers to be entered. Is this what you meant? If so, arry only needs to be 10 units long.

You incorrectly assume there is a direct correlation between the indices of arry and count in your code that I referenced above. They aren't actually referring to the same thing.

Here's what 'arry' is referring to:

arry:
Index: 0 --> The 1st number entered by the user.
Index: 1 --> The 2nd number entered by the user.
Index: 2 --> The 3rd number entered by the user.
...
Index: 9 --> The 10th number entered by the user (the last one according to your code.)

Now, here's what 'count' is referring to:
count:
Index: 0 --> The number of times the user typed "0" throughout the whole sequence.
Index: 1 --> The number of times the user typed "1" throughout the whole sequence.
Index: 2 --> The number of times the user typed "2" throughout the whole sequence.
...
Index: 9 --> The number of times the user typed "9" throughout the whole sequence.

When you finally print out the results, you want to know how many times the user typed X throughout the whole sequence. That means, you'll want to take a look at the values stored in 'count'.

When you loop over the values of 'count' with 'i', you are getting the answer to this question: "How many times did the user type i throughout the whole sequence?"

When you loop on 'i' from 0 to 9, you get the number of times the user typed 0, the number of times the user typed 1, the number of times the user typed 2, ....... the number of times the user typed 9.

So you see, the values stored in 'arry' are completely irrelevant to figuring out how many times the user typed a number. The only reason we would need to reference 'arry' is if we needed to know in which sequence the user typed the numbers. (In other words, what was the first number the user typed? What was the 2nd number the user typed? ... What was the last number the user typed? This is a completely different question from frequency.

Hope that helps.
• 0

Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.
– Douglas Hofstadter, Gödel, Escher, Bach: An Eternal Golden Braid

### #7 halo2ring

halo2ring

CC Lurker

• New Member
• 8 posts

Posted 29 March 2012 - 12:22 PM

Thanks for all the info . It really helped me understand and implement it accordingly and as per your sugestion, i got the counter to work but had a question about the range. I know i can increase the range of numbers but how do I promote the loop to only input 10 numbers where any number they enter can be from 0-1000 for example.

i.e
```for(i =0; i < 50; i++)
{
printf("Enter the number:(%i) ",i);
scanf("%i", &num);
arry[i]= num;
count[num]++;
}
```

increases the range from 0 to a 50 but loops it 50 times. Anyway I can limit that to 10 without affecting the range ?
• 0

### #8 gregwarner

gregwarner

Obi Wan of Programming

• Expert Member
• 1586 posts
• Location:Arkansas
• Programming Language:C, Java, C++, C#, PHP, Transact-SQL

Posted 29 March 2012 - 02:08 PM

```for(i =0; i < 50; i++)
{
printf("Enter the number:(%i) ",i);
scanf("%i", &num);
arry[i]= num;
count[num]++;
}
```

increases the range from 0 to a 50 but loops it 50 times. Anyway I can limit that to 10 without affecting the range ?

That's not quite right. What you've done doesn't affect the range at all. The range and the total number of entries allowed are adjusted completely independently from one another. Here, let me show you:
```// This will allow the user to type a maximum of [COLOR="#FF0000"]50[/COLOR] different numbers. Each number should be in the range [COLOR="#0000FF"]0-9[/COLOR], inclusive.
int count[[COLOR="#0000FF"]10[/COLOR]] = {0};
int arry[[COLOR="#FF0000"]50[/COLOR]] = {0};
```

```// This will allow the user to type a maximum of [COLOR="#FF0000"]10[/COLOR] different numbers. Each number should be in the range [COLOR="#0000FF"]0-9[/COLOR], inclusive.
int count[[COLOR="#0000FF"]10[/COLOR]] = {0};
int arry[[COLOR="#FF0000"]10[/COLOR]] = {0};
```

```// This will allow the user to type a maximum of [COLOR="#FF0000"]100[/COLOR] different numbers. Each number should be in the range [COLOR="#0000FF"]0-49[/COLOR], inclusive.
int count[[COLOR="#0000FF"]50[/COLOR]] = {0};
int arry[[COLOR="#FF0000"]100[/COLOR]] = {0};
```

```// This will allow the user to type a maximum of [COLOR="#FF0000"]10[/COLOR] different numbers. Each number should be in the range [COLOR="#0000FF"]0-1000[/COLOR], inclusive.
int count[[COLOR="#0000FF"]1001[/COLOR]] = {0};
int arry[[COLOR="#FF0000"]10[/COLOR]] = {0};
```

So you see, the maximum size of 'count' determines the range of numbers you will allow to be inputted. The maximum size of 'arry' determines how many different numbers the user will be expected to type.

Of course, you're still not doing any real range checking in your code. You'll need a 'while' loop in there where you scan the numbers to disallow the program to continue until the user has entered a number that falls within your specific range. For instance, as your code stands now, if you declare count[10] and I enter 15, the program will try to increment the value at count[15], but that index doesn't exist. It's somewhere in invalid memory, but C++ will go right ahead and try to access it anyway, causing it to crash. You need to manually check the range for validity before accessing the array.
• 0

Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.
– Douglas Hofstadter, Gödel, Escher, Bach: An Eternal Golden Braid

### Also tagged with one or more of these keywords: array

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download