What I try to do is count the frequency of input number but now my problem is it will print an already printed element.
Ex.
Input: 1 3 5 2 3 1
It will output:
1 2
3 2
5 1
2 1
3 2
1 2
Expect ouput:
1 2
3 2
5 1
How do I fix this any suggestion?
#include<stdio.h>
int n = 0;
int number[100] = {0};
int frequency[100] = {0};
int count = 0;
int i = 0, j = 0, k = 0;
int main()
{
scanf("%d",&n);
for(count=0; count<n; count )
{
scanf("%d",&number[count]);
}
///////////////////////////////////////////////
for(i = 0; i<n; i )
{
for(j = 0; j<n; j )
{
if(number[i] == number[j])
{
frequency[k] = frequency[k] 1;
}
}
k = k 1;
}
////////////////////////////////////////////////
for(k=0, i=0; k<n; i , k )
{
printf("%d %d\n",number[i],frequency[k]);
}
}
CodePudding user response:
I think you are newer in programming.
There are some problems in your code, but the best way to learn is to try, fail and try again. So I'd rather not post the solution code, but I want to just give you some hints :)
First: Use the debugger. This is your best friend when you program.
Second: The output is not what you expect. Why? Is seems it does not print the number with its occurrence just once, but the entire array.
Third: Sorting algorithm may save your life in some situations and this is the case ;) Once sorting the input you have something like 1112222233334555 and it is much easier to count the frequency and print the number with its occurrence just once.
Ps. k index is useless because number and frequency are "twin array" which means that frequency[i] has the frequency of number[i]. Just use one index.
Hope this could help :)
CodePudding user response:
The nested loop with 3 different loop counters is completely unnecessary. Also, the final loop is wrong. For example, it does not make sense to limit that loop to n
iterations.
#include<stdio.h>
//numbers must be in the range of 0 to NUM_MAX
#define NUM_MAX 99
//maximum number of numbers that this program can handle
#define MAX_NUMBERS 100
int main()
{
int n;
int numbers[MAX_NUMBERS];
int frequencies[NUM_MAX 1] = {0};
//prompt user for input
printf( "How many numbers? " );
//read amount of numbers from user
scanf( "%d", &n );
//read the individual numbers from user
for( int i = 0; i < n; i )
{
//prompt user
printf( "Enter #%d: ", i 1 );
//read number
scanf( "%d", &numbers[i] );
}
//count the frequencies of the individual numbers
for( int i = 0; i < n; i )
{
frequencies[numbers[i]] ;
}
//print the frequencies
for ( int i = 0; i < NUM_MAX 1; i )
{
if ( frequencies[i] != 0 )
printf( "The number %d occurred %d times.\n", i, frequencies[i] );
}
}
This program has the following behavior:
How many numbers? 6
Enter #1: 1
Enter #2: 3
Enter #3: 5
Enter #4: 2
Enter #5: 3
Enter #6: 1
The number 1 occurred 2 times.
The number 2 occurred 1 times.
The number 3 occurred 2 times.
The number 5 occurred 1 times.