Friday, August 19, 2005

resolving a set of integers

The following code resolves a series of numbers (ex 1,3,4,5,6,7,9) into a range 1,3 – 7,9

 

 

 

#include <stdlib.h>

#include <stdio.h>

#include <ctype.h>

 

 

int main(int argc, char*argv[])

{

   int i=0;

   int seriesStart=0;

   int curNum=0,prevNum=0;

 

 

   if(argc < 1)

      exit(EXIT_SUCCESS);

 

 

   printf("\n");

 

 

   seriesStart = prevNum = atoi(argv[1]);

 

 

   printf("%d",seriesStart);

 

 

   for(i = 2; i < argc; i++)

   {

         curNum = atoi(argv[i]);

 

 

         if(curNum != (prevNum+1))

         {

                if(seriesStart != prevNum)

               printf(" - %d,",prevNum);

            else

               printf(",");

 

 

                seriesStart = curNum;

            printf("%d",seriesStart);

 

 

     }

       prevNum = curNum;

   }

 

 

   if((seriesStart != curNum) && (curNum == prevNum))

           printf(" - %d",curNum);

 

 

  return 0;

 

}

 

 

Pradyut
http://pradyut.tk
http://spaces.msn.com/members/oop-edge/
http://groups-beta.google.com/group/oop_programming
India

 

No comments: