Answer the question
In order to leave comments, you need to log in
Why is it exiting the loop?
Super simple program, but I'm stupid: ( Why does it exit the loop?
Purpose:
There is a number a. If it is divisible by 2 without a remainder (that is, even a), then we perform the operation a=a/2,
otherwise (if the number a is not even), perform the operation a=a*3+1, and iterate until a==1 (until the number is equal to 1)
As soon as the number a=1, exit the loop and output his.
int main() {
int i, j, N = 6, res;
for (i = 0; i < N; i++) {
res = 2;
for (j = 0; res == 1; j++) {
if (res % 2 == 0) {
res = res / 2;
}
else {
res = ((res * 3) + 1);
}
printf("\t %d", res);
}
printf("%d %d \n", i, res);
res++;
}
return 0;
}
Answer the question
In order to leave comments, you need to log in
First, the condition for terminating the inner loop is incorrect.
Secondly, you use the res variable in two ways - as the initial value of the sequence, and as the current value of the sequence. Obviously, these must be two different variables.
Thirdly, why do you set 2 as the initial value of the sequence at each iteration of the outer loop? Obviously, this way you will get the same result every time, which is hardly included in your plans.
Fourth - why use for for the inner loop? Enough and while.
Here is the corrected version of your code, think about it:
int
N = 6,
start = 2;
for (int i = 0; i < N; i++) {
int val = start;
printf("\n%d: ", val);
while (val != 1) {
if (val % 2 == 0) {
val = val / 2;
} else {
val = val * 3 + 1;
}
printf("\t%d", val);
}
start++;
}
And what about the ability to debug in the mind (on a piece of paper) or even with a debugger is already completely lost among the younger generations? In my opinion, the answers to such questions are simply harmful for the specialist himself, or for the person who wants to become one.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question