Search code examples
cloopswhile-loopconditional-statementsassert

Infinite while loop issue with a conditional operation function


My code gets stuck in an infinite loop. The current number is halved, When the next number is even, the function should execute 2n+1. If odd, it should execute 3n + 1. Once either operation is executed it should halve it again and loop until n = 1. Here is the code:

#include "stdio.h"
#include "assert.h" // ?

long int hailstone(long int k);

int main(void) {
  long int n = 77;
  hailstone(n);
  
  return 0;
}

long int hailstone(long int k) {
  while (k != 1) {
    k = k/2;
    if (k % 2 == 0) {
          k = 2 * k + 1;
          printf("%lu", k);
    
    } else if (k % 2 != 0) {
          k = 3 * k + 1;
          printf("%lu", k);
      
    } else if (k == 1) {
          printf("blue sky!");
    }
  }
}

Would a particular assertion help the compiler execute the code as expected?


Solution

  • As I understand your code

    If the value of n is pair ,you make this n/2 , if not you display 3*n+1

    My code :

    output : 116,58,29,44,22,11,17,26,13,20,10,5,8,4,2,1

    #include "stdio.h"
    #include "assert.h" // ?
    
    
    long int hailstone(long int k);
    
    int main(void)
    {
        long int n = 77;
        hailstone(n);
        return 0;
    }
    
    long int hailstone(long int k)
    {
        while (k != 1)
        {
           if ( k % 2 ==0)
           {
               printf("k = %lu\n",k/2);
               k/=2;   // k=k/2
           }
           else
           {
               k = 3 * k + 1;
           }
        }
            printf("blue sky!\n");
        
    }