Strange behavior in my code

I am trying to find the frequency of each integer in an array but it is showing me only zeros. Below is my code:

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n,t,ans = 0;
    scanf("%d",&n);
    int a[n+1];
    memset(a,0,sizeof(a));
    
    for(int i = 0;i<n;i++){
        scanf("%d",&t);
        a[t] = a[t]+1;
    }
    for(int i = 0;i<=n;i++){
        printf("%d ",a[i]);
    }
    printf("\n");
    printf("ans = %d, %d\n",ans,n-ans);
    
    return 0;
}

Checked with below test case:

34
56 70 70 56 56 56 56 70 56 56 70 70 70 70 70 70 70 56 56 70 70 56 56 56 70 70 56 70 70 70 56 56 70 56

Your problem is you are limiting to n which in this case is 34. However, the input array has values of 70 and 56 which are greater than 34. Hence, you are seeing all zeros set by memset(). Try below code:

#include <bits/stdc++.h>
using namespace std;
#define MAXV 1000
int main() {
    int n,t,ans = 0;
    scanf("%d",&n);
    int a[MAXV+1];
    memset(a,0,sizeof(a));
    
    for(int i = 0;i<n;i++){
        scanf("%d",&t);
        a[t] = a[t]+1;
    }
    for(int i = 0;i<=MAXV;i++){
        printf("%d ",a[i]);
    }
    printf("\n");
    printf("ans = %d, %d\n",ans,n-ans);
    
    return 0;
}

NOTE: MAXV is the maximum possible integer array element. Change it accordingly based on the problem constraints.

2 Likes

@utkalsinha has correctly pointed out the mistake,
You have to calculate frequency of every integer so you can make those numbers as the index of an array and increment everytime you get that number, but should not be limited to 34. I think you are asking this thing only.

Got it. Thanks.

I was as doing the same as you said, but I did the mistake in the loop limit.

//