beesnuts poly
beesnuts poly

Reputation: 11

how to check if specific element not existed in array

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]);
    }
}

Upvotes: 0

Views: 78

Answers (1)

Andreas Wenzel
Andreas Wenzel

Reputation: 25396

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.

Here is a working solution:

#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.

Note that this program does not perform any input validation at all, so that it will likely misbehave if the input is invalid.

Upvotes: 2

Related Questions