1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Simple line graph snippit in C

Discussion in 'C' started by hobbyist, Apr 21, 2012.

  1. hobbyist

    hobbyist New Member

    Joined:
    Jan 7, 2012
    Messages:
    141
    Likes Received:
    0
    Trophy Points:
    0
    Here's a bit of code to display distributation of grades in form of percentages and a crude line graph. If anyone sees a problem or perhaps has a question, please let me know.

    Code:
    /* simple graph for student averages */
    
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    int main(void) {
    
       int i, j,
           student_avgs[] = { 90, 92, 88, 75, 40,
                              79, 84, 83, 91, 88,
                              88, 65, 72, 77, 90,
                              83, 85, 76, 68, 81,
                              96, 59, 64, 79, 88 },
    	   /* one class student averages */
    
           arr_count = sizeof(student_avgs) / sizeof(student_avgs[0]), 
    	   /* number of students in one class */       
    
           ranges[10] = { 0 };
    	   /* temp array to hold distribution of averages */
    	   
       for(i=0; i < arr_count; ++i) /* compute range for each student in class */
          student_avgs[i] >= 90 ? ranges[9]++ :
    	  student_avgs[i] >= 80 ? ranges[8]++ :
    	  student_avgs[i] >= 70 ? ranges[7]++ :
    	  student_avgs[i] >= 60 ? ranges[6]++ :
    	  student_avgs[i] >= 50 ? ranges[5]++ :
    	  student_avgs[i] >= 40 ? ranges[4]++ :
    	  student_avgs[i] >= 30 ? ranges[3]++ :
    	  student_avgs[i] >= 20 ? ranges[2]++ :
    	  student_avgs[i] >= 10 ? ranges[1]++ : ranges[0]++;
    
       puts("distribution of average grades\n==============================\n");
       
       for(i = (sizeof(ranges) / sizeof(ranges[0])) - 1; i >= 0; --i) {
          
          printf("%2d - %3d: (%2d students %2.0f%% ) ", 
    	     i * 10, (i + 1) * 10, 
    		 ranges[i], 
    		 ranges[i] / (float)arr_count * 100); /* per of students in each range 
    		                                         integer div requires cast (float) */
    	  for(j=0; j < ranges[i]; ++j)
    	     putchar('#'); /* output one # for each student in range */
    
          putchar('\n');
       } 
       
       printf("\n%d students in class\n", arr_count);
       getchar();
    
       return 0;
    }
     

Share This Page