fork download
  1. #include <stdio.h>
  2. #include <stdbool.h>
  3.  
  4. void printRange(int sortedArray[], int len) {
  5. int i, current, next, printStart, printEnd, startIndex = 0;
  6. bool print = false;
  7.  
  8. for (i = 0; i < len; i++) {
  9. printStart = sortedArray[startIndex];
  10. printEnd = sortedArray[i];
  11.  
  12. current = sortedArray[i];
  13. next = sortedArray[i + 1];
  14.  
  15. if (next - current != 1) {
  16. startIndex = i + 1;
  17. print = true;
  18. }
  19.  
  20. if (print) {
  21. if (printStart - printEnd == 0) {
  22. printf("%d,", printStart);
  23. } else {
  24. printf("%d-%d,", printStart, printEnd);
  25. }
  26. print = false;
  27. }
  28. }
  29. }
  30.  
  31. int main() {
  32. int sortedArray[] = { 1, 3, 4, 5, 7, 8, 9 };
  33. int len = sizeof(sortedArray) / sizeof(sortedArray[0]);
  34. printRange(sortedArray, len);
  35. return 0;
  36. }
  37.  
Success #stdin #stdout 0s 2156KB
stdin
Standard input is empty
stdout
1,3-5,7-9,