1

This program asks the user for a number of elements and the result tells the frequencies of occurrence of each element. I have marked the question mark using inline text in the code, please help me, I am unable to get the concept here.

#include <stdio.h>

int main()
{
    int arr[100], freq[100];
    int size, i, j, count;

    printf("Enter size of array: ");
    scanf("%d", &size);

    printf("Enter elements in array: ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
        freq[i] = -1; //?? Why is freq said to be -1???

    }

    for(i=0; i<size; i++)
    {
        count=1;
        for(j=i+1; j<size; j++)
        {
            if(arr[i]==arr[j])
            {
                count++;

                freq[j] = 0; //?? How is it checking if some elements going to same as other?? 
            }
        }

        if(freq[i] != 0)
        {
            freq[i] = count;
        }
    }

    printf("\nFrequency of all elements of array : \n");
    for(i=0; i<size; i++)
    {
        if(freq[i] != 0)
        {
            printf("%d occurs %d times\n", arr[i], freq[i]);
        }
    }

    return 0;
}

Please help me.

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
Daksh
  • 27
  • 5
  • 1
    If you want to understand how a program works, usually the best way to do so is to run the program line by line in a [debugger](https://stackoverflow.com/q/25385173/12149471) while monitoring the values of all variables. – Andreas Wenzel Aug 27 '22 at 13:53
  • The entire `freq` array is not necessary, and we did not write the code. But to teach you a little secret: if it is not obvious "*why*" something is in the code, that "*why*" should be added as a comment. I recommend throwing away this code and doing the exercise yourself. – Cheatah Aug 27 '22 at 14:05
  • this code contains unwanted statements... is it working fine? – Exception Aug 27 '22 at 14:30

0 Answers0