Home > Software design >  program not outputting the correct smallest most frequently appeared number
program not outputting the correct smallest most frequently appeared number

Time:11-06

I was making a program in C Language that determines the most frequently appeared number in an array, and also outputting the smallest most frequently appeared number, however I am encountering a bug and I was not sure which part I did wrong.

Here is the example of the program input

2

8

1 1 2 2 3 4 5 5

8

5 5 4 3 2 2 1 1

The number 2 means to create 2 different arrays, the number 8 determines the size of the array. the number afterwards determine the numbers to be put inside of the array, and the program repeats itself by inputting the size of an array etc.

Here is the expected output :

Case #1: 2

1

Case #2: 2

1

The "Case #1: 2" means that the most frequently appeared number appeared 2 times in the array (number 1 2 and 5, each appeared twice in the array), while it prints number 1 because number 1 is the smallest number in the most frequently appeared. and the same goes on for case #2

However, in my program, when I input the second case, it does not properly print the smallest number, and instead just prints nothing. But weirdly enough, if I input a different number in the second array (instead of just the first array in reverse order) it prints the correct smallest number. Here is the example output that my program creates

Case #1: 2

1

Case #2: 2

Here is the code that I made :

#include <stdio.h>
int main(){
 long long t, n;
 scanf("%lld",&t); //masukkin berapa kali mau bikin array
 for(int x=0;x<t;x  ) {
    scanf("%lld",&n); // masukkin mau berapa angka per array
    long long arr[200000]={0};
    long long i, count, freq=0, test=0;
    for(i=0; i<n; i  ){
      scanf("%lld", &count); //masukkin angka ke dalem array
      arr[count]  ;
    }
    for(i=0; i<200000; i  ){
      if(arr[i]>0 && arr[i]>=freq){
        freq=arr[i];
      }
    }
    printf("Case #%d: %lld\n",x 1,freq);
    int min;
    for(i=0; i<200000; i  ){
        if (arr[i] > min){
        min = arr[i];
        printf("%lld",i);
        test=1;
        }  
    }
    printf("\n");
  }
return 0;
}

CodePudding user response:

Your problem is here:

int min;

min is not initialized so when you do if (arr[i] > min){ you have no idea what value min has.

So do

int min = INT_MIN;

That said, you don't really need min. The first arr[i] that equals freq will tell you that i is the smallest number.

Further notice that

long long arr[200000]={0};

is a bad idea. Huge arrays should never be defined as local variables as it may lead to stack overflow. Make it a global variable or use dynamic allocation.

And you should change

arr[count]  ;

to

if (count >= 200000)
{
    // Too big - add error handling
    ...
}
else
{
    arr[count]  ;
}

And you don't need an extra loop for finding freq. Find freq when you get the input.

  • Related