Thread: Mode of an array

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    8

    Mode of an array

    I am continuing work on a program for analysis of an entered array, I have got min,max,median and sorting the array working with some input parameters. I cannot seem to get the mode to work, i have attempted some code to do this.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define N 100
    #define MINVAL 0 /* the lowest allowable data value */ 
    #define MAXVAL 100 /* the highest allowable data value */ 
    
    int main()
    {    
    	int a[N] = {0};   
    	int i, j, value, n;   
    	
    		int freq[MAXVAL + 1 - MINVAL] = { 0 }; /* clear the frequency counts to 0. */ 
    		size_t k = 0; /* loop counter */ 
    		int mode = 0; /* for recording the modal value */ 
       
       	printf("Please enter array: To sort Array enter 0  \n");  
       
    	// Upto 100 items can be created in a[i]   
        scanf("%d", &a[0]);    
    	for(i = 1; i < N && a[i-1] < 100 && a[i-1] != 0; i++)      
     	
    	 // Input of the numbers into array a[i]   
      	scanf("%d", &a[i]);  
    	n = i;    
     
     	if(a[n-1] > 100) 
     	{    
      		printf("Number must be between 0 and 100");   
        	exit(1);   
        }   
     	
    	 if (a[n-1] == 0) 
     	{       
    		a[n-1] = 0;     
      		n--;    
      	}    
       
    
    		for(k = 0; k < sizeof a / sizeof a[0]; k++) /* for each datum */ 
    		{ 
    		++freq[a[k]]; /* track the frequency */ 
    		if(freq[a[k]] > mode) /* is this now the most common item? */ 
    		{ 
    		mode = a[k]; /* yes, so log it */ 
    		} 
    		} 
    		printf("The modal value is %d which occurs %d time%s\n", 
    		mode, 
    		freq[mode], 
    		freq[mode] == 1 ? "" : "s"); /* 1 time, 2 time>>s<< */
    
    	
      	printf("Sorted List: ");    
    	 
     	// Simple insertion sort    
    	for(i = 1; i < n; i++) 
    	{        
     		value = a[i];       
    	  	for (j = i - 1; j >= 0 && a[j] > value; j--)        
    		a[j + 1] = a[j];       
    		a[j + 1] = value;    
    	}      
    	
    	//Prints the sorted array    
    	for(i = 0; i < n; i++)       
    	printf("%d ", a[i]);     
    	printf("\n");    
    	printf("Min: %d\n", a[0]);    
    	printf("Max: %d\n", a[n-1]);   
    	printf("Median: %f\n", n % 2 ? a[n/2] : 0.5*(a[n/2] + a[n/2-1]));
    	}
    Your help would be greatly appriciated, i am eager to learn how to accomplish these things.
    Sorry for the messy code.

  2. #2
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    Sorry for the messy code.
    Instead of being sorry, how about you just clean it up. It takes like 10 seconds to fix your indentation, yet it makes the code 10 times more readable. See how much better this looks?
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define N 100
    #define MINVAL 0 /* the lowest allowable data value */ 
    #define MAXVAL 100 /* the highest allowable data value */ 
    
    int main()
    {
        int a[N] = {0};
        int i, j, value, n;
    
        int freq[MAXVAL + 1 - MINVAL] = { 0 }; /* clear the frequency counts to 0. */
        size_t k = 0; /* loop counter */ 
        int mode = 0; /* for recording the modal value */ 
    
        printf("Please enter array: To sort Array enter 0  \n");  
    
        // Upto 100 items can be created in a[i]   
        scanf("%d", &a[0]);        
        for(i = 1; i < N && a[i-1] < 100 && a[i-1] != 0; i++)          
        {   
            // Input of the numbers into array a[i]   
            scanf("%d", &a[i]);  
        }   
        n = i;    
    
        if(a[n-1] > 100) 
        {        
            printf("Number must be between 0 and 100");   
            exit(1);   
        }   
    
        if (a[n-1] == 0)  
        {           
            a[n-1] = 0;    
            n--;    
        }    
    
    
        for(k = 0; k < sizeof a / sizeof a[0]; k++) /* for each datum */ 
        {   
            ++freq[a[k]]; /* track the frequency */ 
            if(freq[a[k]] > mode) /* is this now the most common item? */ 
            {   
                mode = a[k]; /* yes, so log it */ 
            }   
        }   
        printf("The modal value is %d which occurs %d time%s\n", 
                mode, 
                freq[mode], 
                freq[mode] == 1 ? "" : "s"); /* 1 time, 2 time>>s<< */
    
        printf("Sorted List: ");    
    
        // Simple insertion sort    
        for(i = 1; i < n; i++) 
        {             
            value = a[i];            
            for (j = i - 1; j >= 0 && a[j] > value; j--)
                a[j + 1] = a[j];
            a[j + 1] = value;
        }
    
        //Prints the sorted array    
        for(i = 0; i < n; i++)
            printf("%d ", a[i]);
        printf("\n");
        printf("Min: %d\n", a[0]);
        printf("Max: %d\n", a[n-1]);
        printf("Median: %f\n", n % 2 ? a[n/2] : 0.5*(a[n/2] + a[n/2-1]));
    }
    Now what part of your mode calculation isn't working? The code you have looks like it works at a glance, but it is implemented poorly.

    You can find the mode much easier when working with a sorted list. I suggest you calculate the mode from your sorted list (which you already have). Then you just need to go through the list and see what number appears in a row most often.
    bit∙hub [bit-huhb] n. A source and destination for information.

  3. #3
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    Also, your Median calculation is the one that's really broken.
    bit∙hub [bit-huhb] n. A source and destination for information.

  4. #4
    Registered User
    Join Date
    Mar 2009
    Posts
    8
    Calculating the mode does not seem to work, it will output something like "0 is the modal value which occurs 94 times". I will attempt to do it after the sorting the array.
    Update: I have tried finding the mode after sorting the array but it still gives the same error.
    Last edited by MV1; 08-04-2009 at 05:13 PM. Reason: update

  5. #5
    Registered User
    Join Date
    Jun 2009
    Posts
    486
    Code:
    for(k = 0; k < sizeof a / sizeof a[0]; k++) /* for each datum */ 
        {   
            ++freq[a[k]]; /* track the frequency */ 
            if(freq[a[k]] > mode) /* is this now the most common item? */ 
            {   
                mode = a[k]; /* yes, so log it */ 
            }   
        }
    First, you are using mode as a counter of how many times something occurs, but then setting it to the contents of your array index. Pick one and stick to it, both won't work.

    Second, k < sizeof a / sizeof a[0] only works if you define it as a macro, and even then it's better not to

  6. #6
    Registered User GL.Sam's Avatar
    Join Date
    Aug 2009
    Posts
    88
    Second, k < sizeof a / sizeof a[0] only works if you define it as a macro, and even then it's better not to

    Lolwut? Why are you posting misleading things?
    Last edited by GL.Sam; 08-04-2009 at 06:08 PM.
    The only good is knowledge and the only evil is ignorance.
    ~Socrates

  7. #7
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    Yeah, that's not true at all...
    bit∙hub [bit-huhb] n. A source and destination for information.

  8. #8
    Registered User
    Join Date
    Mar 2009
    Posts
    8
    I know the code for finding the mode works if i use it seperatly and use a hardcoded array. The other calculations work fine. I cannot see what is wrong with the code for getting the mode in this context.

  9. #9
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Quote Originally Posted by MV1 View Post
    I know the code for finding the mode works if i use it seperatly and use a hardcoded array.
    Hint: No it doesn't. As has been pointed out, you need to not consider your data and your counts of how often data happen as the same thing. Your mode variable is that count -- you need to find some number k such that a[k] == mode to find what the mode actually is.

  10. #10
    Registered User
    Join Date
    Mar 2009
    Posts
    8
    This is the code i used for finding the mode of a hardcoded array.
    Code:
    #include <stdio.h> /* prototype for printf, and def of size_t */ 
    
    #define MINVAL 0 /* the lowest allowable data value */ 
    #define MAXVAL 42 /* the highest allowable data value */ 
    
    int main(void) 
    { 
    int data[] = { 0, 1, 2, 3, 4, 5, 3, 7 }; /* initialise the data array */ 
    int freq[MAXVAL + 1 - MINVAL] = { 0 }; /* clear the frequency 
    * counts to 0. 
    */ 
    size_t i = 0; /* loop counter */ 
    int mode = 0; /* for recording the modal value */ 
    
    for(i = 0; i < sizeof data / sizeof data[0]; i++) /* for each datum */ 
    { 
    ++freq[data[i]]; /* track the frequency */ 
    if(freq[data[i]] > mode) /* is this now the most common item? */ 
    { 
    mode = data[i]; /* yes, so log it */ 
    } 
    } 
    printf("The modal value is %d which occurs %d time%s\n", 
    mode, 
    freq[mode], 
    freq[mode] == 1 ? "" : "s"); /* 1 time, 2 time>>s<< */ 
    
    return 0; 
    }
    This seems to work but i do not know how to get it to work with the entered array.

  11. #11
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Quote Originally Posted by MV1 View Post
    This is the code i used for finding the mode of a hardcoded array.
    Code:
    #include <stdio.h> /* prototype for printf, and def of size_t */ 
    
    #define MINVAL 0 /* the lowest allowable data value */ 
    #define MAXVAL 42 /* the highest allowable data value */ 
    
    int main(void) 
    { 
    int data[] = { 0, 1, 2, 3, 4, 5, 3, 7 }; /* initialise the data array */ 
    int freq[MAXVAL + 1 - MINVAL] = { 0 }; /* clear the frequency 
    * counts to 0. 
    */ 
    size_t i = 0; /* loop counter */ 
    int mode = 0; /* for recording the modal value */ 
    
    for(i = 0; i < sizeof data / sizeof data[0]; i++) /* for each datum */ 
    { 
    ++freq[data[i]]; /* track the frequency */ 
    if(freq[data[i]] > mode) /* is this now the most common item? */ 
    { 
    mode = data[i]; /* yes, so log it */ 
    } 
    } 
    printf("The modal value is %d which occurs %d time%s\n", 
    mode, 
    freq[mode], 
    freq[mode] == 1 ? "" : "s"); /* 1 time, 2 time>>s<< */ 
    
    return 0; 
    }
    This seems to work but i do not know how to get it to work with the entered array.
    Does it work with the array 0, 7, 1, 2, 3, 4, 5, 3? I'm guessing no.

    If you want mode to be the actual modal value, you should be checking freq[i] > freq[mode].

  12. #12
    Registered User
    Join Date
    Mar 2009
    Posts
    8
    It works for the entered array giving mode as 3 and appear 2 times.

  13. #13
    Registered User
    Join Date
    Jun 2009
    Posts
    486
    I'm sorry, I must have misunderstood the explanation i got about sizeof applied to arrays, it has been a while since then.

  14. #14
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Quote Originally Posted by MV1 View Post
    It works for the entered array giving mode as 3 and appear 2 times.
    Yes but that is sheer luck because you very carefully chose that one particular array. Change it to the array I posted (0, 7, 1, 2, 3, 4, 5, 3) and you will find that the mode is now 7 which appears one time. And anyway I mentioned up above how to fix it too.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  2. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  3. Template Array Class
    By hpy_gilmore8 in forum C++ Programming
    Replies: 15
    Last Post: 04-11-2004, 11:15 PM
  4. Type and nontype parameters w/overloading
    By Mr_LJ in forum C++ Programming
    Replies: 3
    Last Post: 01-02-2004, 01:01 AM
  5. C Filling and Printing a 2-d array
    By Smoot in forum C Programming
    Replies: 3
    Last Post: 11-13-2003, 08:42 PM