Programming Questions

  • Newest
  • Popular Tags
  • Ask Question
  • Arith Geo Infinite Loop in C
    I finished writing this program and it seems to get caught in an infinite loop or it says 'exited with non-zero status', but when I tested it on my machine it worked just fine. How might this machine be different, or is there a bug I missed? Here is my code: #include <stdio.h> #include <stdlib.h> #define TRUE 1 #define FALSE 0 void ArithGeo(int arr[]) { // code goes here int length=0; //num of ints in array int diff,i,test,arth=TRUE,mult; while(arr[length]!= -1){ length++; } if(length<=1){printf("-1");} //find diff between first two numbers diff = arr[1] - arr[0]; test=diff; //test the rest of the diffs in sequence for(i=1;i<length-1;i++){ test = arr[i+1] - arr[i]; if(diff != test){ arth = FALSE; //if the diff is not always the same then set false } } if(arth == TRUE){ printf("Arithmatic"); exit(1); } mult = arr[1]/arr[0]; //find first mult //test if same for rest for(i=1;i<length-1;i++){ test = arr[i+1]/arr[i]; if(mult != test){ //if not the same then its neither type printf("-1"); exit(1); } } printf("Geometric"); //otherwise is } int main(void) { // disable stdout buffering setvbuf(stdout, NULL, _IONBF, 0); // keep this function call here /* Note: In C you first have to initialize an array and set it equal to the stdin to test your code with arrays. */ int A[] = gets(stdin); ArithGeo(A); return 0; }
    kylecir posted this question on 4/12/17 | arith, geo, infinite, loop
    Answers
  • +
  • 0
  • -
  • while(arr[length]!= -1){ length++; } Im not sure this makes sense. Surely this would cause a memory error as youre eventually accessing memory thats not yours? Maybe your machine protects againts this and nicely gives you a -1 but maybe what they run it on doesnt. Theres probably a better solution to get the length
    Log in to write an answer.