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?
CodePudding user response:
Your code is overly complicated and wrong.
It basically boils down to this (try it):
long int hailstone(long int k) {
while (k != 1) {
k = k/2;
printf("k divided by 2: %lu\n", k);
if (k % 2 == 0) {
k = 2 * k 1;
printf("k after k = 2 * k 1 %lu\n", k);
}
}
}
Output:
k divided by 2: 38
k after k = 2 * k 1 77
k divided by 2: 38
k after k = 2 * k 1 77
k divided by 2: 38
k after k = 2 * k 1 77
...
Just applying the definitions blindly:
#include <stdio.h>
void hailstone(long int k);
int main(void) {
long int n = 77;
hailstone(n);
return 0;
}
long int func(long int k)
{
if (k % 2 == 0)
return k / 2;
else
return 3 * k 1;
}
void hailstone(long int k) {
while (k != 1)
{
printf("k = %d\n", k);
k = func(k);
}
}
CodePudding user response:
Would a particular assertion help the compiler execute the code as expected?
No
Asserts are used to STOP execution for certain events.
CodePudding user response:
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;
}
}
if (k == 1)
{
printf("blue sky!\n");
}
}
CodePudding user response:
long int hailstone(long int k) {
while (k != 1) {
k = k/2; // k is 38
if (k % 2 == 0) {
k = 2 * k 1; // k is 77, and go on while again, that's why loop infinity
printf("%lu", k);
} else if (k % 2 != 0) {
k = 3 * k 1;
printf("%lu", k);
} else if (k == 1) {
printf("blue sky!"); // will never reach because when k==1 then k%2!=0
}
}
}