I was trying to write a function that checks if an array has consecutive numbers (not necessarily in order), return 0 if not and 1 if yes.
For example:
24, 21, 22, 23 The return value would be 1.
22,22,22 Would return 0.
The problem is that it return 1 for something like:
22,22,22 I could really use the help looking into it.
This is the main function (no need to check it or anything, it's fine):
#include <stdio.h> #include <stdlib.h> /* Function declarations */ void Ex1(); void Ex2(); void Ex3(); void Ex4(); void Ex5(); /* Declarations of other functions */ int f3(int *, int); /* ------------------------------- */ // int main() { int select = 0, i, all_Ex_in_loop = 0; printf("Run menu once or cyclically?\n" "(Once - enter 0, cyclically - enter other number) "); if (scanf_s("%d", &all_Ex_in_loop) == 1) do { for (i = 1; i <= 5; i++) printf("Ex%d--->%d\n", i, i); printf("EXIT-->0\n"); do { select = 0; printf("please select 0-5 : "); scanf_s("%d", &select); } while ((select < 0) || (select > 5)); switch (select) { case 1: Ex1(); break; case 2: Ex2(); break; case 3: Ex3(); break; case 4: Ex4(); break; case 5: Ex5(); break; } } while (all_Ex_in_loop && select); return 0; } and this is the function (UPDATED):
void Ex3() { int n, i, res; printf("Enter the size of the Array: "); scanf_s("%d", &n); int *arr = (int *)malloc(n * sizeof(int)); if (!arr) { printf("ERROR - not enough memory."); exit(1); } printf("Enter an Array >>> "); for (i = 0; i < n; i++) scanf_s("%d", &arr[i]); res = f3(arr, n); printf("res = %d\n", res); free(arr); } int f3(int *arr, int size) { int i, min = arr[0], max = arr[0]; for (i = 1; i < size; i++) { if (arr[i] < min) min = arr[i]; if (arr[i] > max) max = arr[i]; } int *CounterArray = (int *)calloc(max + 1, sizeof(int)); if (!CounterArray) { printf("ERROR - not enough memory."); exit(1); } for (i = 0; i < size; i++) { CounterArray[arr[i]]++; } for (i = min; i <= max; i++) if (CounterArray[i] == 0) return 0; free(CounterArray); return 1; }
freefunction call afterreturnstatement.main()is irrelevant — you only need a single callEx3()in it.f3()you break the array bounds withfor (i = 1; i <= size; i++)OK you set the min and max from element[0]but the upper bound breaks.