简体   繁体   中英

I am unable to get the basic concept in this c program using for loop

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.

 freq[i] = -1;

Here you can assign anything except 0 to overwrite the garbage values present in an array.

Why can't you take 0?

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

Here you've added this condition where freq[i] will only be updated if it's not 0. This is to make sure you note the frequencies at the first occurrence of every unique element and at the rest of the occurrences of that particular element freq[i] will be 0 to avoid printing multiple times in output.

 freq[j] = 0;

 if(freq[i] != 0)
    {
        printf("%d occurs %d times\n", arr[i], freq[i]);
    }

without the above 2 conditions for input,

total elements = 5, elements = {1,2,2,1,5}

Output:
1 occurs 2 times
2 occurs 2 times
2 occurs 1 times
1 occurs 1 times
5 occurs 1 times

That is not your desired output.

So to conclude it is pretty straightforward. If the element is occurring for the first time at the ith index then only mark update freq[i] to its occurrence, and if the same element occurs again at any jth index then make freq[j] to 0 for the printing purpose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM