Dividing A Specified Number Into Almost Equal Groups

The other day I was playing around and required a quick and dirty C program which could be used for arrays or bucketing - it divides a value by a specified number and creates groups or teams.

Here it is in both a for loop and a while loop.

  1. #include /<stdio.h/> //stdio and stdlib seem to get filtered
  2. #include /<stdlib.h/>
  3.  
  4. /**
  5.  * Example program that takes a number, divides it by another specified
  6.  * number of your choice and then adds on the remainder (if it exists)
  7.  *
  8.  * To compile: gcc Whateveryoucallthis.c -o looper
  9.  */
  10. int
  11. main(int argc, char **argv) {
  12.        
  13.         int number = 39;
  14.         int divisor = 7;
  15.         int remainder = number % divisor;
  16.         int multi = number / divisor;
  17.         int fixed = number - remainder;
  18.        
  19.         printf("Number: %d, fixed: %d, multi: %d, remainder %d\n",number,fixed,multi,remainder);
  20.        
  21.         printf("For loop example \n");
  22.        
  23.         // Initalize counters
  24.         int start = 0;
  25.         int end = 0;
  26.         int i = 0;
  27.         int x = 0;
  28.        
  29.         for(i = 0; i< divisor; i++) {   
  30.  
  31.                 x++;
  32.                 start = end;
  33.                 end = x*multi;
  34.                
  35.                 if( i == 6) {
  36.                         end = end +remainder;
  37.                 }
  38.                 printf("%d.) start %d, end %d\n",i,start,end);
  39.         }
  40.        
  41.         printf("While loop example \n");
  42.        
  43.         // Reset counters
  44.         start = 0;
  45.         end = 0;
  46.         i = 0;
  47.         x = 0;
  48.        
  49.         while(i < divisor) {   
  50.  
  51.                 i++;
  52.                 start = end;
  53.                 end = i*multi;
  54.                
  55.                 if( i == divisor) {
  56.                         end = end +remainder;
  57.                 }
  58.                 printf("%d.) start %d, end %d\n",i,start,end);
  59.  
  60.         }
  61.        
  62.        
  63.         return 0;
  64. }

Blog tags: 

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.