Thread: what is wrong with my "counting frequency element in array" code?

  1. #1
    Registered User
    Join Date
    Nov 2016
    Posts
    33

    what is wrong with my "counting frequency element in array" code?

    Greeting C gurus!!

    I'm trying to write a counting frequency elements in array code but it's not working

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    int main()
    {
       int v[]={1,5,6,7,9,3,3,6,1,5};
       int c[10]={0};
        int i;int j;int k;
       for(k=0;k<10;++k) //intialising the counter of my elements to 1
        c[i]=1;
    
    
    
    
    
    
       for(i=0;i<strlen(v);++i)
    
    
       {
           for(j=i+1;j<strlen(v);++j)
           {
        if(v[i]==v[j] && v[i]!='\0')
            {
        c[i]++;
        v[j]='\0';
            }
           }
       }
           for(i=0;i<strlen(v);++i)
           {
                if (v[i]!='\0')
            printf("the elements %d is repeated %d times",v[i],c[i]);
           }
    
    
       }
    I also found another code while searching in internet

    Code:
    #include<stdio.h>
    
    int main(){
    int n, t, i, j, arr[30],len, halflen,flag=0,count=0;
    
    printf("Enter number of elements to insert in an array:");
    scanf("%d",&len);
    printf("Enter elements to insert in an array:");
    for(i=0;i<len;i++){
    scanf("%d",&t);
            arr[i]=t;
    }
    printf("\n");
    
    /*****************************/
    for(i=0;i<len;i++){
            count=1;
    for(j=i+1;j<=len-1;j++){
    if(arr[i]==arr[j]&& arr[i]!='\0'){
                    count++;
                    arr[j]='\0';
    }
    }
    if(arr[i]!='\0'){
    printf("%d is %d times.\n",arr[i],count);
    }
    }
    
    /*****************************/
    getch();
    return0;
    }


    My questions are :

    • what's wrong with my code?
    • the second code use count as counter for the all elements in array, but how can this possible? the value of count is different for every element??
    • what's the use of getchar()?


    Many thanks in advance!!

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    what's wrong with my code?
    What is your compiler telling you? The code should have some warnings or errors, so please post the messages exactly as they appear in your development environment. Hint: strlen() only works with strings.

    the second code use count as counter for the all elements in array, but how can this possible? the value of count is different for every element??
    Look at the placement of count in the outer for() loop and the placement of the print statement.

    what's the use of getchar()?
    I don't see getchar() anywhere in that second snippet.

    Jim

  3. #3
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    Why could you initialize your counts (c array elements) to 1? That doesn't make sense. They need to start at zero.

    What possessed you to use strlen to determine the length of an integer array? That's demonstrates a total lack of understanding of arrays and strings.

    You don't need a double loop since your code is not crap like the second listing you've accosted us with. Just go through the array once and increment the pertinent element in your count array. Couldn't be simpler.


    As for the second code listing, it gets by with only using a single count variable by going through the array multiple times in a double loop, counting (and "erasing", i.e., setting to zero) duplicates. However, this code is total garbage. Please don't grab code from a trash can and post it here. Leave it to rot in peace.

    The getch() at the end is just to "hold the terminal open" which is apparently necessary on some incredibly crappy IDE's.

  4. #4
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    Actually, the second listing (properly written and formatted) does have the property of being able to handle any values except 0. Changing the "erased" value to INT_MIN would be an improvement, allowing it to handle 0.

    Unfortunately the results aren't printed by value or count but by the order in which the values were originally encountered.
    Code:
    #include <stdio.h>
    #include <limits.h>
    
    int main() {
        int a[] = {10001, 0, 13, 10001, -2, 88, -2, 10001, 0};
        int len = sizeof a / sizeof a[0];
    
        for (int i = 0; i < len; i++) {
            if (a[i] == INT_MIN) continue;
            int count = 1;
            for (int j = i + 1; j < len; j++)
                if (a[i] == a[j]) {
                    count++;
                    a[j] = INT_MIN;
                }
            printf("%5d: %3d\n", a[i], count);
        }
    
        return 0;
    }

  5. #5
    Registered User
    Join Date
    Nov 2016
    Posts
    33
    First let me thank you both Jim and Algorithm, every time i'm learning so much things from your posts and yes you are right Algorithm i have still so much confusiong about C principles but please just bear with me

    I've tried to address my code (thanks to you both for the strlen point!!) and here is my new code

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    
    
    int main()
    {
       int v[]={1,5,6,7,9,3,3,6,1,5};
       int c[10]={0};
       int flag[10];
        int i;int j;int k;
       for(k=0;k<10;++k) //intialising the counter of my elements to 1
        {
        c[i]=1;
        flag[i]=0;// the flag is to show if the elements have already been counted 
        }
       for(i=0;i<10;++i)
       {
           for(j=i+1;j<10;++j)
           {
        if(v[i]==v[j] && flag[j]==0)
            {
        c[i]++;
        flag[j]=1;
            }
           }
           if (flag[i]==0)
                {
                  printf("the elements %d is repeated %d times\n",v[i],c[i]);
                }
    
    
       }
    
    
    
    
       }

    the results i'm getting are totally wrong even though i think that every thing seems right!!


    the results are :
    the elements 6 is repeated 1 time
    the element 7 is repeated 0 time
    the element 9 is repteated 0 time


    • what's wrong with it?
    • Algorithm you said that i shouldn't start from 1 but i have no idea how to do so and still got a correct output?

    Thanks a million!!

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    For starters your code is sorely in need of consistent indentation. Some whitespace might help too. For example:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        int v[] = {1, 5, 6, 7, 9, 3, 3, 6, 1, 5};
        int c[10] = {0};
        int flag[10];
        int i;
        int j;
        int k;
    
        for (k = 0; k < 10; ++k) //intialising the counter of my elements to 1
        {
            c[i] = 1;
            flag[i] = 0; // the flag is to show if the elements have already been counted
        }
    
        for (i = 0; i < 10; ++i)
        {
            for (j = i + 1; j < 10; ++j)
            {
                if (v[i] == v[j] && flag[j] == 0)
                {
                    c[i]++;
                    flag[j] = 1;
                }
            }
    
            if (flag[i] == 0)
            {
                printf("the elements %d is repeated %d times\n", v[i], c[i]);
            }
        }
    }
    Next, generally, variables should have descriptive names, especially if they have a larger scope. Typically only loop index variables and sometimes variables in a mathematical formula reasonably expected to be well known to the reader might be exempt from this. Therefore, you might rename v to say, input or elements, and rename c to counters. Actually, you don't seem to need counters as an array: you only need a single counter that is reused for each element to be counted.

    Now, you have a bug for which your compiler should have warned you if you compiled at a high enough warning level:
    Code:
    for (k = 0; k < 10; ++k) //intialising the counter of my elements to 1
    {
        c[i] = 1;
        flag[i] = 0; // the flag is to show if the elements have already been counted
    }
    Notice that the loop index variable above is k, but you use i to access c and flag.

    Incidentally, you wouldn't need to set flag[k] in this loop if you had zero initialised the array:
    Code:
    int flag[10] = {0};
    Personally, I agree that presetting c[k] to 1 is not very intuitive. You might as well do this in the main counting loop, e.g.,
    Code:
    for (i = 0; i < 10; ++i)
    {
        c[i] = 1;
        for (j = i + 1; j < 10; ++j)
        {
            // ...
        }
    
        if (flag[i] == 0)
        {
            printf("the elements %d is repeated %d times\n", v[i], c[i]);
        }
    Last edited by laserlight; 12-12-2016 at 05:28 AM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    Registered User
    Join Date
    Nov 2016
    Posts
    33
    Great explanation and the code works just fine!!

    My sincere thanks to you Laserlight as well as to Jim and to Algorithm!! You guys are the best!!!

  8. #8
    Registered User
    Join Date
    Nov 2016
    Posts
    33
    Here is the code in which the counter starts 0;
    Thanks to you all again, without you i couldn't have made such progress!!
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    
    
    int main()
    {
       int v[]={1,5,6,7,9,3,3,6,1,5};
       int c[10]={0};
       int flag[10]={0};
    
    
        int i;int j;
       
       for(i=0;i<10;++i)
       {
           for(j=0;j<10;++j)
           {
        if(v[i]==v[j] && flag[j]==0)
            {
        c[i]++;
        flag[j]=1;
            }
           }
     if (c[i]!=0)
                {
           printf("the elements %d is repeated %d times\n",v[i],c[i]);
                }
    
    
       }
    
    
    
    
       }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A "Simple" Array/String Problem. "Help" ASAP needed
    By AirulFmy in forum C Programming
    Replies: 10
    Last Post: 08-19-2015, 04:30 AM
  2. Replies: 3
    Last Post: 03-06-2015, 07:25 AM
  3. Replies: 39
    Last Post: 07-28-2013, 08:24 PM
  4. I'm trying to count the frequency of the phrase "ing"
    By thefreeman1159 in forum C Programming
    Replies: 14
    Last Post: 09-23-2008, 11:58 AM
  5. "CWnd"-"HWnd","CBitmap"-"HBitmap"...., What is mean by "
    By L.O.K. in forum Windows Programming
    Replies: 2
    Last Post: 12-04-2002, 07:59 AM

Tags for this Thread