Advertisement
codemonkey

Untitled

Sep 5th, 2011
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1.  
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <assert.h>
  6.  
  7. #define USAGE(err) printf("USAGE: fibo [number]\nError: %s", err)
  8.  
  9. // Typedef heap and stack strings
  10. typedef char* string;
  11.  
  12. // Define functions
  13. int fibo_index(int index);
  14. int fibo(int** output, int limit);
  15. int intLength(int input);
  16.  
  17. // Main function
  18. int main(int argc, const char** args)
  19. {
  20. // Application expects 2 arguments
  21. if(argc != 2)
  22. {
  23. // Build an error message
  24. const char errorMsg[] = "Got %d arguments";
  25. char error[strlen(errorMsg) - 2 + intLength(argc - 1) + 1];
  26. sprintf(error, errorMsg, argc - 1);
  27.  
  28. // Output usage
  29. USAGE(error);
  30. }
  31. else
  32. {
  33. int input;
  34.  
  35. if(sscanf(args[1], "%d", &input))
  36. {
  37. int* range;
  38.  
  39. if(fibo(&range, input))
  40. {
  41. printf("The fibonacci range:\n");
  42.  
  43. int index;
  44.  
  45. for(index = 0; index < input; index++)
  46. {
  47. printf("%d, ", range[index]);
  48. }
  49.  
  50. free(range);
  51. }
  52. else
  53. {
  54. printf("Couldn't use the input to make a fibonacci range");
  55. }
  56. }
  57. else
  58. {
  59. // Build an error message
  60. const char errorMsg[] = "Input was not a valid number: %s";
  61. char error[strlen(errorMsg) - 2 + strlen(args[1]) + 1];
  62. sprintf(error, errorMsg, args[1]);
  63.  
  64. // Print error message
  65. USAGE(error);
  66. }
  67. }
  68.  
  69. printf("\n");
  70. }
  71.  
  72. // Returns the specified index from the fibonacci range
  73. int fibo_index(int index)
  74. {
  75.  
  76. }
  77.  
  78. // Returns the fibonacci range until the specified limit
  79. int fibo(int** output, int limit)
  80. {
  81. // Must be 1 or more
  82. if(limit < 1) return 0;
  83.  
  84. int* range = (int*)malloc(sizeof(int) * limit);
  85. assert(range);
  86.  
  87. int i;
  88.  
  89. // Calculate the range
  90. for(i = 0; i < limit; i++)
  91. {
  92. int value;
  93.  
  94. if(i == 0) value = 0;
  95. if(i == 1) value = 1;
  96. else value = range[i - 2] + range[i - 1];
  97.  
  98. range[i] = value;
  99. }
  100.  
  101. *output = range;
  102.  
  103. return 1;
  104. }
  105.  
  106. // Count the digits by counting the number of times dividing by 10 is necessary
  107. int intLength(int input)
  108. {
  109. // 1 digit
  110. if(input < 10) return 1;
  111.  
  112. else return 1 + intLength(input / 10);
  113. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement