Reputation: 15
I'm a beginner in C++ and the code is part of an assignment. I'm having problem with the program infinite looping. I know the infinite loop occurs in sequence(n), but I don't understand why it is infinite looping. I've evaluated the process step by step but I seem to be missing something.
Ex: of a problem I am facing: n = 7, sequence prints: 7 22 22 22 22 22
#include <cstdio>
using namespace std;
// next(n) returns the value that follows n in the hailstone sequence.
// Example: next(7) = 22, next(22) = 11, etc.
// Since the hailstone sequence ends at 1, n is required to be > 1.
int next (int n)
{
while (n > 1)
{
if (n%2 == 0)
{
return n/2;
}
else
{
return 3*n+1;
}
}
return 1;
}
// sequence(n) executes next(n) in a loop to print the next integer(s)
// in the hailstorm sequence, starting from n until ending with 1.
void sequence(int n)
{
int nextNum = n, x = next(nextNum);
while (nextNum > 1)
{
printf("%i", nextNum);
nextNum = x;
break;
}
if (nextNum == 1)
{
printf("%i", 1);
}
}
int main()
{
int n;
printf("Enter n: ");
scanf("%i", &n);
sequence(n);
return 0;
}
Upvotes: 1
Views: 6498
Reputation: 98
Firstly as @NPE suggests about the not changing value of nextNum in while loop. You can simply assign value of nextNum directly without using a variable x.
Second thing is that Why are you using break statement in the loop. You can write as follows:-
while (nextNum > 1)
{
printf("%i", nextNum);
nextNum = next(nextNum);
}
Now nextNum will have new value in every iteration of loop. Hope this will help you. :-)
Upvotes: 0
Reputation: 40
You could actually use this code instead which generates the hailstone sequence.
#include <cstdio>
using namespace std;
int main()
{
int n;
printf("Enter n: ");
scanf("%i", &n);
printf("%i\t",n);
while(n>1)
{
if(n%2==0)
{
n=n/2;
}
else
{
n=(3*n)+1;
}
printf("%i\t",n);
}
return 0;
}
Upvotes: -1
Reputation: 500673
Consider the following:
while (nextNum > 1)
{
printf("%i", nextNum);
nextNum = x;
break;
}
Here, x
never changes. Consequently, nextNum
also never changes. This makes the loop either to execute indefinitely or not at all.
Did you mean to call next()
inside the body of the loop, not outside?
Also note that while (n > 1)
in next()
is a no-op, given that the body of the loop always returns
.
Upvotes: 2